blob: 6a90352582736e1619197ee8c5338530aba30403 [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));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001233 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001235 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 return false; // wait for the command to run
1237 } else {
1238 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1239 }
1240 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001241 if (*dropReason == DropReason::NOT_DROPPED) {
1242 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244 }
1245
1246 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001247 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001249 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1250 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001251 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 return true;
1253 }
1254
1255 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001256 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001257 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001258 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001259 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 return false;
1261 }
1262
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001263 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001264 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 return true;
1266 }
1267
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001268 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001269 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270
1271 // Dispatch the key.
1272 dispatchEventLocked(currentTime, entry, inputTargets);
1273 return true;
1274}
1275
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001276void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001278 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001279 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1280 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001281 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1282 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1283 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284#endif
1285}
1286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001288 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001289 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 entry->dispatchInProgress = true;
1293
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001294 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 }
1296
1297 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001298 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001300 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1301 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 return true;
1303 }
1304
1305 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1306
1307 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001308 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309
1310 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001311 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 if (isPointerEvent) {
1313 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001314 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 } else {
1318 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001319 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001320 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001322 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 return false;
1324 }
1325
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001326 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001327 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001328 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1329 return true;
1330 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001331 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001332 CancelationOptions::Mode mode(isPointerEvent
1333 ? CancelationOptions::CANCEL_POINTER_EVENTS
1334 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1335 CancelationOptions options(mode, "input event injection failed");
1336 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 return true;
1338 }
1339
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001340 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001341 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001343 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001344 std::unordered_map<int32_t, TouchState>::iterator it =
1345 mTouchStatesByDisplay.find(entry->displayId);
1346 if (it != mTouchStatesByDisplay.end()) {
1347 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001348 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001349 // The event has gone through these portal windows, so we add monitoring targets of
1350 // the corresponding displays as well.
1351 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001352 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001353 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001355 }
1356 }
1357 }
1358 }
1359
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 // Dispatch the motion.
1361 if (conflictingPointerActions) {
1362 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001363 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 synthesizeCancelationEventsForAllConnectionsLocked(options);
1365 }
1366 dispatchEventLocked(currentTime, entry, inputTargets);
1367 return true;
1368}
1369
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001370void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001372 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373 ", policyFlags=0x%x, "
1374 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1375 "metaState=0x%x, buttonState=0x%x,"
1376 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001377 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1378 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1379 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 "x=%f, y=%f, pressure=%f, size=%f, "
1384 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1385 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001386 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1387 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1388 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1389 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1390 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1391 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1392 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1393 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1394 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1395 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 }
1397#endif
1398}
1399
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001400void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1401 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001403 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404#if DEBUG_DISPATCH_CYCLE
1405 ALOGD("dispatchEventToCurrentInputTargets");
1406#endif
1407
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001408 updateInteractionTokensLocked(*eventEntry, inputTargets);
1409
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1411
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001412 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001414 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001415 sp<Connection> connection =
1416 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001417 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001418 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001420 if (DEBUG_FOCUS) {
1421 ALOGD("Dropping event delivery to target with channel '%s' because it "
1422 "is no longer registered with the input dispatcher.",
1423 inputTarget.inputChannel->getName().c_str());
1424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 }
1426 }
1427}
1428
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001429void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1430 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1431 // If the policy decides to close the app, we will get a channel removal event via
1432 // unregisterInputChannel, and will clean up the connection that way. We are already not
1433 // sending new pointers to the connection when it blocked, but focused events will continue to
1434 // pile up.
1435 ALOGW("Canceling events for %s because it is unresponsive",
1436 connection->inputChannel->getName().c_str());
1437 if (connection->status == Connection::STATUS_NORMAL) {
1438 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1439 "application not responding");
1440 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 }
1442}
1443
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001444void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001445 if (DEBUG_FOCUS) {
1446 ALOGD("Resetting ANR timeouts.");
1447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448
1449 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001450 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001451 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452}
1453
Tiger Huang721e26f2018-07-24 22:26:19 +08001454/**
1455 * Get the display id that the given event should go to. If this event specifies a valid display id,
1456 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1457 * Focused display is the display that the user most recently interacted with.
1458 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001459int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001460 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001461 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001462 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001463 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1464 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001465 break;
1466 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001467 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1469 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001470 break;
1471 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001472 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001473 case EventEntry::Type::CONFIGURATION_CHANGED:
1474 case EventEntry::Type::DEVICE_RESET: {
1475 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001476 return ADISPLAY_ID_NONE;
1477 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001478 }
1479 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1480}
1481
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001482bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1483 const char* focusedWindowName) {
1484 if (mAnrTracker.empty()) {
1485 // already processed all events that we waited for
1486 mKeyIsWaitingForEventsTimeout = std::nullopt;
1487 return false;
1488 }
1489
1490 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1491 // Start the timer
1492 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1493 "focus to change",
1494 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001495 mKeyIsWaitingForEventsTimeout = currentTime +
1496 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1497 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001498 return true;
1499 }
1500
1501 // We still have pending events, and already started the timer
1502 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1503 return true; // Still waiting
1504 }
1505
1506 // Waited too long, and some connection still hasn't processed all motions
1507 // Just send the key to the focused window
1508 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1509 focusedWindowName);
1510 mKeyIsWaitingForEventsTimeout = std::nullopt;
1511 return false;
1512}
1513
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001514InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1515 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1516 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001517 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518
Tiger Huang721e26f2018-07-24 22:26:19 +08001519 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001520 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001521 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001522 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1523
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 // If there is no currently focused window and no focused application
1525 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001526 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1527 ALOGI("Dropping %s event because there is no focused window or focused application in "
1528 "display %" PRId32 ".",
1529 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001530 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001533 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1534 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1535 // start interacting with another application via touch (app switch). This code can be removed
1536 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1537 // an app is expected to have a focused window.
1538 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1539 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1540 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001541 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1542 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1543 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001544 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001545 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001546 ALOGW("Waiting because no window has focus but %s may eventually add a "
1547 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001548 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001549 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001550 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001551 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1552 // Already raised ANR. Drop the event
1553 ALOGE("Dropping %s event because there is no focused window",
1554 EventEntry::typeToString(entry.type));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001556 } else {
1557 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001558 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001559 }
1560 }
1561
1562 // we have a valid, non-null focused window
1563 resetNoFocusedWindowTimeoutLocked();
1564
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001566 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001567 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
1569
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001570 if (focusedWindowHandle->getInfo()->paused) {
1571 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001572 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001573 }
1574
1575 // If the event is a key event, then we must wait for all previous events to
1576 // complete before delivering it because previous events may have the
1577 // side-effect of transferring focus to a different window and we want to
1578 // ensure that the following keys are sent to the new window.
1579 //
1580 // Suppose the user touches a button in a window then immediately presses "A".
1581 // If the button causes a pop-up window to appear then we want to ensure that
1582 // the "A" key is delivered to the new pop-up window. This is because users
1583 // often anticipate pending UI changes when typing on a keyboard.
1584 // To obtain this behavior, we must serialize key events with respect to all
1585 // prior input events.
1586 if (entry.type == EventEntry::Type::KEY) {
1587 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1588 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 }
1592
1593 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001594 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001595 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1596 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
1598 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001599 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600}
1601
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001602/**
1603 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1604 * that are currently unresponsive.
1605 */
1606std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1607 const std::vector<TouchedMonitor>& monitors) const {
1608 std::vector<TouchedMonitor> responsiveMonitors;
1609 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1610 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1611 sp<Connection> connection = getConnectionLocked(
1612 monitor.monitor.inputChannel->getConnectionToken());
1613 if (connection == nullptr) {
1614 ALOGE("Could not find connection for monitor %s",
1615 monitor.monitor.inputChannel->getName().c_str());
1616 return false;
1617 }
1618 if (!connection->responsive) {
1619 ALOGW("Unresponsive monitor %s will not get the new gesture",
1620 connection->inputChannel->getName().c_str());
1621 return false;
1622 }
1623 return true;
1624 });
1625 return responsiveMonitors;
1626}
1627
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001628InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1629 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1630 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001631 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 enum InjectionPermission {
1633 INJECTION_PERMISSION_UNKNOWN,
1634 INJECTION_PERMISSION_GRANTED,
1635 INJECTION_PERMISSION_DENIED
1636 };
1637
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 // For security reasons, we defer updating the touch state until we are sure that
1639 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 int32_t displayId = entry.displayId;
1641 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1643
1644 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001645 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001647 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1648 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001650 // Copy current touch state into tempTouchState.
1651 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1652 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001653 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001654 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001655 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1656 mTouchStatesByDisplay.find(displayId);
1657 if (oldStateIt != mTouchStatesByDisplay.end()) {
1658 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001659 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001660 }
1661
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001662 bool isSplit = tempTouchState.split;
1663 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1664 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1665 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1667 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1668 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1669 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1670 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001671 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 bool wrongDevice = false;
1673 if (newGesture) {
1674 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001675 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001676 ALOGI("Dropping event because a pointer for a different device is already down "
1677 "in display %" PRId32,
1678 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001679 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001680 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 switchedDevice = false;
1682 wrongDevice = true;
1683 goto Failed;
1684 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001685 tempTouchState.reset();
1686 tempTouchState.down = down;
1687 tempTouchState.deviceId = entry.deviceId;
1688 tempTouchState.source = entry.source;
1689 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001691 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001692 ALOGI("Dropping move event because a pointer for a different device is already active "
1693 "in display %" PRId32,
1694 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001695 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001696 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001697 switchedDevice = false;
1698 wrongDevice = true;
1699 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701
1702 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1703 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1704
Garfield Tan00f511d2019-06-12 16:55:40 -07001705 int32_t x;
1706 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001708 // Always dispatch mouse events to cursor position.
1709 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001710 x = int32_t(entry.xCursorPosition);
1711 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001712 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001713 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1714 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001715 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001716 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001717 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001718 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1719 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001720
1721 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001722 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001723 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001726 if (newTouchedWindowHandle != nullptr &&
1727 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001728 // New window supports splitting, but we should never split mouse events.
1729 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 } else if (isSplit) {
1731 // New window does not support splitting but we have already split events.
1732 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001733 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735
1736 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001737 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001739 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001740 }
1741
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001742 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1743 ALOGI("Not sending touch event to %s because it is paused",
1744 newTouchedWindowHandle->getName().c_str());
1745 newTouchedWindowHandle = nullptr;
1746 }
1747
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001748 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001749 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001750 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1751 if (!isResponsive) {
1752 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001753 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1754 newTouchedWindowHandle = nullptr;
1755 }
1756 }
1757
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001758 // Drop events that can't be trusted due to occlusion
1759 if (newTouchedWindowHandle != nullptr &&
1760 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1761 TouchOcclusionInfo occlusionInfo =
1762 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001763 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001764 if (DEBUG_TOUCH_OCCLUSION) {
1765 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1766 for (const auto& log : occlusionInfo.debugInfo) {
1767 ALOGD("%s", log.c_str());
1768 }
1769 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001770 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1771 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1772 ALOGW("Dropping untrusted touch event due to %s/%d",
1773 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1774 newTouchedWindowHandle = nullptr;
1775 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001776 }
1777 }
1778
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001779 // Also don't send the new touch event to unresponsive gesture monitors
1780 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1781
Michael Wright3dd60e22019-03-27 22:06:44 +00001782 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1783 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001784 "(%d, %d) in display %" PRId32 ".",
1785 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001787 goto Failed;
1788 }
1789
1790 if (newTouchedWindowHandle != nullptr) {
1791 // Set target flags.
1792 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1793 if (isSplit) {
1794 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001796 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1797 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1798 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1799 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1800 }
1801
1802 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001803 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1804 newHoverWindowHandle = nullptr;
1805 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001806 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001807 }
1808
1809 // Update the temporary touch state.
1810 BitSet32 pointerIds;
1811 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001813 pointerIds.markBit(pointerId);
1814 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001815 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
1817
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001818 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 } else {
1820 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1821
1822 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001823 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001824 if (DEBUG_FOCUS) {
1825 ALOGD("Dropping event because the pointer is not down or we previously "
1826 "dropped the pointer down event in display %" PRId32,
1827 displayId);
1828 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001829 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 goto Failed;
1831 }
1832
1833 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001836 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1837 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838
1839 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001840 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001841 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1843 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001844 if (DEBUG_FOCUS) {
1845 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1846 oldTouchedWindowHandle->getName().c_str(),
1847 newTouchedWindowHandle->getName().c_str(), displayId);
1848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001850 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1851 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1852 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
1854 // Make a slippery entrance into the new window.
1855 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1856 isSplit = true;
1857 }
1858
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001859 int32_t targetFlags =
1860 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 if (isSplit) {
1862 targetFlags |= InputTarget::FLAG_SPLIT;
1863 }
1864 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1865 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1866 }
1867
1868 BitSet32 pointerIds;
1869 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001870 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001872 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 }
1874 }
1875 }
1876
1877 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001878 // Let the previous window know that the hover sequence is over, unless we already did it
1879 // when dispatching it as is to newTouchedWindowHandle.
1880 if (mLastHoverWindowHandle != nullptr &&
1881 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1882 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883#if DEBUG_HOVER
1884 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001885 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001887 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1888 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 }
1890
Garfield Tandf26e862020-07-01 20:18:19 -07001891 // Let the new window know that the hover sequence is starting, unless we already did it
1892 // when dispatching it as is to newTouchedWindowHandle.
1893 if (newHoverWindowHandle != nullptr &&
1894 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1895 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896#if DEBUG_HOVER
1897 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001898 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001900 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1901 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1902 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904 }
1905
1906 // Check permission to inject into all touched foreground windows and ensure there
1907 // is at least one touched foreground window.
1908 {
1909 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001910 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1912 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001913 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001914 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 injectionPermission = INJECTION_PERMISSION_DENIED;
1916 goto Failed;
1917 }
1918 }
1919 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001920 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001921 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001922 ALOGI("Dropping event because there is no touched foreground window in display "
1923 "%" PRId32 " or gesture monitor to receive it.",
1924 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001925 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 goto Failed;
1927 }
1928
1929 // Permission granted to injection into all touched foreground windows.
1930 injectionPermission = INJECTION_PERMISSION_GRANTED;
1931 }
1932
1933 // Check whether windows listening for outside touches are owned by the same UID. If it is
1934 // set the policy flag that we will not reveal coordinate information to this window.
1935 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1936 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001937 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001938 if (foregroundWindowHandle) {
1939 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001940 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001941 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1942 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1943 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001944 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1945 InputTarget::FLAG_ZERO_COORDS,
1946 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 }
1949 }
1950 }
1951 }
1952
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 // If this is the first pointer going down and the touched window has a wallpaper
1954 // then also add the touched wallpaper windows so they are locked in for the duration
1955 // of the touch gesture.
1956 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1957 // engine only supports touch events. We would need to add a mechanism similar
1958 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1959 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1960 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001961 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001962 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001963 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001964 getWindowHandlesLocked(displayId);
1965 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001967 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001968 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001969 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001970 .addOrUpdateWindow(windowHandle,
1971 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1972 InputTarget::
1973 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1974 InputTarget::FLAG_DISPATCH_AS_IS,
1975 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977 }
1978 }
1979 }
1980
1981 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001982 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001984 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001986 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 }
1988
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001989 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001990 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001991 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001992 }
1993
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 // Drop the outside or hover touch windows since we will not care about them
1995 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001996 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997
1998Failed:
1999 // Check injection permission once and for all.
2000 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002001 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 injectionPermission = INJECTION_PERMISSION_GRANTED;
2003 } else {
2004 injectionPermission = INJECTION_PERMISSION_DENIED;
2005 }
2006 }
2007
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002008 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2009 return injectionResult;
2010 }
2011
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002013 if (!wrongDevice) {
2014 if (switchedDevice) {
2015 if (DEBUG_FOCUS) {
2016 ALOGD("Conflicting pointer actions: Switched to a different device.");
2017 }
2018 *outConflictingPointerActions = true;
2019 }
2020
2021 if (isHoverAction) {
2022 // Started hovering, therefore no longer down.
2023 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002024 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002025 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2026 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 *outConflictingPointerActions = true;
2029 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002030 tempTouchState.reset();
2031 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2032 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2033 tempTouchState.deviceId = entry.deviceId;
2034 tempTouchState.source = entry.source;
2035 tempTouchState.displayId = displayId;
2036 }
2037 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2038 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2039 // All pointers up or canceled.
2040 tempTouchState.reset();
2041 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2042 // First pointer went down.
2043 if (oldState && oldState->down) {
2044 if (DEBUG_FOCUS) {
2045 ALOGD("Conflicting pointer actions: Down received while already down.");
2046 }
2047 *outConflictingPointerActions = true;
2048 }
2049 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2050 // One pointer went up.
2051 if (isSplit) {
2052 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2053 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002055 for (size_t i = 0; i < tempTouchState.windows.size();) {
2056 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2057 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2058 touchedWindow.pointerIds.clearBit(pointerId);
2059 if (touchedWindow.pointerIds.isEmpty()) {
2060 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2061 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002064 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002066 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002067 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002068
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002069 // Save changes unless the action was scroll in which case the temporary touch
2070 // state was only valid for this one action.
2071 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2072 if (tempTouchState.displayId >= 0) {
2073 mTouchStatesByDisplay[displayId] = tempTouchState;
2074 } else {
2075 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002079 // Update hover state.
2080 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 return injectionResult;
2084}
2085
2086void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002087 int32_t targetFlags, BitSet32 pointerIds,
2088 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002089 std::vector<InputTarget>::iterator it =
2090 std::find_if(inputTargets.begin(), inputTargets.end(),
2091 [&windowHandle](const InputTarget& inputTarget) {
2092 return inputTarget.inputChannel->getConnectionToken() ==
2093 windowHandle->getToken();
2094 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002095
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002096 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002097
2098 if (it == inputTargets.end()) {
2099 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002100 std::shared_ptr<InputChannel> inputChannel =
2101 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002102 if (inputChannel == nullptr) {
2103 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2104 return;
2105 }
2106 inputTarget.inputChannel = inputChannel;
2107 inputTarget.flags = targetFlags;
2108 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2109 inputTargets.push_back(inputTarget);
2110 it = inputTargets.end() - 1;
2111 }
2112
2113 ALOG_ASSERT(it->flags == targetFlags);
2114 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2115
chaviw1ff3d1e2020-07-01 15:53:47 -07002116 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117}
2118
Michael Wright3dd60e22019-03-27 22:06:44 +00002119void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002120 int32_t displayId, float xOffset,
2121 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002122 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2123 mGlobalMonitorsByDisplay.find(displayId);
2124
2125 if (it != mGlobalMonitorsByDisplay.end()) {
2126 const std::vector<Monitor>& monitors = it->second;
2127 for (const Monitor& monitor : monitors) {
2128 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 }
2131}
2132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002133void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2134 float yOffset,
2135 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002136 InputTarget target;
2137 target.inputChannel = monitor.inputChannel;
2138 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002139 ui::Transform t;
2140 t.set(xOffset, yOffset);
2141 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002142 inputTargets.push_back(target);
2143}
2144
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002146 const InjectionState* injectionState) {
2147 if (injectionState &&
2148 (windowHandle == nullptr ||
2149 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2150 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002151 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153 "owned by uid %d",
2154 injectionState->injectorPid, injectionState->injectorUid,
2155 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 } else {
2157 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002158 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 }
2160 return false;
2161 }
2162 return true;
2163}
2164
Robert Carrc9bf1d32020-04-13 17:21:08 -07002165/**
2166 * Indicate whether one window handle should be considered as obscuring
2167 * another window handle. We only check a few preconditions. Actually
2168 * checking the bounds is left to the caller.
2169 */
2170static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2171 const sp<InputWindowHandle>& otherHandle) {
2172 // Compare by token so cloned layers aren't counted
2173 if (haveSameToken(windowHandle, otherHandle)) {
2174 return false;
2175 }
2176 auto info = windowHandle->getInfo();
2177 auto otherInfo = otherHandle->getInfo();
2178 if (!otherInfo->visible) {
2179 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002180 } else if (otherInfo->alpha == 0 &&
2181 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2182 // Those act as if they were invisible, so we don't need to flag them.
2183 // We do want to potentially flag touchable windows even if they have 0
2184 // opacity, since they can consume touches and alter the effects of the
2185 // user interaction (eg. apps that rely on
2186 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2187 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2188 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002189 } else if (info->ownerUid == otherInfo->ownerUid) {
2190 // If ownerUid is the same we don't generate occlusion events as there
2191 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002192 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002193 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002194 return false;
2195 } else if (otherInfo->displayId != info->displayId) {
2196 return false;
2197 }
2198 return true;
2199}
2200
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002201/**
2202 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2203 * untrusted, one should check:
2204 *
2205 * 1. If result.hasBlockingOcclusion is true.
2206 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2207 * BLOCK_UNTRUSTED.
2208 *
2209 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2210 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2211 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2212 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2213 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2214 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2215 *
2216 * If neither of those is true, then it means the touch can be allowed.
2217 */
2218InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2219 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002220 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2221 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002222 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2223 TouchOcclusionInfo info;
2224 info.hasBlockingOcclusion = false;
2225 info.obscuringOpacity = 0;
2226 info.obscuringUid = -1;
2227 std::map<int32_t, float> opacityByUid;
2228 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2229 if (windowHandle == otherHandle) {
2230 break; // All future windows are below us. Exit early.
2231 }
2232 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2233 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002234 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2235 if (DEBUG_TOUCH_OCCLUSION) {
2236 info.debugInfo.push_back(
2237 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2238 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002239 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2240 // we perform the checks below to see if the touch can be propagated or not based on the
2241 // window's touch occlusion mode
2242 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2243 info.hasBlockingOcclusion = true;
2244 info.obscuringUid = otherInfo->ownerUid;
2245 info.obscuringPackage = otherInfo->packageName;
2246 break;
2247 }
2248 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2249 uint32_t uid = otherInfo->ownerUid;
2250 float opacity =
2251 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2252 // Given windows A and B:
2253 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2254 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2255 opacityByUid[uid] = opacity;
2256 if (opacity > info.obscuringOpacity) {
2257 info.obscuringOpacity = opacity;
2258 info.obscuringUid = uid;
2259 info.obscuringPackage = otherInfo->packageName;
2260 }
2261 }
2262 }
2263 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002264 if (DEBUG_TOUCH_OCCLUSION) {
2265 info.debugInfo.push_back(
2266 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2267 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002268 return info;
2269}
2270
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002271std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2272 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002273 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2274 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002275 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2276 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2277 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002278 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002279 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002280 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002281 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2282 info->frameTop, info->frameRight, info->frameBottom,
2283 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002284 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2285 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002286}
2287
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002288bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2289 if (occlusionInfo.hasBlockingOcclusion) {
2290 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2291 occlusionInfo.obscuringUid);
2292 return false;
2293 }
2294 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2295 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2296 "%.2f, maximum allowed = %.2f)",
2297 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2298 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2299 return false;
2300 }
2301 return true;
2302}
2303
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2305 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002307 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002308 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002309 if (windowHandle == otherHandle) {
2310 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002313 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002314 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 return true;
2316 }
2317 }
2318 return false;
2319}
2320
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002321bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2322 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002323 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002324 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002325 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002326 if (windowHandle == otherHandle) {
2327 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002328 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002329 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002330 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002331 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002332 return true;
2333 }
2334 }
2335 return false;
2336}
2337
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002338std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002339 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002341 if (applicationHandle != nullptr) {
2342 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002343 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 } else {
2345 return applicationHandle->getName();
2346 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002347 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002348 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002350 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 }
2352}
2353
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002354void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002355 if (eventEntry.type == EventEntry::Type::FOCUS) {
2356 // Focus events are passed to apps, but do not represent user activity.
2357 return;
2358 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002359 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002360 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002361 if (focusedWindowHandle != nullptr) {
2362 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002363 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002365 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366#endif
2367 return;
2368 }
2369 }
2370
2371 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002373 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002374 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2375 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002376 return;
2377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002379 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 eventType = USER_ACTIVITY_EVENT_TOUCH;
2381 }
2382 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002384 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002385 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2386 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 return;
2388 }
2389 eventType = USER_ACTIVITY_EVENT_BUTTON;
2390 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002392 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002393 case EventEntry::Type::CONFIGURATION_CHANGED:
2394 case EventEntry::Type::DEVICE_RESET: {
2395 LOG_ALWAYS_FATAL("%s events are not user activity",
2396 EventEntry::typeToString(eventEntry.type));
2397 break;
2398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 }
2400
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002401 std::unique_ptr<CommandEntry> commandEntry =
2402 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002403 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002405 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406}
2407
2408void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002409 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002410 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002411 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002412 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002414 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002415 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002416 ATRACE_NAME(message.c_str());
2417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418#if DEBUG_DISPATCH_CYCLE
2419 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002420 "globalScaleFactor=%f, pointerIds=0x%x %s",
2421 connection->getInputChannelName().c_str(), inputTarget.flags,
2422 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2423 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424#endif
2425
2426 // Skip this event if the connection status is not normal.
2427 // We don't want to enqueue additional outbound events if the connection is broken.
2428 if (connection->status != Connection::STATUS_NORMAL) {
2429#if DEBUG_DISPATCH_CYCLE
2430 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002431 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432#endif
2433 return;
2434 }
2435
2436 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002437 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2438 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2439 "Entry type %s should not have FLAG_SPLIT",
2440 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002442 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002443 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002444 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002445 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 if (!splitMotionEntry) {
2447 return; // split event was dropped
2448 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002449 if (DEBUG_FOCUS) {
2450 ALOGD("channel '%s' ~ Split motion event.",
2451 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002452 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002453 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002454 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2455 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 return;
2457 }
2458 }
2459
2460 // Not splitting. Enqueue dispatch entries for the event as is.
2461 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2462}
2463
2464void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002466 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002467 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002468 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002470 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002471 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002472 ATRACE_NAME(message.c_str());
2473 }
2474
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002475 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476
2477 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002478 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002479 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002480 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002481 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002482 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002484 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002486 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002488 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490
2491 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002492 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 startDispatchCycleLocked(currentTime, connection);
2494 }
2495}
2496
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002498 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002499 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002500 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002501 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2503 connection->getInputChannelName().c_str(),
2504 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002505 ATRACE_NAME(message.c_str());
2506 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002507 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 if (!(inputTargetFlags & dispatchMode)) {
2509 return;
2510 }
2511 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2512
2513 // This is a new event.
2514 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002515 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002516 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002518 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2519 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002520 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002522 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002523 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002524 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002525 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002526 dispatchEntry->resolvedAction = keyEntry.action;
2527 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2530 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2533 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535 return; // skip the inconsistent event
2536 }
2537 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002540 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002541 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002542 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2543 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2544 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2545 static_cast<int32_t>(IdGenerator::Source::OTHER);
2546 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2548 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2549 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2550 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2551 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2552 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2553 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2554 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2555 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2556 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2557 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002558 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002559 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 }
2561 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002562 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2563 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002565 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2566 "event",
2567 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002572 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2574 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2575 }
2576 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2577 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002580 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2581 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2584 "event",
2585 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 return; // skip the inconsistent event
2588 }
2589
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002590 dispatchEntry->resolvedEventId =
2591 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2592 ? mIdGenerator.nextId()
2593 : motionEntry.id;
2594 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2595 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2596 ") to MotionEvent(id=0x%" PRIx32 ").",
2597 motionEntry.id, dispatchEntry->resolvedEventId);
2598 ATRACE_NAME(message.c_str());
2599 }
2600
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002601 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002602 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002603
2604 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002606 case EventEntry::Type::FOCUS: {
2607 break;
2608 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002609 case EventEntry::Type::CONFIGURATION_CHANGED:
2610 case EventEntry::Type::DEVICE_RESET: {
2611 LOG_ALWAYS_FATAL("%s events should not go to apps",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002612 EventEntry::typeToString(newEntry.type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002613 break;
2614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 }
2616
2617 // Remember that we are waiting for this dispatch to complete.
2618 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002619 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
2621
2622 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002623 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002624 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002625}
2626
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002627/**
2628 * This function is purely for debugging. It helps us understand where the user interaction
2629 * was taking place. For example, if user is touching launcher, we will see a log that user
2630 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2631 * We will see both launcher and wallpaper in that list.
2632 * Once the interaction with a particular set of connections starts, no new logs will be printed
2633 * until the set of interacted connections changes.
2634 *
2635 * The following items are skipped, to reduce the logspam:
2636 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2637 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2638 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2639 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2640 * Both of those ACTION_UP events would not be logged
2641 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2642 * will not be logged. This is omitted to reduce the amount of data printed.
2643 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2644 * gesture monitor is the only connection receiving the remainder of the gesture.
2645 */
2646void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2647 const std::vector<InputTarget>& targets) {
2648 // Skip ACTION_UP events, and all events other than keys and motions
2649 if (entry.type == EventEntry::Type::KEY) {
2650 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2651 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2652 return;
2653 }
2654 } else if (entry.type == EventEntry::Type::MOTION) {
2655 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2656 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2657 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2658 return;
2659 }
2660 } else {
2661 return; // Not a key or a motion
2662 }
2663
2664 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2665 std::vector<sp<Connection>> newConnections;
2666 for (const InputTarget& target : targets) {
2667 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2668 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2669 continue; // Skip windows that receive ACTION_OUTSIDE
2670 }
2671
2672 sp<IBinder> token = target.inputChannel->getConnectionToken();
2673 sp<Connection> connection = getConnectionLocked(token);
2674 if (connection == nullptr || connection->monitor) {
2675 continue; // We only need to keep track of the non-monitor connections.
2676 }
2677 newConnectionTokens.insert(std::move(token));
2678 newConnections.emplace_back(connection);
2679 }
2680 if (newConnectionTokens == mInteractionConnectionTokens) {
2681 return; // no change
2682 }
2683 mInteractionConnectionTokens = newConnectionTokens;
2684
2685 std::string windowList;
2686 for (const sp<Connection>& connection : newConnections) {
2687 windowList += connection->getWindowName() + ", ";
2688 }
2689 std::string message = "Interaction with windows: " + windowList;
2690 if (windowList.empty()) {
2691 message += "<none>";
2692 }
2693 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2694}
2695
chaviwfd6d3512019-03-25 13:23:49 -07002696void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002697 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002698 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002699 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2700 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002701 return;
2702 }
2703
Vishnu Nairad321cd2020-08-20 16:40:21 -07002704 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2705 if (focusedToken == token) {
2706 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002707 return;
2708 }
2709
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002710 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2711 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002712 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002713 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714}
2715
2716void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002718 if (ATRACE_ENABLED()) {
2719 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002720 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002721 ATRACE_NAME(message.c_str());
2722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725#endif
2726
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002727 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2728 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002730 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002731 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002732 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733
2734 // Publish the event.
2735 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002736 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2737 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002738 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002739 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2740 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002743 status = connection->inputPublisher
2744 .publishKeyEvent(dispatchEntry->seq,
2745 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2746 keyEntry.source, keyEntry.displayId,
2747 std::move(hmac), dispatchEntry->resolvedAction,
2748 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2749 keyEntry.scanCode, keyEntry.metaState,
2750 keyEntry.repeatCount, keyEntry.downTime,
2751 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 }
2754
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002755 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002756 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002758 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002759 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760
chaviw82357092020-01-28 13:13:06 -08002761 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002762 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2764 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002765 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002766 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2767 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002768 // Don't apply window scale here since we don't want scale to affect raw
2769 // coordinates. The scale will be sent back to the client and applied
2770 // later when requesting relative coordinates.
2771 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2772 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 }
2774 usingCoords = scaledCoords;
2775 }
2776 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 // We don't want the dispatch target to know.
2778 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002779 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 scaledCoords[i].clear();
2781 }
2782 usingCoords = scaledCoords;
2783 }
2784 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002785
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002786 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002787
2788 // Publish the motion event.
2789 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002790 .publishMotionEvent(dispatchEntry->seq,
2791 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002792 motionEntry.deviceId, motionEntry.source,
2793 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002794 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002795 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002796 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002797 motionEntry.edgeFlags, motionEntry.metaState,
2798 motionEntry.buttonState,
2799 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002800 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002801 motionEntry.xPrecision, motionEntry.yPrecision,
2802 motionEntry.xCursorPosition,
2803 motionEntry.yCursorPosition,
2804 motionEntry.downTime, motionEntry.eventTime,
2805 motionEntry.pointerCount,
2806 motionEntry.pointerProperties, usingCoords);
2807 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 break;
2809 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002810 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002811 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002812 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002813 focusEntry.id,
2814 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002815 mInTouchMode);
2816 break;
2817 }
2818
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002819 case EventEntry::Type::CONFIGURATION_CHANGED:
2820 case EventEntry::Type::DEVICE_RESET: {
2821 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002822 EventEntry::typeToString(eventEntry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 }
2826
2827 // Check the result.
2828 if (status) {
2829 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002830 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 "This is unexpected because the wait queue is empty, so the pipe "
2833 "should be empty and we shouldn't have any problems writing an "
2834 "event to it, status=%d",
2835 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2837 } else {
2838 // Pipe is full and we are waiting for the app to finish process some events
2839 // before sending more events to it.
2840#if DEBUG_DISPATCH_CYCLE
2841 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002842 "waiting for the application to catch up",
2843 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 }
2846 } else {
2847 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848 "status=%d",
2849 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2851 }
2852 return;
2853 }
2854
2855 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002856 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2857 connection->outboundQueue.end(),
2858 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002859 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002860 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002861 if (connection->responsive) {
2862 mAnrTracker.insert(dispatchEntry->timeoutTime,
2863 connection->inputChannel->getConnectionToken());
2864 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002865 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 }
2867}
2868
chaviw09c8d2d2020-08-24 15:48:26 -07002869std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2870 size_t size;
2871 switch (event.type) {
2872 case VerifiedInputEvent::Type::KEY: {
2873 size = sizeof(VerifiedKeyEvent);
2874 break;
2875 }
2876 case VerifiedInputEvent::Type::MOTION: {
2877 size = sizeof(VerifiedMotionEvent);
2878 break;
2879 }
2880 }
2881 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2882 return mHmacKeyManager.sign(start, size);
2883}
2884
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002885const std::array<uint8_t, 32> InputDispatcher::getSignature(
2886 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2887 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2888 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2889 // Only sign events up and down events as the purely move events
2890 // are tied to their up/down counterparts so signing would be redundant.
2891 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2892 verifiedEvent.actionMasked = actionMasked;
2893 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002894 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002895 }
2896 return INVALID_HMAC;
2897}
2898
2899const std::array<uint8_t, 32> InputDispatcher::getSignature(
2900 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2901 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2902 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2903 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002904 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002905}
2906
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002908 const sp<Connection>& connection, uint32_t seq,
2909 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910#if DEBUG_DISPATCH_CYCLE
2911 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913#endif
2914
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 if (connection->status == Connection::STATUS_BROKEN ||
2916 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 return;
2918 }
2919
2920 // Notify other system components and prepare to start the next dispatch cycle.
2921 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2922}
2923
2924void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 const sp<Connection>& connection,
2926 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927#if DEBUG_DISPATCH_CYCLE
2928 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930#endif
2931
2932 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002933 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002934 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002935 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002936 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937
2938 // The connection appears to be unrecoverably broken.
2939 // Ignore already broken or zombie connections.
2940 if (connection->status == Connection::STATUS_NORMAL) {
2941 connection->status = Connection::STATUS_BROKEN;
2942
2943 if (notify) {
2944 // Notify other system components.
2945 onDispatchCycleBrokenLocked(currentTime, connection);
2946 }
2947 }
2948}
2949
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002950void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2951 while (!queue.empty()) {
2952 DispatchEntry* dispatchEntry = queue.front();
2953 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002954 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 }
2956}
2957
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002958void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002960 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 }
2962 delete dispatchEntry;
2963}
2964
2965int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2966 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2967
2968 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002969 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002971 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 "fd=%d, events=0x%x",
2974 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 return 0; // remove the callback
2976 }
2977
2978 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002979 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2981 if (!(events & ALOOPER_EVENT_INPUT)) {
2982 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 "events=0x%x",
2984 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985 return 1;
2986 }
2987
2988 nsecs_t currentTime = now();
2989 bool gotOne = false;
2990 status_t status;
2991 for (;;) {
2992 uint32_t seq;
2993 bool handled;
2994 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2995 if (status) {
2996 break;
2997 }
2998 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2999 gotOne = true;
3000 }
3001 if (gotOne) {
3002 d->runCommandsLockedInterruptible();
3003 if (status == WOULD_BLOCK) {
3004 return 1;
3005 }
3006 }
3007
3008 notify = status != DEAD_OBJECT || !connection->monitor;
3009 if (notify) {
3010 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 }
3013 } else {
3014 // Monitor channels are never explicitly unregistered.
3015 // We do it automatically when the remote endpoint is closed so don't warn
3016 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003017 const bool stillHaveWindowHandle =
3018 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3019 nullptr;
3020 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 if (notify) {
3022 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003023 "events=0x%x",
3024 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 }
3026 }
3027
Garfield Tan15601662020-09-22 15:32:38 -07003028 // Remove the channel.
3029 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003031 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032}
3033
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003036 for (const auto& pair : mConnectionsByFd) {
3037 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 }
3039}
3040
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003042 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003043 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3044 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3045}
3046
3047void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3048 const CancelationOptions& options,
3049 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3050 for (const auto& it : monitorsByDisplay) {
3051 const std::vector<Monitor>& monitors = it.second;
3052 for (const Monitor& monitor : monitors) {
3053 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003054 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003055 }
3056}
3057
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003059 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003060 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003061 if (connection == nullptr) {
3062 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003064
3065 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066}
3067
3068void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3069 const sp<Connection>& connection, const CancelationOptions& options) {
3070 if (connection->status == Connection::STATUS_BROKEN) {
3071 return;
3072 }
3073
3074 nsecs_t currentTime = now();
3075
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003076 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003077 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003079 if (cancelationEvents.empty()) {
3080 return;
3081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003083 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3084 "with reality: %s, mode=%d.",
3085 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3086 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003088
3089 InputTarget target;
3090 sp<InputWindowHandle> windowHandle =
3091 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3092 if (windowHandle != nullptr) {
3093 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003094 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003095 target.globalScaleFactor = windowInfo->globalScaleFactor;
3096 }
3097 target.inputChannel = connection->inputChannel;
3098 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3099
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003100 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003101 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003102 switch (cancelationEventEntry->type) {
3103 case EventEntry::Type::KEY: {
3104 logOutboundKeyDetails("cancel - ",
3105 static_cast<const KeyEntry&>(*cancelationEventEntry));
3106 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003108 case EventEntry::Type::MOTION: {
3109 logOutboundMotionDetails("cancel - ",
3110 static_cast<const MotionEntry&>(*cancelationEventEntry));
3111 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003113 case EventEntry::Type::FOCUS: {
3114 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3115 break;
3116 }
3117 case EventEntry::Type::CONFIGURATION_CHANGED:
3118 case EventEntry::Type::DEVICE_RESET: {
3119 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3120 EventEntry::typeToString(cancelationEventEntry->type));
3121 break;
3122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123 }
3124
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3126 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003128
3129 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130}
3131
Svet Ganov5d3bc372020-01-26 23:11:07 -08003132void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3133 const sp<Connection>& connection) {
3134 if (connection->status == Connection::STATUS_BROKEN) {
3135 return;
3136 }
3137
3138 nsecs_t currentTime = now();
3139
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003140 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003141 connection->inputState.synthesizePointerDownEvents(currentTime);
3142
3143 if (downEvents.empty()) {
3144 return;
3145 }
3146
3147#if DEBUG_OUTBOUND_EVENT_DETAILS
3148 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3149 connection->getInputChannelName().c_str(), downEvents.size());
3150#endif
3151
3152 InputTarget target;
3153 sp<InputWindowHandle> windowHandle =
3154 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3155 if (windowHandle != nullptr) {
3156 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003157 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003158 target.globalScaleFactor = windowInfo->globalScaleFactor;
3159 }
3160 target.inputChannel = connection->inputChannel;
3161 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3162
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003164 switch (downEventEntry->type) {
3165 case EventEntry::Type::MOTION: {
3166 logOutboundMotionDetails("down - ",
3167 static_cast<const MotionEntry&>(*downEventEntry));
3168 break;
3169 }
3170
3171 case EventEntry::Type::KEY:
3172 case EventEntry::Type::FOCUS:
3173 case EventEntry::Type::CONFIGURATION_CHANGED:
3174 case EventEntry::Type::DEVICE_RESET: {
3175 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3176 EventEntry::typeToString(downEventEntry->type));
3177 break;
3178 }
3179 }
3180
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3182 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003183 }
3184
3185 startDispatchCycleLocked(currentTime, connection);
3186}
3187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3189 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 ALOG_ASSERT(pointerIds.value != 0);
3191
3192 uint32_t splitPointerIndexMap[MAX_POINTERS];
3193 PointerProperties splitPointerProperties[MAX_POINTERS];
3194 PointerCoords splitPointerCoords[MAX_POINTERS];
3195
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003196 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 uint32_t splitPointerCount = 0;
3198
3199 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003202 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 uint32_t pointerId = uint32_t(pointerProperties.id);
3204 if (pointerIds.hasBit(pointerId)) {
3205 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3206 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3207 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003208 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 splitPointerCount += 1;
3210 }
3211 }
3212
3213 if (splitPointerCount != pointerIds.count()) {
3214 // This is bad. We are missing some of the pointers that we expected to deliver.
3215 // Most likely this indicates that we received an ACTION_MOVE events that has
3216 // different pointer ids than we expected based on the previous ACTION_DOWN
3217 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3218 // in this way.
3219 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 "we expected there to be %d pointers. This probably means we received "
3221 "a broken sequence of pointer ids from the input device.",
3222 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003223 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 }
3225
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003226 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3229 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3231 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003232 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 uint32_t pointerId = uint32_t(pointerProperties.id);
3234 if (pointerIds.hasBit(pointerId)) {
3235 if (pointerIds.count() == 1) {
3236 // The first/last pointer went down/up.
3237 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 ? AMOTION_EVENT_ACTION_DOWN
3239 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 } else {
3241 // A secondary pointer went down/up.
3242 uint32_t splitPointerIndex = 0;
3243 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3244 splitPointerIndex += 1;
3245 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246 action = maskedAction |
3247 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
3249 } else {
3250 // An unrelated pointer changed.
3251 action = AMOTION_EVENT_ACTION_MOVE;
3252 }
3253 }
3254
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003255 int32_t newId = mIdGenerator.nextId();
3256 if (ATRACE_ENABLED()) {
3257 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3258 ") to MotionEvent(id=0x%" PRIx32 ").",
3259 originalMotionEntry.id, newId);
3260 ATRACE_NAME(message.c_str());
3261 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003262 std::unique_ptr<MotionEntry> splitMotionEntry =
3263 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3264 originalMotionEntry.deviceId, originalMotionEntry.source,
3265 originalMotionEntry.displayId,
3266 originalMotionEntry.policyFlags, action,
3267 originalMotionEntry.actionButton,
3268 originalMotionEntry.flags, originalMotionEntry.metaState,
3269 originalMotionEntry.buttonState,
3270 originalMotionEntry.classification,
3271 originalMotionEntry.edgeFlags,
3272 originalMotionEntry.xPrecision,
3273 originalMotionEntry.yPrecision,
3274 originalMotionEntry.xCursorPosition,
3275 originalMotionEntry.yCursorPosition,
3276 originalMotionEntry.downTime, splitPointerCount,
3277 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003279 if (originalMotionEntry.injectionState) {
3280 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 splitMotionEntry->injectionState->refCount += 1;
3282 }
3283
3284 return splitMotionEntry;
3285}
3286
3287void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3288#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003289 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290#endif
3291
3292 bool needWake;
3293 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003294 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3297 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3298 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 } // release lock
3300
3301 if (needWake) {
3302 mLooper->wake();
3303 }
3304}
3305
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003306/**
3307 * If one of the meta shortcuts is detected, process them here:
3308 * Meta + Backspace -> generate BACK
3309 * Meta + Enter -> generate HOME
3310 * This will potentially overwrite keyCode and metaState.
3311 */
3312void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003314 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3315 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3316 if (keyCode == AKEYCODE_DEL) {
3317 newKeyCode = AKEYCODE_BACK;
3318 } else if (keyCode == AKEYCODE_ENTER) {
3319 newKeyCode = AKEYCODE_HOME;
3320 }
3321 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003322 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003323 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003324 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003325 keyCode = newKeyCode;
3326 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3327 }
3328 } else if (action == AKEY_EVENT_ACTION_UP) {
3329 // In order to maintain a consistent stream of up and down events, check to see if the key
3330 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3331 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003332 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003333 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003334 auto replacementIt = mReplacedKeys.find(replacement);
3335 if (replacementIt != mReplacedKeys.end()) {
3336 keyCode = replacementIt->second;
3337 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003338 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3339 }
3340 }
3341}
3342
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3344#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003345 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3346 "policyFlags=0x%x, action=0x%x, "
3347 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3348 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3349 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3350 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351#endif
3352 if (!validateKeyEvent(args->action)) {
3353 return;
3354 }
3355
3356 uint32_t policyFlags = args->policyFlags;
3357 int32_t flags = args->flags;
3358 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003359 // InputDispatcher tracks and generates key repeats on behalf of
3360 // whatever notifies it, so repeatCount should always be set to 0
3361 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3363 policyFlags |= POLICY_FLAG_VIRTUAL;
3364 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 if (policyFlags & POLICY_FLAG_FUNCTION) {
3367 metaState |= AMETA_FUNCTION_ON;
3368 }
3369
3370 policyFlags |= POLICY_FLAG_TRUSTED;
3371
Michael Wright78f24442014-08-06 15:55:28 -07003372 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003373 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003374
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003376 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003377 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3378 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379
Michael Wright2b3c3302018-03-02 17:19:13 +00003380 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003382 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3383 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 bool needWake;
3388 { // acquire lock
3389 mLock.lock();
3390
3391 if (shouldSendKeyToInputFilterLocked(args)) {
3392 mLock.unlock();
3393
3394 policyFlags |= POLICY_FLAG_FILTERED;
3395 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3396 return; // event was consumed by the filter
3397 }
3398
3399 mLock.lock();
3400 }
3401
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003402 std::unique_ptr<KeyEntry> newEntry =
3403 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3404 args->displayId, policyFlags, args->action, flags,
3405 keyCode, args->scanCode, metaState, repeatCount,
3406 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003408 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 mLock.unlock();
3410 } // release lock
3411
3412 if (needWake) {
3413 mLooper->wake();
3414 }
3415}
3416
3417bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3418 return mInputFilterEnabled;
3419}
3420
3421void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3422#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003423 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3424 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003425 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3426 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003427 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003428 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3429 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3430 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3431 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 for (uint32_t i = 0; i < args->pointerCount; i++) {
3433 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434 "x=%f, y=%f, pressure=%f, size=%f, "
3435 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3436 "orientation=%f",
3437 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3438 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3439 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3440 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3441 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3442 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3443 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3444 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3445 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3446 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 }
3448#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003449 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3450 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 return;
3452 }
3453
3454 uint32_t policyFlags = args->policyFlags;
3455 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003456
3457 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003458 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003459 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3460 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463
3464 bool needWake;
3465 { // acquire lock
3466 mLock.lock();
3467
3468 if (shouldSendMotionToInputFilterLocked(args)) {
3469 mLock.unlock();
3470
3471 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003472 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003473 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3474 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003475 args->metaState, args->buttonState, args->classification, transform,
3476 args->xPrecision, args->yPrecision, args->xCursorPosition,
3477 args->yCursorPosition, args->downTime, args->eventTime,
3478 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
3480 policyFlags |= POLICY_FLAG_FILTERED;
3481 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3482 return; // event was consumed by the filter
3483 }
3484
3485 mLock.lock();
3486 }
3487
3488 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003489 std::unique_ptr<MotionEntry> newEntry =
3490 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3491 args->source, args->displayId, policyFlags,
3492 args->action, args->actionButton, args->flags,
3493 args->metaState, args->buttonState,
3494 args->classification, args->edgeFlags,
3495 args->xPrecision, args->yPrecision,
3496 args->xCursorPosition, args->yCursorPosition,
3497 args->downTime, args->pointerCount,
3498 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003500 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 mLock.unlock();
3502 } // release lock
3503
3504 if (needWake) {
3505 mLooper->wake();
3506 }
3507}
3508
3509bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003510 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511}
3512
3513void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3514#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003515 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003516 "switchMask=0x%08x",
3517 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518#endif
3519
3520 uint32_t policyFlags = args->policyFlags;
3521 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523}
3524
3525void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3526#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3528 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529#endif
3530
3531 bool needWake;
3532 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003533 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003535 std::unique_ptr<DeviceResetEntry> newEntry =
3536 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3537 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 } // release lock
3539
3540 if (needWake) {
3541 mLooper->wake();
3542 }
3543}
3544
Prabir Pradhan7e186182020-11-10 13:56:45 -08003545void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3546#if DEBUG_INBOUND_EVENT_DETAILS
3547 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3548 args->enabled ? "true" : "false");
3549#endif
3550
3551 // TODO(prabirmsp): Implement.
3552}
3553
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003554InputEventInjectionResult InputDispatcher::injectInputEvent(
3555 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3556 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557#if DEBUG_INBOUND_EVENT_DETAILS
3558 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003559 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3560 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003562 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563
3564 policyFlags |= POLICY_FLAG_INJECTED;
3565 if (hasInjectionPermission(injectorPid, injectorUid)) {
3566 policyFlags |= POLICY_FLAG_TRUSTED;
3567 }
3568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003569 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003571 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003572 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3573 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003574 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003575 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003578 int32_t flags = incomingKey.getFlags();
3579 int32_t keyCode = incomingKey.getKeyCode();
3580 int32_t metaState = incomingKey.getMetaState();
3581 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003583 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003584 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003585 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3586 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3587 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3590 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003591 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003592
3593 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3594 android::base::Timer t;
3595 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3596 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3597 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3598 std::to_string(t.duration().count()).c_str());
3599 }
3600 }
3601
3602 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003603 std::unique_ptr<KeyEntry> injectedEntry =
3604 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3605 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3606 incomingKey.getDisplayId(), policyFlags, action,
3607 flags, keyCode, incomingKey.getScanCode(), metaState,
3608 incomingKey.getRepeatCount(),
3609 incomingKey.getDownTime());
3610 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003611 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
3613
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 case AINPUT_EVENT_TYPE_MOTION: {
3615 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3616 int32_t action = motionEvent->getAction();
3617 size_t pointerCount = motionEvent->getPointerCount();
3618 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3619 int32_t actionButton = motionEvent->getActionButton();
3620 int32_t displayId = motionEvent->getDisplayId();
3621 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003622 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 }
3624
3625 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3626 nsecs_t eventTime = motionEvent->getEventTime();
3627 android::base::Timer t;
3628 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3629 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3630 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3631 std::to_string(t.duration().count()).c_str());
3632 }
3633 }
3634
3635 mLock.lock();
3636 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3637 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003638 std::unique_ptr<MotionEntry> injectedEntry =
3639 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3640 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3641 motionEvent->getDisplayId(), policyFlags, action,
3642 actionButton, motionEvent->getFlags(),
3643 motionEvent->getMetaState(),
3644 motionEvent->getButtonState(),
3645 motionEvent->getClassification(),
3646 motionEvent->getEdgeFlags(),
3647 motionEvent->getXPrecision(),
3648 motionEvent->getYPrecision(),
3649 motionEvent->getRawXCursorPosition(),
3650 motionEvent->getRawYCursorPosition(),
3651 motionEvent->getDownTime(),
3652 uint32_t(pointerCount), pointerProperties,
3653 samplePointerCoords, motionEvent->getXOffset(),
3654 motionEvent->getYOffset());
3655 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003656 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3657 sampleEventTimes += 1;
3658 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003659 std::unique_ptr<MotionEntry> nextInjectedEntry =
3660 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3661 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3662 motionEvent->getDisplayId(), policyFlags,
3663 action, actionButton, motionEvent->getFlags(),
3664 motionEvent->getMetaState(),
3665 motionEvent->getButtonState(),
3666 motionEvent->getClassification(),
3667 motionEvent->getEdgeFlags(),
3668 motionEvent->getXPrecision(),
3669 motionEvent->getYPrecision(),
3670 motionEvent->getRawXCursorPosition(),
3671 motionEvent->getRawYCursorPosition(),
3672 motionEvent->getDownTime(),
3673 uint32_t(pointerCount), pointerProperties,
3674 samplePointerCoords,
3675 motionEvent->getXOffset(),
3676 motionEvent->getYOffset());
3677 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003678 }
3679 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003682 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003683 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003684 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 }
3686
3687 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003688 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 injectionState->injectionIsAsync = true;
3690 }
3691
3692 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003693 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694
3695 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003696 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003697 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003698 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 }
3700
3701 mLock.unlock();
3702
3703 if (needWake) {
3704 mLooper->wake();
3705 }
3706
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003707 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003709 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003711 if (syncMode == InputEventInjectionSync::NONE) {
3712 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 } else {
3714 for (;;) {
3715 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003716 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 break;
3718 }
3719
3720 nsecs_t remainingTimeout = endTime - now();
3721 if (remainingTimeout <= 0) {
3722#if DEBUG_INJECTION
3723 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003726 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 break;
3728 }
3729
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003730 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 }
3732
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003733 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3734 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 while (injectionState->pendingForegroundDispatches != 0) {
3736#if DEBUG_INJECTION
3737 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003738 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739#endif
3740 nsecs_t remainingTimeout = endTime - now();
3741 if (remainingTimeout <= 0) {
3742#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003743 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3744 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 break;
3748 }
3749
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003750 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 }
3752 }
3753 }
3754
3755 injectionState->release();
3756 } // release lock
3757
3758#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003759 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003760 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761#endif
3762
3763 return injectionResult;
3764}
3765
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003766std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003767 std::array<uint8_t, 32> calculatedHmac;
3768 std::unique_ptr<VerifiedInputEvent> result;
3769 switch (event.getType()) {
3770 case AINPUT_EVENT_TYPE_KEY: {
3771 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3772 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3773 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003774 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003775 break;
3776 }
3777 case AINPUT_EVENT_TYPE_MOTION: {
3778 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3779 VerifiedMotionEvent verifiedMotionEvent =
3780 verifiedMotionEventFromMotionEvent(motionEvent);
3781 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003782 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003783 break;
3784 }
3785 default: {
3786 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3787 return nullptr;
3788 }
3789 }
3790 if (calculatedHmac == INVALID_HMAC) {
3791 return nullptr;
3792 }
3793 if (calculatedHmac != event.getHmac()) {
3794 return nullptr;
3795 }
3796 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003797}
3798
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 return injectorUid == 0 ||
3801 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802}
3803
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003804void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003805 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003806 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 if (injectionState) {
3808#if DEBUG_INJECTION
3809 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003810 "injectorPid=%d, injectorUid=%d",
3811 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812#endif
3813
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003814 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 // Log the outcome since the injector did not wait for the injection result.
3816 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003817 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003818 ALOGV("Asynchronous input event injection succeeded.");
3819 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003820 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 ALOGW("Asynchronous input event injection failed.");
3822 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003823 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003824 ALOGW("Asynchronous input event injection permission denied.");
3825 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003826 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 ALOGW("Asynchronous input event injection timed out.");
3828 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003829 case InputEventInjectionResult::PENDING:
3830 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3831 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 }
3833 }
3834
3835 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003836 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 }
3838}
3839
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003840void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
3841 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 if (injectionState) {
3843 injectionState->pendingForegroundDispatches += 1;
3844 }
3845}
3846
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003847void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
3848 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 if (injectionState) {
3850 injectionState->pendingForegroundDispatches -= 1;
3851
3852 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003853 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 }
3855 }
3856}
3857
Vishnu Nairad321cd2020-08-20 16:40:21 -07003858const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003859 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003860 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3861 auto it = mWindowHandlesByDisplay.find(displayId);
3862 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003863}
3864
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003866 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003867 if (windowHandleToken == nullptr) {
3868 return nullptr;
3869 }
3870
Arthur Hungb92218b2018-08-14 12:00:21 +08003871 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003872 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003873 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003874 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003875 return windowHandle;
3876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 }
3878 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003879 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880}
3881
Vishnu Nairad321cd2020-08-20 16:40:21 -07003882sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3883 int displayId) const {
3884 if (windowHandleToken == nullptr) {
3885 return nullptr;
3886 }
3887
3888 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3889 if (windowHandle->getToken() == windowHandleToken) {
3890 return windowHandle;
3891 }
3892 }
3893 return nullptr;
3894}
3895
3896sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3897 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3898 return getWindowHandleLocked(focusedToken, displayId);
3899}
3900
Mady Mellor017bcd12020-06-23 19:12:00 +00003901bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3902 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003903 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003904 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003905 if (handle->getId() == windowHandle->getId() &&
3906 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003907 if (windowHandle->getInfo()->displayId != it.first) {
3908 ALOGE("Found window %s in display %" PRId32
3909 ", but it should belong to display %" PRId32,
3910 windowHandle->getName().c_str(), it.first,
3911 windowHandle->getInfo()->displayId);
3912 }
3913 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 }
3916 }
3917 return false;
3918}
3919
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003920bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3921 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3922 const bool noInputChannel =
3923 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3924 if (connection != nullptr && noInputChannel) {
3925 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3926 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3927 return false;
3928 }
3929
3930 if (connection == nullptr) {
3931 if (!noInputChannel) {
3932 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3933 }
3934 return false;
3935 }
3936 if (!connection->responsive) {
3937 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3938 return false;
3939 }
3940 return true;
3941}
3942
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003943std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3944 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003945 size_t count = mInputChannelsByToken.count(token);
3946 if (count == 0) {
3947 return nullptr;
3948 }
3949 return mInputChannelsByToken.at(token);
3950}
3951
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003952void InputDispatcher::updateWindowHandlesForDisplayLocked(
3953 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3954 if (inputWindowHandles.empty()) {
3955 // Remove all handles on a display if there are no windows left.
3956 mWindowHandlesByDisplay.erase(displayId);
3957 return;
3958 }
3959
3960 // Since we compare the pointer of input window handles across window updates, we need
3961 // to make sure the handle object for the same window stays unchanged across updates.
3962 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003963 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003964 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003965 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003966 }
3967
3968 std::vector<sp<InputWindowHandle>> newHandles;
3969 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3970 if (!handle->updateInfo()) {
3971 // handle no longer valid
3972 continue;
3973 }
3974
3975 const InputWindowInfo* info = handle->getInfo();
3976 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3977 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3978 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003979 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3980 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3981 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003982 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003983 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003984 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003985 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003986 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003987 }
3988
3989 if (info->displayId != displayId) {
3990 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3991 handle->getName().c_str(), displayId, info->displayId);
3992 continue;
3993 }
3994
Robert Carredd13602020-04-13 17:24:34 -07003995 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3996 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003997 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003998 oldHandle->updateFrom(handle);
3999 newHandles.push_back(oldHandle);
4000 } else {
4001 newHandles.push_back(handle);
4002 }
4003 }
4004
4005 // Insert or replace
4006 mWindowHandlesByDisplay[displayId] = newHandles;
4007}
4008
Arthur Hung72d8dc32020-03-28 00:48:39 +00004009void InputDispatcher::setInputWindows(
4010 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4011 { // acquire lock
4012 std::scoped_lock _l(mLock);
4013 for (auto const& i : handlesPerDisplay) {
4014 setInputWindowsLocked(i.second, i.first);
4015 }
4016 }
4017 // Wake up poll loop since it may need to make new input dispatching choices.
4018 mLooper->wake();
4019}
4020
Arthur Hungb92218b2018-08-14 12:00:21 +08004021/**
4022 * Called from InputManagerService, update window handle list by displayId that can receive input.
4023 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4024 * If set an empty list, remove all handles from the specific display.
4025 * For focused handle, check if need to change and send a cancel event to previous one.
4026 * For removed handle, check if need to send a cancel event if already in touch.
4027 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004028void InputDispatcher::setInputWindowsLocked(
4029 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004030 if (DEBUG_FOCUS) {
4031 std::string windowList;
4032 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4033 windowList += iwh->getName() + " ";
4034 }
4035 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004038 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4039 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4040 const bool noInputWindow =
4041 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4042 if (noInputWindow && window->getToken() != nullptr) {
4043 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4044 window->getName().c_str());
4045 window->releaseChannel();
4046 }
4047 }
4048
Arthur Hung72d8dc32020-03-28 00:48:39 +00004049 // Copy old handles for release if they are no longer present.
4050 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
Arthur Hung72d8dc32020-03-28 00:48:39 +00004052 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004053
Vishnu Nair958da932020-08-21 17:12:37 -07004054 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4055 if (mLastHoverWindowHandle &&
4056 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4057 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004058 mLastHoverWindowHandle = nullptr;
4059 }
4060
Vishnu Nair958da932020-08-21 17:12:37 -07004061 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4062 if (focusedToken) {
4063 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4064 if (result != FocusResult::OK) {
4065 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4066 }
4067 }
4068
4069 std::optional<FocusRequest> focusRequest =
4070 getOptionalValueByKey(mPendingFocusRequests, displayId);
4071 if (focusRequest) {
4072 // If the window from the pending request is now visible, provide it focus.
4073 FocusResult result = handleFocusRequestLocked(*focusRequest);
4074 if (result != FocusResult::NOT_VISIBLE) {
4075 // Drop the request if we were able to change the focus or we cannot change
4076 // it for another reason.
4077 mPendingFocusRequests.erase(displayId);
4078 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004081 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4082 mTouchStatesByDisplay.find(displayId);
4083 if (stateIt != mTouchStatesByDisplay.end()) {
4084 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004085 for (size_t i = 0; i < state.windows.size();) {
4086 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004087 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004088 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004089 ALOGD("Touched window was removed: %s in display %" PRId32,
4090 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004091 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004092 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004093 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4094 if (touchedInputChannel != nullptr) {
4095 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4096 "touched window was removed");
4097 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004099 state.windows.erase(state.windows.begin() + i);
4100 } else {
4101 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 }
4103 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004104 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004105
Arthur Hung72d8dc32020-03-28 00:48:39 +00004106 // Release information for windows that are no longer present.
4107 // This ensures that unused input channels are released promptly.
4108 // Otherwise, they might stick around until the window handle is destroyed
4109 // which might not happen until the next GC.
4110 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004111 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004112 if (DEBUG_FOCUS) {
4113 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004114 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004115 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004116 }
chaviw291d88a2019-02-14 10:33:58 -08004117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118}
4119
4120void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004121 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004122 if (DEBUG_FOCUS) {
4123 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4124 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4125 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004126 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004127 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128
Chris Yea209fde2020-07-22 13:54:51 -07004129 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004130 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004131
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004132 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4133 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004134 }
4135
Chris Yea209fde2020-07-22 13:54:51 -07004136 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004137 if (inputApplicationHandle != nullptr) {
4138 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4139 } else {
4140 mFocusedApplicationHandlesByDisplay.erase(displayId);
4141 }
4142
4143 // No matter what the old focused application was, stop waiting on it because it is
4144 // no longer focused.
4145 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 } // release lock
4147
4148 // Wake up poll loop since it may need to make new input dispatching choices.
4149 mLooper->wake();
4150}
4151
Tiger Huang721e26f2018-07-24 22:26:19 +08004152/**
4153 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4154 * the display not specified.
4155 *
4156 * We track any unreleased events for each window. If a window loses the ability to receive the
4157 * released event, we will send a cancel event to it. So when the focused display is changed, we
4158 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4159 * display. The display-specified events won't be affected.
4160 */
4161void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004162 if (DEBUG_FOCUS) {
4163 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4164 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004165 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004166 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004167
4168 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004169 sp<IBinder> oldFocusedWindowToken =
4170 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4171 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004172 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004173 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004174 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 CancelationOptions
4176 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4177 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004178 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004179 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4180 }
4181 }
4182 mFocusedDisplayId = displayId;
4183
Chris Ye3c2d6f52020-08-09 10:39:48 -07004184 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004185 sp<IBinder> newFocusedWindowToken =
4186 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4187 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004188
Vishnu Nairad321cd2020-08-20 16:40:21 -07004189 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004190 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004191 if (!mFocusedWindowTokenByDisplay.empty()) {
4192 ALOGE("But another display has a focused window\n%s",
4193 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004194 }
4195 }
4196 }
4197
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004198 if (DEBUG_FOCUS) {
4199 logDispatchStateLocked();
4200 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004201 } // release lock
4202
4203 // Wake up poll loop since it may need to make new input dispatching choices.
4204 mLooper->wake();
4205}
4206
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004208 if (DEBUG_FOCUS) {
4209 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211
4212 bool changed;
4213 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004214 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215
4216 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4217 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004218 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 }
4220
4221 if (mDispatchEnabled && !enabled) {
4222 resetAndDropEverythingLocked("dispatcher is being disabled");
4223 }
4224
4225 mDispatchEnabled = enabled;
4226 mDispatchFrozen = frozen;
4227 changed = true;
4228 } else {
4229 changed = false;
4230 }
4231
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004232 if (DEBUG_FOCUS) {
4233 logDispatchStateLocked();
4234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 } // release lock
4236
4237 if (changed) {
4238 // Wake up poll loop since it may need to make new input dispatching choices.
4239 mLooper->wake();
4240 }
4241}
4242
4243void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004244 if (DEBUG_FOCUS) {
4245 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247
4248 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004249 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250
4251 if (mInputFilterEnabled == enabled) {
4252 return;
4253 }
4254
4255 mInputFilterEnabled = enabled;
4256 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4257 } // release lock
4258
4259 // Wake up poll loop since there might be work to do to drop everything.
4260 mLooper->wake();
4261}
4262
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004263void InputDispatcher::setInTouchMode(bool inTouchMode) {
4264 std::scoped_lock lock(mLock);
4265 mInTouchMode = inTouchMode;
4266}
4267
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004268void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4269 if (opacity < 0 || opacity > 1) {
4270 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4271 return;
4272 }
4273
4274 std::scoped_lock lock(mLock);
4275 mMaximumObscuringOpacityForTouch = opacity;
4276}
4277
4278void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4279 std::scoped_lock lock(mLock);
4280 mBlockUntrustedTouchesMode = mode;
4281}
4282
chaviwfbe5d9c2018-12-26 12:23:37 -08004283bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4284 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004285 if (DEBUG_FOCUS) {
4286 ALOGD("Trivial transfer to same window.");
4287 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004288 return true;
4289 }
4290
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004292 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
chaviwfbe5d9c2018-12-26 12:23:37 -08004294 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4295 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004296 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004297 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 return false;
4299 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004300 if (DEBUG_FOCUS) {
4301 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4302 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004305 if (DEBUG_FOCUS) {
4306 ALOGD("Cannot transfer focus because windows are on different displays.");
4307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 return false;
4309 }
4310
4311 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004312 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4313 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004314 for (size_t i = 0; i < state.windows.size(); i++) {
4315 const TouchedWindow& touchedWindow = state.windows[i];
4316 if (touchedWindow.windowHandle == fromWindowHandle) {
4317 int32_t oldTargetFlags = touchedWindow.targetFlags;
4318 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004320 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004322 int32_t newTargetFlags = oldTargetFlags &
4323 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4324 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004325 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Jeff Brownf086ddb2014-02-11 14:28:48 -08004327 found = true;
4328 goto Found;
4329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 }
4331 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004332 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004334 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004335 if (DEBUG_FOCUS) {
4336 ALOGD("Focus transfer failed because from window did not have focus.");
4337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 return false;
4339 }
4340
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004341 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4342 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004343 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004344 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004345 CancelationOptions
4346 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4347 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004349 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
4351
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004352 if (DEBUG_FOCUS) {
4353 logDispatchStateLocked();
4354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 } // release lock
4356
4357 // Wake up poll loop since it may need to make new input dispatching choices.
4358 mLooper->wake();
4359 return true;
4360}
4361
4362void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004363 if (DEBUG_FOCUS) {
4364 ALOGD("Resetting and dropping all events (%s).", reason);
4365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
4367 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4368 synthesizeCancelationEventsForAllConnectionsLocked(options);
4369
4370 resetKeyRepeatLocked();
4371 releasePendingEventLocked();
4372 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004373 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004375 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004376 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004378 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379}
4380
4381void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004382 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 dumpDispatchStateLocked(dump);
4384
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004385 std::istringstream stream(dump);
4386 std::string line;
4387
4388 while (std::getline(stream, line, '\n')) {
4389 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 }
4391}
4392
Vishnu Nairad321cd2020-08-20 16:40:21 -07004393std::string InputDispatcher::dumpFocusedWindowsLocked() {
4394 if (mFocusedWindowTokenByDisplay.empty()) {
4395 return INDENT "FocusedWindows: <none>\n";
4396 }
4397
4398 std::string dump;
4399 dump += INDENT "FocusedWindows:\n";
4400 for (auto& it : mFocusedWindowTokenByDisplay) {
4401 const int32_t displayId = it.first;
4402 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4403 if (windowHandle) {
4404 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4405 windowHandle->getName().c_str());
4406 } else {
4407 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4408 " has focused token without a window'\n",
4409 displayId);
4410 }
4411 }
4412 return dump;
4413}
4414
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004415std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4416 if (mPendingFocusRequests.empty()) {
4417 return INDENT "mPendingFocusRequests: <none>\n";
4418 }
4419
4420 std::string dump;
4421 dump += INDENT "mPendingFocusRequests:\n";
4422 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4423 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4424 // try to resolve them to actual windows.
4425 std::string windowName = getConnectionNameLocked(focusRequest.token);
4426 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4427 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4428 displayId, windowName.c_str(), focusedWindowName.c_str());
4429 }
4430 return dump;
4431}
4432
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004433void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004434 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4435 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4436 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004437 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438
Tiger Huang721e26f2018-07-24 22:26:19 +08004439 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4440 dump += StringPrintf(INDENT "FocusedApplications:\n");
4441 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4442 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004443 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004444 const std::chrono::duration timeout =
4445 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004446 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004447 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004448 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004451 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004453
Vishnu Nairad321cd2020-08-20 16:40:21 -07004454 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004455 dump += dumpPendingFocusRequestsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004457 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004458 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004459 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4460 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004461 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004462 state.displayId, toString(state.down), toString(state.split),
4463 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004464 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004465 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004466 for (size_t i = 0; i < state.windows.size(); i++) {
4467 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004468 dump += StringPrintf(INDENT4
4469 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4470 i, touchedWindow.windowHandle->getName().c_str(),
4471 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004472 }
4473 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004474 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004475 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004476 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004477 dump += INDENT3 "Portal windows:\n";
4478 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004479 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004480 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4481 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004482 }
4483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 }
4485 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004486 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
4488
Arthur Hungb92218b2018-08-14 12:00:21 +08004489 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004490 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004491 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004492 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004493 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004494 dump += INDENT2 "Windows:\n";
4495 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004496 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004497 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004499 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004500 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004501 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Michael Wright44753b12020-07-08 13:48:11 +01004502 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004504 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004505 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004506 i, windowInfo->name.c_str(), windowInfo->id,
4507 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004508 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004509 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004510 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004511 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004512 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004513 static_cast<int32_t>(windowInfo->type),
4514 windowInfo->frameLeft, windowInfo->frameTop,
4515 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004516 windowInfo->globalScaleFactor,
4517 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004518 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004519 dump += StringPrintf(", inputFeatures=%s",
4520 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004521 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004522 "ms, trustedOverlay=%s, hasToken=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004524 millis(windowInfo->dispatchingTimeout),
4525 toString(windowInfo->trustedOverlay),
4526 toString(windowInfo->token != nullptr));
chaviw85b44202020-07-24 11:46:21 -07004527 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004528 }
4529 } else {
4530 dump += INDENT2 "Windows: <none>\n";
4531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 }
4533 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004534 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 }
4536
Michael Wright3dd60e22019-03-27 22:06:44 +00004537 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004538 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004539 const std::vector<Monitor>& monitors = it.second;
4540 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4541 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004542 }
4543 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004544 const std::vector<Monitor>& monitors = it.second;
4545 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4546 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004549 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 }
4551
4552 nsecs_t currentTime = now();
4553
4554 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004555 if (!mRecentQueue.empty()) {
4556 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004557 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004558 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004559 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004560 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 }
4562 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004563 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 }
4565
4566 // Dump event currently being dispatched.
4567 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004568 dump += INDENT "PendingEvent:\n";
4569 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004570 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004571 dump += StringPrintf(", age=%" PRId64 "ms\n",
4572 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004574 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 }
4576
4577 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004578 if (!mInboundQueue.empty()) {
4579 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004580 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004581 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004582 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004583 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 }
4585 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004586 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 }
4588
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004589 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004590 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004591 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4592 const KeyReplacement& replacement = pair.first;
4593 int32_t newKeyCode = pair.second;
4594 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004595 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004596 }
4597 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004598 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004599 }
4600
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004601 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004602 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004603 for (const auto& pair : mConnectionsByFd) {
4604 const sp<Connection>& connection = pair.second;
4605 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004607 pair.first, connection->getInputChannelName().c_str(),
4608 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004611 if (!connection->outboundQueue.empty()) {
4612 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4613 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004614 dump += dumpQueue(connection->outboundQueue, currentTime);
4615
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004617 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 }
4619
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004620 if (!connection->waitQueue.empty()) {
4621 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4622 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004623 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004625 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 }
4627 }
4628 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004629 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 }
4631
4632 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004633 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4634 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004636 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 }
4638
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004639 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004640 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4641 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4642 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643}
4644
Michael Wright3dd60e22019-03-27 22:06:44 +00004645void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4646 const size_t numMonitors = monitors.size();
4647 for (size_t i = 0; i < numMonitors; i++) {
4648 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004649 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004650 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4651 dump += "\n";
4652 }
4653}
4654
Garfield Tan15601662020-09-22 15:32:38 -07004655base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4656 const std::string& name) {
4657#if DEBUG_CHANNEL_CREATION
4658 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659#endif
4660
Garfield Tan15601662020-09-22 15:32:38 -07004661 std::shared_ptr<InputChannel> serverChannel;
4662 std::unique_ptr<InputChannel> clientChannel;
4663 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4664
4665 if (result) {
4666 return base::Error(result) << "Failed to open input channel pair with name " << name;
4667 }
4668
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004670 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004671 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672
Garfield Tan15601662020-09-22 15:32:38 -07004673 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004674 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004675 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4678 } // release lock
4679
4680 // Wake the looper because some connections have changed.
4681 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004682 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683}
4684
Garfield Tan15601662020-09-22 15:32:38 -07004685base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4686 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4687 std::shared_ptr<InputChannel> serverChannel;
4688 std::unique_ptr<InputChannel> clientChannel;
4689 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4690 if (result) {
4691 return base::Error(result) << "Failed to open input channel pair with name " << name;
4692 }
4693
Michael Wright3dd60e22019-03-27 22:06:44 +00004694 { // acquire lock
4695 std::scoped_lock _l(mLock);
4696
4697 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004698 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4699 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004700 }
4701
Garfield Tan15601662020-09-22 15:32:38 -07004702 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004703
Garfield Tan15601662020-09-22 15:32:38 -07004704 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004705 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004706 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004707
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004708 auto& monitorsByDisplay =
4709 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004710 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004711
4712 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004713 }
Garfield Tan15601662020-09-22 15:32:38 -07004714
Michael Wright3dd60e22019-03-27 22:06:44 +00004715 // Wake the looper because some connections have changed.
4716 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004717 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004718}
4719
Garfield Tan15601662020-09-22 15:32:38 -07004720status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004722 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
Garfield Tan15601662020-09-22 15:32:38 -07004724 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 if (status) {
4726 return status;
4727 }
4728 } // release lock
4729
4730 // Wake the poll loop because removing the connection may have changed the current
4731 // synchronization state.
4732 mLooper->wake();
4733 return OK;
4734}
4735
Garfield Tan15601662020-09-22 15:32:38 -07004736status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4737 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004738 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004739 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004740 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 return BAD_VALUE;
4742 }
4743
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004744 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004745 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004746
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004748 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 }
4750
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004751 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
4753 nsecs_t currentTime = now();
4754 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4755
4756 connection->status = Connection::STATUS_ZOMBIE;
4757 return OK;
4758}
4759
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004760void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4761 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4762 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004763}
4764
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004765void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004766 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004767 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004768 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004769 std::vector<Monitor>& monitors = it->second;
4770 const size_t numMonitors = monitors.size();
4771 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004772 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 monitors.erase(monitors.begin() + i);
4774 break;
4775 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004776 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004777 if (monitors.empty()) {
4778 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004779 } else {
4780 ++it;
4781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 }
4783}
4784
Michael Wright3dd60e22019-03-27 22:06:44 +00004785status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4786 { // acquire lock
4787 std::scoped_lock _l(mLock);
4788 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4789
4790 if (!foundDisplayId) {
4791 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4792 return BAD_VALUE;
4793 }
4794 int32_t displayId = foundDisplayId.value();
4795
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004796 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4797 mTouchStatesByDisplay.find(displayId);
4798 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004799 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4800 return BAD_VALUE;
4801 }
4802
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004803 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004804 std::optional<int32_t> foundDeviceId;
4805 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004806 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004807 foundDeviceId = state.deviceId;
4808 }
4809 }
4810 if (!foundDeviceId || !state.down) {
4811 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004813 return BAD_VALUE;
4814 }
4815 int32_t deviceId = foundDeviceId.value();
4816
4817 // Send cancel events to all the input channels we're stealing from.
4818 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004819 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004820 options.deviceId = deviceId;
4821 options.displayId = displayId;
4822 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004823 std::shared_ptr<InputChannel> channel =
4824 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004825 if (channel != nullptr) {
4826 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4827 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004828 }
4829 // Then clear the current touch state so we stop dispatching to them as well.
4830 state.filterNonMonitors();
4831 }
4832 return OK;
4833}
4834
Michael Wright3dd60e22019-03-27 22:06:44 +00004835std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4836 const sp<IBinder>& token) {
4837 for (const auto& it : mGestureMonitorsByDisplay) {
4838 const std::vector<Monitor>& monitors = it.second;
4839 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004840 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004841 return it.first;
4842 }
4843 }
4844 }
4845 return std::nullopt;
4846}
4847
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004848sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004849 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004850 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004851 }
4852
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004853 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004854 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004855 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004856 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858 }
Robert Carr4e670e52018-08-15 13:26:12 -07004859
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004860 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861}
4862
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004863std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
4864 sp<Connection> connection = getConnectionLocked(connectionToken);
4865 if (connection == nullptr) {
4866 return "<nullptr>";
4867 }
4868 return connection->getInputChannelName();
4869}
4870
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004871void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004873 removeByValue(mConnectionsByFd, connection);
4874}
4875
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004876void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4877 const sp<Connection>& connection, uint32_t seq,
4878 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004879 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4880 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 commandEntry->connection = connection;
4882 commandEntry->eventTime = currentTime;
4883 commandEntry->seq = seq;
4884 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004885 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886}
4887
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004888void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4889 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004891 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004893 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4894 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004896 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897}
4898
Vishnu Nairad321cd2020-08-20 16:40:21 -07004899void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4900 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004901 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4902 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004903 commandEntry->oldToken = oldToken;
4904 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004905 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004906}
4907
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004908void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004909 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4910 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004911 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004912 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004913 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914 return;
4915 }
4916 /**
4917 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4918 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4919 * has changed. This could cause newer entries to time out before the already dispatched
4920 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4921 * processes the events linearly. So providing information about the oldest entry seems to be
4922 * most useful.
4923 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004924 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004925 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4926 std::string reason =
4927 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004928 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004929 ns2ms(currentWait),
4930 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06004931 sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
4932 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004933
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004934 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4935 &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06004936 commandEntry->connectionToken = connectionToken;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004937 commandEntry->reason = std::move(reason);
4938 postCommandLocked(std::move(commandEntry));
4939}
4940
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004941void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
4942 std::string reason =
4943 StringPrintf("%s does not have a focused window", application->getName().c_str());
4944 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004945
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004946 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4947 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
4948 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004949 postCommandLocked(std::move(commandEntry));
4950}
4951
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004952void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
4953 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4954 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
4955 commandEntry->obscuringPackage = obscuringPackage;
4956 postCommandLocked(std::move(commandEntry));
4957}
4958
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004959void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4960 const std::string& reason) {
4961 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4962 updateLastAnrStateLocked(windowLabel, reason);
4963}
4964
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004965void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
4966 const std::string& reason) {
4967 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004968 updateLastAnrStateLocked(windowLabel, reason);
4969}
4970
4971void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4972 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004974 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 struct tm tm;
4976 localtime_r(&t, &tm);
4977 char timestr[64];
4978 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004979 mLastAnrState.clear();
4980 mLastAnrState += INDENT "ANR:\n";
4981 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004982 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4983 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004984 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985}
4986
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004987void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 mLock.unlock();
4989
4990 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4991
4992 mLock.lock();
4993}
4994
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996 sp<Connection> connection = commandEntry->connection;
4997
4998 if (connection->status != Connection::STATUS_ZOMBIE) {
4999 mLock.unlock();
5000
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005001 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002
5003 mLock.lock();
5004 }
5005}
5006
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005008 sp<IBinder> oldToken = commandEntry->oldToken;
5009 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005010 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005011 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005012 mLock.lock();
5013}
5014
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005015void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005017
5018 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5019
5020 mLock.lock();
5021}
5022
5023void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
5024 CommandEntry* commandEntry) {
5025 mLock.unlock();
5026
5027 mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028
5029 mLock.lock();
5030
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005031 // stop waking up for events in this connection, it is already not responding
5032 sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
5033 if (connection == nullptr) {
5034 return;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005035 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005036 cancelEventsForAnrLocked(connection);
5037}
5038
5039void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5040 mLock.unlock();
5041
5042 mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
5043
5044 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005045}
5046
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005047void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5048 mLock.unlock();
5049
5050 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5051
5052 mLock.lock();
5053}
5054
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5056 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005057 KeyEntry& entry = *(commandEntry->keyEntry);
5058 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059
5060 mLock.unlock();
5061
Michael Wright2b3c3302018-03-02 17:19:13 +00005062 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005063 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005064 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005065 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5066 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005067 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069
5070 mLock.lock();
5071
5072 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005073 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005075 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005077 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5078 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080}
5081
chaviwfd6d3512019-03-25 13:23:49 -07005082void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5083 mLock.unlock();
5084 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5085 mLock.lock();
5086}
5087
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005088/**
5089 * Connection is responsive if it has no events in the waitQueue that are older than the
5090 * current time.
5091 */
5092static bool isConnectionResponsive(const Connection& connection) {
5093 const nsecs_t currentTime = now();
5094 for (const DispatchEntry* entry : connection.waitQueue) {
5095 if (entry->timeoutTime < currentTime) {
5096 return false;
5097 }
5098 }
5099 return true;
5100}
5101
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005102void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005104 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005106 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107
5108 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005109 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005110 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005111 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005113 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005114 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005115 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005116 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5117 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005118 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005119 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005120
5121 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005122 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005123 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005124 restartEvent =
5125 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005126 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005127 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005128 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5129 handled);
5130 } else {
5131 restartEvent = false;
5132 }
5133
5134 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005135 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005136 // contents of the wait queue to have been drained, so we need to double-check
5137 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005138 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5139 if (dispatchEntryIt != connection->waitQueue.end()) {
5140 dispatchEntry = *dispatchEntryIt;
5141 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005142 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5143 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005144 if (!connection->responsive) {
5145 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005146 if (connection->responsive) {
5147 // The connection was unresponsive, and now it's responsive. Tell the policy
5148 // about it so that it can stop ANR.
5149 std::unique_ptr<CommandEntry> connectionResponsiveCommand =
5150 std::make_unique<CommandEntry>(
5151 &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
5152 connectionResponsiveCommand->connectionToken = connectionToken;
5153 postCommandLocked(std::move(connectionResponsiveCommand));
5154 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005155 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005156 traceWaitQueueLength(connection);
5157 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005158 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005159 traceOutboundQueueLength(connection);
5160 } else {
5161 releaseDispatchEntry(dispatchEntry);
5162 }
5163 }
5164
5165 // Start the next dispatch cycle for this connection.
5166 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167}
5168
5169bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005170 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005171 KeyEntry& keyEntry, bool handled) {
5172 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005173 if (!handled) {
5174 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005175 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005176 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005177 return false;
5178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005180 // Get the fallback key state.
5181 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005182 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005183 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005184 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005185 connection->inputState.removeFallbackKey(originalKeyCode);
5186 }
5187
5188 if (handled || !dispatchEntry->hasForegroundTarget()) {
5189 // If the application handles the original key for which we previously
5190 // generated a fallback or if the window is not a foreground window,
5191 // then cancel the associated fallback key, if any.
5192 if (fallbackKeyCode != -1) {
5193 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005195 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005196 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005197 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005199 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005200 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201
5202 mLock.unlock();
5203
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005204 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005205 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206
5207 mLock.lock();
5208
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005209 // Cancel the fallback key.
5210 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005212 "application handled the original non-fallback key "
5213 "or is no longer a foreground target, "
5214 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 options.keyCode = fallbackKeyCode;
5216 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005218 connection->inputState.removeFallbackKey(originalKeyCode);
5219 }
5220 } else {
5221 // If the application did not handle a non-fallback key, first check
5222 // that we are in a good state to perform unhandled key event processing
5223 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005224 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005225 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005227 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005228 "since this is not an initial down. "
5229 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005230 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005232 return false;
5233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005235 // Dispatch the unhandled key to the policy.
5236#if DEBUG_OUTBOUND_EVENT_DETAILS
5237 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005238 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005239 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005240#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005241 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005242
5243 mLock.unlock();
5244
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005245 bool fallback =
5246 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005247 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005248
5249 mLock.lock();
5250
5251 if (connection->status != Connection::STATUS_NORMAL) {
5252 connection->inputState.removeFallbackKey(originalKeyCode);
5253 return false;
5254 }
5255
5256 // Latch the fallback keycode for this key on an initial down.
5257 // The fallback keycode cannot change at any other point in the lifecycle.
5258 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005260 fallbackKeyCode = event.getKeyCode();
5261 } else {
5262 fallbackKeyCode = AKEYCODE_UNKNOWN;
5263 }
5264 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5265 }
5266
5267 ALOG_ASSERT(fallbackKeyCode != -1);
5268
5269 // Cancel the fallback key if the policy decides not to send it anymore.
5270 // We will continue to dispatch the key to the policy but we will no
5271 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005272 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5273 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005274#if DEBUG_OUTBOUND_EVENT_DETAILS
5275 if (fallback) {
5276 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005277 "as a fallback for %d, but on the DOWN it had requested "
5278 "to send %d instead. Fallback canceled.",
5279 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005280 } else {
5281 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005282 "but on the DOWN it had requested to send %d. "
5283 "Fallback canceled.",
5284 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005285 }
5286#endif
5287
5288 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5289 "canceling fallback, policy no longer desires it");
5290 options.keyCode = fallbackKeyCode;
5291 synthesizeCancelationEventsForConnectionLocked(connection, options);
5292
5293 fallback = false;
5294 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005295 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005297 }
5298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299
5300#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005301 {
5302 std::string msg;
5303 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5304 connection->inputState.getFallbackKeys();
5305 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005306 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005308 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005309 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005310 }
5311#endif
5312
5313 if (fallback) {
5314 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005315 keyEntry.eventTime = event.getEventTime();
5316 keyEntry.deviceId = event.getDeviceId();
5317 keyEntry.source = event.getSource();
5318 keyEntry.displayId = event.getDisplayId();
5319 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5320 keyEntry.keyCode = fallbackKeyCode;
5321 keyEntry.scanCode = event.getScanCode();
5322 keyEntry.metaState = event.getMetaState();
5323 keyEntry.repeatCount = event.getRepeatCount();
5324 keyEntry.downTime = event.getDownTime();
5325 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005326
5327#if DEBUG_OUTBOUND_EVENT_DETAILS
5328 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005329 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005330 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005331#endif
5332 return true; // restart the event
5333 } else {
5334#if DEBUG_OUTBOUND_EVENT_DETAILS
5335 ALOGD("Unhandled key event: No fallback key.");
5336#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005337
5338 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005339 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 }
5341 }
5342 return false;
5343}
5344
5345bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005346 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005347 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 return false;
5349}
5350
5351void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5352 mLock.unlock();
5353
5354 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5355
5356 mLock.lock();
5357}
5358
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005359KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5360 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005361 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005362 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5363 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005364 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365}
5366
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005367void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5368 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 // TODO Write some statistics about how long we spend waiting.
5370}
5371
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005372/**
5373 * Report the touch event latency to the statsd server.
5374 * Input events are reported for statistics if:
5375 * - This is a touchscreen event
5376 * - InputFilter is not enabled
5377 * - Event is not injected or synthesized
5378 *
5379 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5380 * from getting aggregated with the "old" data.
5381 */
5382void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5383 REQUIRES(mLock) {
5384 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5385 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5386 if (!reportForStatistics) {
5387 return;
5388 }
5389
5390 if (mTouchStatistics.shouldReport()) {
5391 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5392 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5393 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5394 mTouchStatistics.reset();
5395 }
5396 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5397 mTouchStatistics.addValue(latencyMicros);
5398}
5399
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400void InputDispatcher::traceInboundQueueLengthLocked() {
5401 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005402 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 }
5404}
5405
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005406void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 if (ATRACE_ENABLED()) {
5408 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005409 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005410 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 }
5412}
5413
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005414void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005415 if (ATRACE_ENABLED()) {
5416 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005417 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005418 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 }
5420}
5421
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005422void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005423 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005425 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 dumpDispatchStateLocked(dump);
5427
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005428 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005430 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 }
5432}
5433
5434void InputDispatcher::monitor() {
5435 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005436 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005438 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439}
5440
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005441/**
5442 * Wake up the dispatcher and wait until it processes all events and commands.
5443 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5444 * this method can be safely called from any thread, as long as you've ensured that
5445 * the work you are interested in completing has already been queued.
5446 */
5447bool InputDispatcher::waitForIdle() {
5448 /**
5449 * Timeout should represent the longest possible time that a device might spend processing
5450 * events and commands.
5451 */
5452 constexpr std::chrono::duration TIMEOUT = 100ms;
5453 std::unique_lock lock(mLock);
5454 mLooper->wake();
5455 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5456 return result == std::cv_status::no_timeout;
5457}
5458
Vishnu Naire798b472020-07-23 13:52:21 -07005459/**
5460 * Sets focus to the window identified by the token. This must be called
5461 * after updating any input window handles.
5462 *
5463 * Params:
5464 * request.token - input channel token used to identify the window that should gain focus.
5465 * request.focusedToken - the token that the caller expects currently to be focused. If the
5466 * specified token does not match the currently focused window, this request will be dropped.
5467 * If the specified focused token matches the currently focused window, the call will succeed.
5468 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5469 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5470 * when requesting the focus change. This determines which request gets
5471 * precedence if there is a focus change request from another source such as pointer down.
5472 */
Vishnu Nair958da932020-08-21 17:12:37 -07005473void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5474 { // acquire lock
5475 std::scoped_lock _l(mLock);
5476
5477 const int32_t displayId = request.displayId;
5478 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5479 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5480 ALOGD_IF(DEBUG_FOCUS,
5481 "setFocusedWindow on display %" PRId32
5482 " ignored, reason: focusedToken is not focused",
5483 displayId);
5484 return;
5485 }
5486
5487 mPendingFocusRequests.erase(displayId);
5488 FocusResult result = handleFocusRequestLocked(request);
5489 if (result == FocusResult::NOT_VISIBLE) {
5490 // The requested window is not currently visible. Wait for the window to become visible
5491 // and then provide it focus. This is to handle situations where a user action triggers
5492 // a new window to appear. We want to be able to queue any key events after the user
5493 // action and deliver it to the newly focused window. In order for this to happen, we
5494 // take focus from the currently focused window so key events can be queued.
5495 ALOGD_IF(DEBUG_FOCUS,
5496 "setFocusedWindow on display %" PRId32
5497 " pending, reason: window is not visible",
5498 displayId);
5499 mPendingFocusRequests[displayId] = request;
5500 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5501 "setFocusedWindow_AwaitingWindowVisibility");
5502 } else if (result != FocusResult::OK) {
5503 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5504 typeToString(result));
5505 }
5506 } // release lock
5507 // Wake up poll loop since it may need to make new input dispatching choices.
5508 mLooper->wake();
5509}
5510
5511InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5512 const FocusRequest& request) {
5513 const int32_t displayId = request.displayId;
5514 const sp<IBinder> newFocusedToken = request.token;
5515 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5516
5517 if (oldFocusedToken == request.token) {
5518 ALOGD_IF(DEBUG_FOCUS,
5519 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5520 displayId);
5521 return FocusResult::OK;
5522 }
5523
5524 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5525 if (result != FocusResult::OK) {
5526 return result;
5527 }
5528
5529 std::string_view reason =
5530 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5531 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5532 return FocusResult::OK;
5533}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005534
Vishnu Nairad321cd2020-08-20 16:40:21 -07005535void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5536 const sp<IBinder>& newFocusedToken, int32_t displayId,
5537 std::string_view reason) {
5538 if (oldFocusedToken) {
5539 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005540 if (focusedInputChannel) {
5541 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5542 "focus left window");
5543 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005544 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005545 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005546 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005547 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005548 if (newFocusedToken) {
5549 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5550 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005551 }
5552
5553 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005554 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005555 }
5556}
Vishnu Nair958da932020-08-21 17:12:37 -07005557
5558/**
5559 * Checks if the window token can be focused on a display. The token can be focused if there is
5560 * at least one window handle that is visible with the same token and all window handles with the
5561 * same token are focusable.
5562 *
5563 * In the case of mirroring, two windows may share the same window token and their visibility
5564 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5565 * we expect the focusability of the windows to match since its hard to reason why one window can
5566 * receive focus events and the other cannot when both are backed by the same input channel.
5567 */
5568InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5569 int32_t displayId) const {
5570 bool allWindowsAreFocusable = true;
5571 bool visibleWindowFound = false;
5572 bool windowFound = false;
5573 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5574 if (window->getToken() != token) {
5575 continue;
5576 }
5577 windowFound = true;
5578 if (window->getInfo()->visible) {
5579 // Check if at least a single window is visible.
5580 visibleWindowFound = true;
5581 }
5582 if (!window->getInfo()->focusable) {
5583 // Check if all windows with the window token are focusable.
5584 allWindowsAreFocusable = false;
5585 break;
5586 }
5587 }
5588
5589 if (!windowFound) {
5590 return FocusResult::NO_WINDOW;
5591 }
5592 if (!allWindowsAreFocusable) {
5593 return FocusResult::NOT_FOCUSABLE;
5594 }
5595 if (!visibleWindowFound) {
5596 return FocusResult::NOT_VISIBLE;
5597 }
5598
5599 return FocusResult::OK;
5600}
Garfield Tane84e6f92019-08-29 17:28:41 -07005601} // namespace android::inputdispatcher