blob: 80520849255acef5fef31af5e702183dee6bde8c [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
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800207static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800209 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 return;
211 }
212
213 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 }
225}
226
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500227static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
228 constexpr size_t maxEntries = 50; // max events to print
229 constexpr size_t skipBegin = maxEntries / 2;
230 const size_t skipEnd = queue.size() - maxEntries / 2;
231 // skip from maxEntries / 2 ... size() - maxEntries/2
232 // only print from 0 .. skipBegin and then from skipEnd .. size()
233
234 std::string dump;
235 for (size_t i = 0; i < queue.size(); i++) {
236 const DispatchEntry& entry = *queue[i];
237 if (i >= skipBegin && i < skipEnd) {
238 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
239 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
240 continue;
241 }
242 dump.append(INDENT4);
243 dump += entry.eventEntry->getDescription();
244 dump += StringPrintf(", seq=%" PRIu32
245 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
246 entry.seq, entry.targetFlags, entry.resolvedAction,
247 ns2ms(currentTime - entry.eventEntry->eventTime));
248 if (entry.deliveryTime != 0) {
249 // This entry was delivered, so add information on how long we've been waiting
250 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
251 }
252 dump.append("\n");
253 }
254 return dump;
255}
256
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700257/**
258 * Find the entry in std::unordered_map by key, and return it.
259 * If the entry is not found, return a default constructed entry.
260 *
261 * Useful when the entries are vectors, since an empty vector will be returned
262 * if the entry is not found.
263 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
264 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700265template <typename K, typename V>
266static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700267 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700268 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800269}
270
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700271/**
272 * Find the entry in std::unordered_map by value, and remove it.
273 * If more than one entry has the same value, then all matching
274 * key-value pairs will be removed.
275 *
276 * Return true if at least one value has been removed.
277 */
278template <typename K, typename V>
279static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
280 bool removed = false;
281 for (auto it = map.begin(); it != map.end();) {
282 if (it->second == value) {
283 it = map.erase(it);
284 removed = true;
285 } else {
286 it++;
287 }
288 }
289 return removed;
290}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291
Vishnu Nair958da932020-08-21 17:12:37 -0700292/**
293 * Find the entry in std::unordered_map by key and return the value as an optional.
294 */
295template <typename K, typename V>
296static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
297 auto it = map.find(key);
298 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
299}
300
chaviwaf87b3e2019-10-01 16:59:28 -0700301static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
302 if (first == second) {
303 return true;
304 }
305
306 if (first == nullptr || second == nullptr) {
307 return false;
308 }
309
310 return first->getToken() == second->getToken();
311}
312
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800313static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
314 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
315}
316
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
318 EventEntry* eventEntry,
319 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700320 if (inputTarget.useDefaultPointerTransform()) {
321 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000322 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700323 inputTargetFlags, transform,
324 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
330 PointerCoords pointerCoords[motionEntry.pointerCount];
331
332 // Use the first pointer information to normalize all other pointers. This could be any pointer
333 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700334 // uses the transform for the normalized pointer.
335 const ui::Transform& firstPointerTransform =
336 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
337 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000338
339 // Iterate through all pointers in the event to normalize against the first.
340 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
341 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
342 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700343 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000344
345 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700346 // First, apply the current pointer's transform to update the coordinates into
347 // window space.
348 pointerCoords[pointerIndex].transform(currTransform);
349 // Next, apply the inverse transform of the normalized coordinates so the
350 // current coordinates are transformed into the normalized coordinate space.
351 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 }
353
354 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800355 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
357 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
358 motionEntry.metaState, motionEntry.buttonState,
359 motionEntry.classification, motionEntry.edgeFlags,
360 motionEntry.xPrecision, motionEntry.yPrecision,
361 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
362 motionEntry.downTime, motionEntry.pointerCount,
363 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
364 0 /* yOffset */);
365
366 if (motionEntry.injectionState) {
367 combinedMotionEntry->injectionState = motionEntry.injectionState;
368 combinedMotionEntry->injectionState->refCount += 1;
369 }
370
371 std::unique_ptr<DispatchEntry> dispatchEntry =
372 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700373 inputTargetFlags, firstPointerTransform,
374 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000375 combinedMotionEntry->release();
376 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 {
564 // Keep waiting
565 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
566 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
567 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
568 }
569 }
570
571 // Check if any connection ANRs are due
572 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
573 if (currentTime < nextAnrCheck) { // most likely scenario
574 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
575 }
576
577 // If we reached here, we have an unresponsive connection.
578 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
579 if (connection == nullptr) {
580 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
581 return nextAnrCheck;
582 }
583 connection->responsive = false;
584 // Stop waking up for this unresponsive connection
585 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500586 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700587 return LONG_LONG_MIN;
588}
589
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500590std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700591 sp<InputWindowHandle> window = getWindowHandleLocked(token);
592 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500593 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700594 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500595 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700596}
597
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
599 nsecs_t currentTime = now();
600
Jeff Browndc5992e2014-04-11 01:27:26 -0700601 // Reset the key repeat timer whenever normal dispatch is suspended while the
602 // device is in a non-interactive state. This is to ensure that we abort a key
603 // repeat if the device is just coming out of sleep.
604 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 resetKeyRepeatLocked();
606 }
607
608 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
609 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100610 if (DEBUG_FOCUS) {
611 ALOGD("Dispatch frozen. Waiting some more.");
612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 return;
614 }
615
616 // Optimize latency of app switches.
617 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
618 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
619 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
620 if (mAppSwitchDueTime < *nextWakeupTime) {
621 *nextWakeupTime = mAppSwitchDueTime;
622 }
623
624 // Ready to start a new event.
625 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700627 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 if (isAppSwitchDue) {
629 // The inbound queue is empty so the app switch key we were waiting
630 // for will never arrive. Stop waiting for it.
631 resetPendingAppSwitchLocked(false);
632 isAppSwitchDue = false;
633 }
634
635 // Synthesize a key repeat if appropriate.
636 if (mKeyRepeatState.lastKeyEntry) {
637 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
638 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
639 } else {
640 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
641 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
642 }
643 }
644 }
645
646 // Nothing to do if there is no pending event.
647 if (!mPendingEvent) {
648 return;
649 }
650 } else {
651 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700652 mPendingEvent = mInboundQueue.front();
653 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 traceInboundQueueLengthLocked();
655 }
656
657 // Poke user activity for this event.
658 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700659 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 }
662
663 // Now we have an event to dispatch.
664 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700665 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700667 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700669 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700671 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 }
673
674 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700675 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677
678 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700679 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 ConfigurationChangedEntry* typedEntry =
681 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
682 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700683 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700684 break;
685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700687 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700688 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
689 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700690 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700691 break;
692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100694 case EventEntry::Type::FOCUS: {
695 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
696 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: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
704 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700705 if (isAppSwitchKeyEvent(*typedEntry)) {
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 Vishniakoud2770042019-10-29 11:08:14 -0700712 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
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 }
718 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
719 break;
720 }
721
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700722 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700723 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700724 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
725 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700727 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700728 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700730 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
731 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700732 }
733 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
734 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 }
737
738 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700739 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700740 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 }
Michael Wright3a981722015-06-10 15:26:13 +0100742 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743
744 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700745 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 }
747}
748
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700749/**
750 * Return true if the events preceding this incoming motion event should be dropped
751 * Return false otherwise (the default behaviour)
752 */
753bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700754 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700755 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700756
757 // Optimize case where the current application is unresponsive and the user
758 // decides to touch a window in a different application.
759 // If the application takes too long to catch up then we drop all events preceding
760 // the touch into the other window.
761 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700762 int32_t displayId = motionEntry.displayId;
763 int32_t x = static_cast<int32_t>(
764 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
765 int32_t y = static_cast<int32_t>(
766 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
767 sp<InputWindowHandle> touchedWindowHandle =
768 findTouchedWindowAtLocked(displayId, x, y, nullptr);
769 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700770 touchedWindowHandle->getApplicationToken() !=
771 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700772 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700773 ALOGI("Pruning input queue because user touched a different application while waiting "
774 "for %s",
775 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700776 return true;
777 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700778
779 // Alternatively, maybe there's a gesture monitor that could handle this event
780 std::vector<TouchedMonitor> gestureMonitors =
781 findTouchedGestureMonitorsLocked(displayId, {});
782 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
783 sp<Connection> connection =
784 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000785 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700786 // This monitor could take more input. Drop all events preceding this
787 // event, so that gesture monitor could get a chance to receive the stream
788 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
789 "responsive gesture monitor that may handle the event",
790 mAwaitedFocusedApplication->getName().c_str());
791 return true;
792 }
793 }
794 }
795
796 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
797 // yet been processed by some connections, the dispatcher will wait for these motion
798 // events to be processed before dispatching the key event. This is because these motion events
799 // may cause a new window to be launched, which the user might expect to receive focus.
800 // To prevent waiting forever for such events, just send the key to the currently focused window
801 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
802 ALOGD("Received a new pointer down event, stop waiting for events to process and "
803 "just send the pending key event to the focused window.");
804 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700805 }
806 return false;
807}
808
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700810 bool needWake = mInboundQueue.empty();
811 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 traceInboundQueueLengthLocked();
813
814 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700815 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 // Optimize app switch latency.
817 // If the application takes too long to catch up then we drop all events preceding
818 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700819 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700821 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700823 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700828 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829 mAppSwitchSawKeyDown = false;
830 needWake = true;
831 }
832 }
833 }
834 break;
835 }
836
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700837 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700838 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
839 mNextUnblockedEvent = entry;
840 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700842 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100844 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700845 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
846 break;
847 }
848 case EventEntry::Type::CONFIGURATION_CHANGED:
849 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700850 // nothing to do
851 break;
852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
854
855 return needWake;
856}
857
858void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
859 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700860 mRecentQueue.push_back(entry);
861 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
862 mRecentQueue.front()->release();
863 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()) {
1042 EventEntry* entry = mInboundQueue.front();
1043 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
1056void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1057 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 Vishniakouae6229e2019-12-30 16:23:19 -08001062 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);
1068 entry->release();
1069}
1070
1071void InputDispatcher::resetKeyRepeatLocked() {
1072 if (mKeyRepeatState.lastKeyEntry) {
1073 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001074 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076}
1077
Garfield Tane84e6f92019-08-29 17:28:41 -07001078KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1080
1081 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001082 uint32_t policyFlags = entry->policyFlags &
1083 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 if (entry->refCount == 1) {
1085 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001086 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 entry->eventTime = currentTime;
1088 entry->policyFlags = policyFlags;
1089 entry->repeatCount += 1;
1090 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001092 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001093 entry->displayId, policyFlags, entry->action, entry->flags,
1094 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096
1097 mKeyRepeatState.lastKeyEntry = newEntry;
1098 entry->release();
1099
1100 entry = newEntry;
1101 }
1102 entry->syntheticRepeat = true;
1103
1104 // Increment reference count since we keep a reference to the event in
1105 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1106 entry->refCount += 1;
1107
1108 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1109 return entry;
1110}
1111
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1113 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001115 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116#endif
1117
1118 // Reset key repeating in case a keyboard device was added or removed or something.
1119 resetKeyRepeatLocked();
1120
1121 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001122 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1123 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001125 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 return true;
1127}
1128
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001131 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133#endif
1134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 options.deviceId = entry->deviceId;
1137 synthesizeCancelationEventsForAllConnectionsLocked(options);
1138 return true;
1139}
1140
Vishnu Nairad321cd2020-08-20 16:40:21 -07001141void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001142 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001143 if (mPendingEvent != nullptr) {
1144 // Move the pending event to the front of the queue. This will give the chance
1145 // for the pending event to get dispatched to the newly focused window
1146 mInboundQueue.push_front(mPendingEvent);
1147 mPendingEvent = nullptr;
1148 }
1149
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001150 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001151 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001152
1153 // This event should go to the front of the queue, but behind all other focus events
1154 // Find the last focus event, and insert right after it
1155 std::deque<EventEntry*>::reverse_iterator it =
1156 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1157 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1158
1159 // Maintain the order of focus events. Insert the entry after all other focus events.
1160 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001161}
1162
1163void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001164 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001165 if (channel == nullptr) {
1166 return; // Window has gone away
1167 }
1168 InputTarget target;
1169 target.inputChannel = channel;
1170 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1171 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001172 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1173 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001174 std::string reason = std::string("reason=").append(entry->reason);
1175 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001176 dispatchEventLocked(currentTime, entry, {target});
1177}
1178
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001182 if (!entry->dispatchInProgress) {
1183 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1184 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1185 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1186 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001187 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 // We have seen two identical key downs in a row which indicates that the device
1189 // driver is automatically generating key repeats itself. We take note of the
1190 // repeat here, but we disable our own next key repeat timer since it is clear that
1191 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001192 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1193 // Make sure we don't get key down from a different device. If a different
1194 // device Id has same key pressed down, the new device Id will replace the
1195 // current one to hold the key repeat with repeat count reset.
1196 // In the future when got a KEY_UP on the device id, drop it and do not
1197 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1199 resetKeyRepeatLocked();
1200 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1201 } else {
1202 // Not a repeat. Save key down state in case we do see a repeat later.
1203 resetKeyRepeatLocked();
1204 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1205 }
1206 mKeyRepeatState.lastKeyEntry = entry;
1207 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001208 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1209 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1210 // The stale device releases the key, reset staleDeviceId.
1211#if DEBUG_INBOUND_EVENT_DETAILS
1212 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1213#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 resetKeyRepeatLocked();
1216 }
1217
1218 if (entry->repeatCount == 1) {
1219 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1220 } else {
1221 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1222 }
1223
1224 entry->dispatchInProgress = true;
1225
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001226 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 }
1228
1229 // Handle case where the policy asked us to try again later last time.
1230 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1231 if (currentTime < entry->interceptKeyWakeupTime) {
1232 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1233 *nextWakeupTime = entry->interceptKeyWakeupTime;
1234 }
1235 return false; // wait until next wakeup
1236 }
1237 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1238 entry->interceptKeyWakeupTime = 0;
1239 }
1240
1241 // Give the policy a chance to intercept the key.
1242 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1243 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001244 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001245 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001246 sp<IBinder> focusedWindowToken =
1247 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1248 if (focusedWindowToken != nullptr) {
1249 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 }
1251 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001252 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 entry->refCount += 1;
1254 return false; // wait for the command to run
1255 } else {
1256 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1257 }
1258 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001259 if (*dropReason == DropReason::NOT_DROPPED) {
1260 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 }
1262 }
1263
1264 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001265 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001266 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001267 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1268 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001269 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 return true;
1271 }
1272
1273 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001274 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001275 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001276 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001277 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 return false;
1279 }
1280
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001281 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001282 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 return true;
1284 }
1285
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001286 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001287 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
1289 // Dispatch the key.
1290 dispatchEventLocked(currentTime, entry, inputTargets);
1291 return true;
1292}
1293
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001294void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001296 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1298 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001299 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1300 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1301 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302#endif
1303}
1304
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1306 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001307 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 entry->dispatchInProgress = true;
1311
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001312 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 }
1314
1315 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001316 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001317 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001318 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1319 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 return true;
1321 }
1322
1323 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1324
1325 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001326 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327
1328 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001329 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 if (isPointerEvent) {
1331 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001332 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001333 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001334 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 } else {
1336 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001337 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001338 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001340 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 return false;
1342 }
1343
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001344 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001345 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001346 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1347 return true;
1348 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001349 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001350 CancelationOptions::Mode mode(isPointerEvent
1351 ? CancelationOptions::CANCEL_POINTER_EVENTS
1352 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1353 CancelationOptions options(mode, "input event injection failed");
1354 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 return true;
1356 }
1357
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001358 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001359 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001361 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001362 std::unordered_map<int32_t, TouchState>::iterator it =
1363 mTouchStatesByDisplay.find(entry->displayId);
1364 if (it != mTouchStatesByDisplay.end()) {
1365 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001366 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001367 // The event has gone through these portal windows, so we add monitoring targets of
1368 // the corresponding displays as well.
1369 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001370 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001371 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001372 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001373 }
1374 }
1375 }
1376 }
1377
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 // Dispatch the motion.
1379 if (conflictingPointerActions) {
1380 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 synthesizeCancelationEventsForAllConnectionsLocked(options);
1383 }
1384 dispatchEventLocked(currentTime, entry, inputTargets);
1385 return true;
1386}
1387
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001388void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001390 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001391 ", policyFlags=0x%x, "
1392 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1393 "metaState=0x%x, buttonState=0x%x,"
1394 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1396 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1397 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001399 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001401 "x=%f, y=%f, pressure=%f, size=%f, "
1402 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1403 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1405 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1406 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1407 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1408 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1409 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1410 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1411 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1412 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1413 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415#endif
1416}
1417
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001418void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1419 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001420 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421#if DEBUG_DISPATCH_CYCLE
1422 ALOGD("dispatchEventToCurrentInputTargets");
1423#endif
1424
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001425 updateInteractionTokensLocked(*eventEntry, inputTargets);
1426
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1428
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001429 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001431 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001432 sp<Connection> connection =
1433 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001434 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001435 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001437 if (DEBUG_FOCUS) {
1438 ALOGD("Dropping event delivery to target with channel '%s' because it "
1439 "is no longer registered with the input dispatcher.",
1440 inputTarget.inputChannel->getName().c_str());
1441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 }
1443 }
1444}
1445
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001446void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1447 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1448 // If the policy decides to close the app, we will get a channel removal event via
1449 // unregisterInputChannel, and will clean up the connection that way. We are already not
1450 // sending new pointers to the connection when it blocked, but focused events will continue to
1451 // pile up.
1452 ALOGW("Canceling events for %s because it is unresponsive",
1453 connection->inputChannel->getName().c_str());
1454 if (connection->status == Connection::STATUS_NORMAL) {
1455 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1456 "application not responding");
1457 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 }
1459}
1460
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001461void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001462 if (DEBUG_FOCUS) {
1463 ALOGD("Resetting ANR timeouts.");
1464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465
1466 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001467 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001468 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469}
1470
Tiger Huang721e26f2018-07-24 22:26:19 +08001471/**
1472 * Get the display id that the given event should go to. If this event specifies a valid display id,
1473 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1474 * Focused display is the display that the user most recently interacted with.
1475 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001476int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001477 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001479 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1481 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 break;
1483 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001484 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1486 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001487 break;
1488 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001489 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001490 case EventEntry::Type::CONFIGURATION_CHANGED:
1491 case EventEntry::Type::DEVICE_RESET: {
1492 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 return ADISPLAY_ID_NONE;
1494 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001495 }
1496 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1497}
1498
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001499bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1500 const char* focusedWindowName) {
1501 if (mAnrTracker.empty()) {
1502 // already processed all events that we waited for
1503 mKeyIsWaitingForEventsTimeout = std::nullopt;
1504 return false;
1505 }
1506
1507 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1508 // Start the timer
1509 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1510 "focus to change",
1511 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001512 mKeyIsWaitingForEventsTimeout = currentTime +
1513 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1514 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001515 return true;
1516 }
1517
1518 // We still have pending events, and already started the timer
1519 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1520 return true; // Still waiting
1521 }
1522
1523 // Waited too long, and some connection still hasn't processed all motions
1524 // Just send the key to the focused window
1525 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1526 focusedWindowName);
1527 mKeyIsWaitingForEventsTimeout = std::nullopt;
1528 return false;
1529}
1530
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001531InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1532 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1533 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001534 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
Tiger Huang721e26f2018-07-24 22:26:19 +08001536 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001537 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001538 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001539 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1540
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 // If there is no currently focused window and no focused application
1542 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001543 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1544 ALOGI("Dropping %s event because there is no focused window or focused application in "
1545 "display %" PRId32 ".",
1546 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 }
1549
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001550 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1551 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1552 // start interacting with another application via touch (app switch). This code can be removed
1553 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1554 // an app is expected to have a focused window.
1555 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1556 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1557 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001558 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1559 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1560 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001561 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001562 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001563 ALOGW("Waiting because no window has focus but %s may eventually add a "
1564 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001565 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001566 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001567 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001568 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1569 // Already raised ANR. Drop the event
1570 ALOGE("Dropping %s event because there is no focused window",
1571 EventEntry::typeToString(entry.type));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001572 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001573 } else {
1574 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001575 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001576 }
1577 }
1578
1579 // we have a valid, non-null focused window
1580 resetNoFocusedWindowTimeoutLocked();
1581
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001584 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 }
1586
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001587 if (focusedWindowHandle->getInfo()->paused) {
1588 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001590 }
1591
1592 // If the event is a key event, then we must wait for all previous events to
1593 // complete before delivering it because previous events may have the
1594 // side-effect of transferring focus to a different window and we want to
1595 // ensure that the following keys are sent to the new window.
1596 //
1597 // Suppose the user touches a button in a window then immediately presses "A".
1598 // If the button causes a pop-up window to appear then we want to ensure that
1599 // the "A" key is delivered to the new pop-up window. This is because users
1600 // often anticipate pending UI changes when typing on a keyboard.
1601 // To obtain this behavior, we must serialize key events with respect to all
1602 // prior input events.
1603 if (entry.type == EventEntry::Type::KEY) {
1604 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1605 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001606 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 }
1609
1610 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001611 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1613 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614
1615 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001616 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617}
1618
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001619/**
1620 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1621 * that are currently unresponsive.
1622 */
1623std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1624 const std::vector<TouchedMonitor>& monitors) const {
1625 std::vector<TouchedMonitor> responsiveMonitors;
1626 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1627 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1628 sp<Connection> connection = getConnectionLocked(
1629 monitor.monitor.inputChannel->getConnectionToken());
1630 if (connection == nullptr) {
1631 ALOGE("Could not find connection for monitor %s",
1632 monitor.monitor.inputChannel->getName().c_str());
1633 return false;
1634 }
1635 if (!connection->responsive) {
1636 ALOGW("Unresponsive monitor %s will not get the new gesture",
1637 connection->inputChannel->getName().c_str());
1638 return false;
1639 }
1640 return true;
1641 });
1642 return responsiveMonitors;
1643}
1644
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001645InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1646 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1647 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001648 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 enum InjectionPermission {
1650 INJECTION_PERMISSION_UNKNOWN,
1651 INJECTION_PERMISSION_GRANTED,
1652 INJECTION_PERMISSION_DENIED
1653 };
1654
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 // For security reasons, we defer updating the touch state until we are sure that
1656 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 int32_t displayId = entry.displayId;
1658 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1660
1661 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001662 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001664 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1665 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001667 // Copy current touch state into tempTouchState.
1668 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1669 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001670 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001671 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001672 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1673 mTouchStatesByDisplay.find(displayId);
1674 if (oldStateIt != mTouchStatesByDisplay.end()) {
1675 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001676 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001677 }
1678
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001679 bool isSplit = tempTouchState.split;
1680 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1681 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1682 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001683 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1684 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1685 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1686 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1687 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001688 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 bool wrongDevice = false;
1690 if (newGesture) {
1691 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001692 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001693 ALOGI("Dropping event because a pointer for a different device is already down "
1694 "in display %" PRId32,
1695 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001696 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001697 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 switchedDevice = false;
1699 wrongDevice = true;
1700 goto Failed;
1701 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001702 tempTouchState.reset();
1703 tempTouchState.down = down;
1704 tempTouchState.deviceId = entry.deviceId;
1705 tempTouchState.source = entry.source;
1706 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001708 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001709 ALOGI("Dropping move event because a pointer for a different device is already active "
1710 "in display %" PRId32,
1711 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001712 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001713 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001714 switchedDevice = false;
1715 wrongDevice = true;
1716 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718
1719 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1720 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1721
Garfield Tan00f511d2019-06-12 16:55:40 -07001722 int32_t x;
1723 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001725 // Always dispatch mouse events to cursor position.
1726 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001727 x = int32_t(entry.xCursorPosition);
1728 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001729 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001730 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1731 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001732 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001733 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001734 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001735 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1736 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001737
1738 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001739 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001740 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001743 if (newTouchedWindowHandle != nullptr &&
1744 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001745 // New window supports splitting, but we should never split mouse events.
1746 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 } else if (isSplit) {
1748 // New window does not support splitting but we have already split events.
1749 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001750 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 }
1752
1753 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001754 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001756 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001757 }
1758
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001759 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1760 ALOGI("Not sending touch event to %s because it is paused",
1761 newTouchedWindowHandle->getName().c_str());
1762 newTouchedWindowHandle = nullptr;
1763 }
1764
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001765 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001766 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001767 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1768 if (!isResponsive) {
1769 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001770 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1771 newTouchedWindowHandle = nullptr;
1772 }
1773 }
1774
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001775 // Drop events that can't be trusted due to occlusion
1776 if (newTouchedWindowHandle != nullptr &&
1777 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1778 TouchOcclusionInfo occlusionInfo =
1779 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001780 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001781 if (DEBUG_TOUCH_OCCLUSION) {
1782 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1783 for (const auto& log : occlusionInfo.debugInfo) {
1784 ALOGD("%s", log.c_str());
1785 }
1786 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001787 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1788 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1789 ALOGW("Dropping untrusted touch event due to %s/%d",
1790 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1791 newTouchedWindowHandle = nullptr;
1792 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001793 }
1794 }
1795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001796 // Also don't send the new touch event to unresponsive gesture monitors
1797 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1798
Michael Wright3dd60e22019-03-27 22:06:44 +00001799 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1800 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 "(%d, %d) in display %" PRId32 ".",
1802 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001803 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001804 goto Failed;
1805 }
1806
1807 if (newTouchedWindowHandle != nullptr) {
1808 // Set target flags.
1809 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1810 if (isSplit) {
1811 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001813 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1814 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1815 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1816 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1817 }
1818
1819 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001820 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1821 newHoverWindowHandle = nullptr;
1822 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001823 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001824 }
1825
1826 // Update the temporary touch state.
1827 BitSet32 pointerIds;
1828 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001829 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001830 pointerIds.markBit(pointerId);
1831 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001832 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 }
1834
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 } else {
1837 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1838
1839 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001840 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001841 if (DEBUG_FOCUS) {
1842 ALOGD("Dropping event because the pointer is not down or we previously "
1843 "dropped the pointer down event in display %" PRId32,
1844 displayId);
1845 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001846 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 goto Failed;
1848 }
1849
1850 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001852 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001853 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1854 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855
1856 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001858 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001859 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1860 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001861 if (DEBUG_FOCUS) {
1862 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1863 oldTouchedWindowHandle->getName().c_str(),
1864 newTouchedWindowHandle->getName().c_str(), displayId);
1865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1868 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1869 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870
1871 // Make a slippery entrance into the new window.
1872 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1873 isSplit = true;
1874 }
1875
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001876 int32_t targetFlags =
1877 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 if (isSplit) {
1879 targetFlags |= InputTarget::FLAG_SPLIT;
1880 }
1881 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1882 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1883 }
1884
1885 BitSet32 pointerIds;
1886 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001887 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001889 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891 }
1892 }
1893
1894 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001895 // Let the previous window know that the hover sequence is over, unless we already did it
1896 // when dispatching it as is to newTouchedWindowHandle.
1897 if (mLastHoverWindowHandle != nullptr &&
1898 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1899 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900#if DEBUG_HOVER
1901 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001902 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001904 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1905 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 }
1907
Garfield Tandf26e862020-07-01 20:18:19 -07001908 // Let the new window know that the hover sequence is starting, unless we already did it
1909 // when dispatching it as is to newTouchedWindowHandle.
1910 if (newHoverWindowHandle != nullptr &&
1911 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1912 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913#if DEBUG_HOVER
1914 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001915 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001917 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1918 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1919 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 }
1921 }
1922
1923 // Check permission to inject into all touched foreground windows and ensure there
1924 // is at least one touched foreground window.
1925 {
1926 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001927 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1929 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001930 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001931 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 injectionPermission = INJECTION_PERMISSION_DENIED;
1933 goto Failed;
1934 }
1935 }
1936 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001937 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001938 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001939 ALOGI("Dropping event because there is no touched foreground window in display "
1940 "%" PRId32 " or gesture monitor to receive it.",
1941 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 goto Failed;
1944 }
1945
1946 // Permission granted to injection into all touched foreground windows.
1947 injectionPermission = INJECTION_PERMISSION_GRANTED;
1948 }
1949
1950 // Check whether windows listening for outside touches are owned by the same UID. If it is
1951 // set the policy flag that we will not reveal coordinate information to this window.
1952 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1953 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001954 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001955 if (foregroundWindowHandle) {
1956 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001957 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001958 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1959 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1960 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001961 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1962 InputTarget::FLAG_ZERO_COORDS,
1963 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
1966 }
1967 }
1968 }
1969
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 // If this is the first pointer going down and the touched window has a wallpaper
1971 // then also add the touched wallpaper windows so they are locked in for the duration
1972 // of the touch gesture.
1973 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1974 // engine only supports touch events. We would need to add a mechanism similar
1975 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1976 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1977 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001978 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001979 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001980 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001981 getWindowHandlesLocked(displayId);
1982 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001984 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001985 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001986 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001987 .addOrUpdateWindow(windowHandle,
1988 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1989 InputTarget::
1990 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1991 InputTarget::FLAG_DISPATCH_AS_IS,
1992 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 }
1994 }
1995 }
1996 }
1997
1998 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001999 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002001 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002003 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
2005
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002006 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002007 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002008 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002009 }
2010
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 // Drop the outside or hover touch windows since we will not care about them
2012 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002013 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
2015Failed:
2016 // Check injection permission once and for all.
2017 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 injectionPermission = INJECTION_PERMISSION_GRANTED;
2020 } else {
2021 injectionPermission = INJECTION_PERMISSION_DENIED;
2022 }
2023 }
2024
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002025 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2026 return injectionResult;
2027 }
2028
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002030 if (!wrongDevice) {
2031 if (switchedDevice) {
2032 if (DEBUG_FOCUS) {
2033 ALOGD("Conflicting pointer actions: Switched to a different device.");
2034 }
2035 *outConflictingPointerActions = true;
2036 }
2037
2038 if (isHoverAction) {
2039 // Started hovering, therefore no longer down.
2040 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002041 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002042 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2043 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 *outConflictingPointerActions = true;
2046 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002047 tempTouchState.reset();
2048 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2049 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2050 tempTouchState.deviceId = entry.deviceId;
2051 tempTouchState.source = entry.source;
2052 tempTouchState.displayId = displayId;
2053 }
2054 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2055 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2056 // All pointers up or canceled.
2057 tempTouchState.reset();
2058 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2059 // First pointer went down.
2060 if (oldState && oldState->down) {
2061 if (DEBUG_FOCUS) {
2062 ALOGD("Conflicting pointer actions: Down received while already down.");
2063 }
2064 *outConflictingPointerActions = true;
2065 }
2066 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2067 // One pointer went up.
2068 if (isSplit) {
2069 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2070 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002072 for (size_t i = 0; i < tempTouchState.windows.size();) {
2073 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2074 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2075 touchedWindow.pointerIds.clearBit(pointerId);
2076 if (touchedWindow.pointerIds.isEmpty()) {
2077 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2078 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002081 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002083 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002084 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002085
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002086 // Save changes unless the action was scroll in which case the temporary touch
2087 // state was only valid for this one action.
2088 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2089 if (tempTouchState.displayId >= 0) {
2090 mTouchStatesByDisplay[displayId] = tempTouchState;
2091 } else {
2092 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002096 // Update hover state.
2097 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
2099
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 return injectionResult;
2101}
2102
2103void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002104 int32_t targetFlags, BitSet32 pointerIds,
2105 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002106 std::vector<InputTarget>::iterator it =
2107 std::find_if(inputTargets.begin(), inputTargets.end(),
2108 [&windowHandle](const InputTarget& inputTarget) {
2109 return inputTarget.inputChannel->getConnectionToken() ==
2110 windowHandle->getToken();
2111 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002112
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002113 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002114
2115 if (it == inputTargets.end()) {
2116 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002117 std::shared_ptr<InputChannel> inputChannel =
2118 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002119 if (inputChannel == nullptr) {
2120 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2121 return;
2122 }
2123 inputTarget.inputChannel = inputChannel;
2124 inputTarget.flags = targetFlags;
2125 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2126 inputTargets.push_back(inputTarget);
2127 it = inputTargets.end() - 1;
2128 }
2129
2130 ALOG_ASSERT(it->flags == targetFlags);
2131 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2132
chaviw1ff3d1e2020-07-01 15:53:47 -07002133 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134}
2135
Michael Wright3dd60e22019-03-27 22:06:44 +00002136void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002137 int32_t displayId, float xOffset,
2138 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002139 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2140 mGlobalMonitorsByDisplay.find(displayId);
2141
2142 if (it != mGlobalMonitorsByDisplay.end()) {
2143 const std::vector<Monitor>& monitors = it->second;
2144 for (const Monitor& monitor : monitors) {
2145 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 }
2148}
2149
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002150void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2151 float yOffset,
2152 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002153 InputTarget target;
2154 target.inputChannel = monitor.inputChannel;
2155 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002156 ui::Transform t;
2157 t.set(xOffset, yOffset);
2158 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002159 inputTargets.push_back(target);
2160}
2161
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002163 const InjectionState* injectionState) {
2164 if (injectionState &&
2165 (windowHandle == nullptr ||
2166 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2167 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002168 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002170 "owned by uid %d",
2171 injectionState->injectorPid, injectionState->injectorUid,
2172 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 } else {
2174 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002175 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
2177 return false;
2178 }
2179 return true;
2180}
2181
Robert Carrc9bf1d32020-04-13 17:21:08 -07002182/**
2183 * Indicate whether one window handle should be considered as obscuring
2184 * another window handle. We only check a few preconditions. Actually
2185 * checking the bounds is left to the caller.
2186 */
2187static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2188 const sp<InputWindowHandle>& otherHandle) {
2189 // Compare by token so cloned layers aren't counted
2190 if (haveSameToken(windowHandle, otherHandle)) {
2191 return false;
2192 }
2193 auto info = windowHandle->getInfo();
2194 auto otherInfo = otherHandle->getInfo();
2195 if (!otherInfo->visible) {
2196 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002197 } else if (info->ownerUid == otherInfo->ownerUid) {
2198 // If ownerUid is the same we don't generate occlusion events as there
2199 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002200 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002201 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002202 return false;
2203 } else if (otherInfo->displayId != info->displayId) {
2204 return false;
2205 }
2206 return true;
2207}
2208
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002209/**
2210 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2211 * untrusted, one should check:
2212 *
2213 * 1. If result.hasBlockingOcclusion is true.
2214 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2215 * BLOCK_UNTRUSTED.
2216 *
2217 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2218 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2219 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2220 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2221 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2222 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2223 *
2224 * If neither of those is true, then it means the touch can be allowed.
2225 */
2226InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2227 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002228 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2229 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002230 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2231 TouchOcclusionInfo info;
2232 info.hasBlockingOcclusion = false;
2233 info.obscuringOpacity = 0;
2234 info.obscuringUid = -1;
2235 std::map<int32_t, float> opacityByUid;
2236 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2237 if (windowHandle == otherHandle) {
2238 break; // All future windows are below us. Exit early.
2239 }
2240 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2241 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002242 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2243 if (DEBUG_TOUCH_OCCLUSION) {
2244 info.debugInfo.push_back(
2245 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2246 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002247 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2248 // we perform the checks below to see if the touch can be propagated or not based on the
2249 // window's touch occlusion mode
2250 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2251 info.hasBlockingOcclusion = true;
2252 info.obscuringUid = otherInfo->ownerUid;
2253 info.obscuringPackage = otherInfo->packageName;
2254 break;
2255 }
2256 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2257 uint32_t uid = otherInfo->ownerUid;
2258 float opacity =
2259 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2260 // Given windows A and B:
2261 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2262 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2263 opacityByUid[uid] = opacity;
2264 if (opacity > info.obscuringOpacity) {
2265 info.obscuringOpacity = opacity;
2266 info.obscuringUid = uid;
2267 info.obscuringPackage = otherInfo->packageName;
2268 }
2269 }
2270 }
2271 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002272 if (DEBUG_TOUCH_OCCLUSION) {
2273 info.debugInfo.push_back(
2274 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2275 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002276 return info;
2277}
2278
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002279std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2280 bool isTouchedWindow) const {
2281 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", mode=%s, alpha=%.2f, "
2282 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2283 "], window=%s, applicationInfo=%s, flags=%s\n",
2284 (isTouchedWindow) ? "[TOUCHED] " : "",
2285 NamedEnum::string(info->type).c_str(), info->packageName.c_str(),
2286 info->ownerUid, toString(info->touchOcclusionMode).c_str(), info->alpha,
2287 info->frameLeft, info->frameTop, info->frameRight, info->frameBottom,
2288 info->name.c_str(), info->applicationInfo.name.c_str(),
2289 info->flags.string().c_str());
2290}
2291
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002292bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2293 if (occlusionInfo.hasBlockingOcclusion) {
2294 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2295 occlusionInfo.obscuringUid);
2296 return false;
2297 }
2298 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2299 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2300 "%.2f, maximum allowed = %.2f)",
2301 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2302 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2303 return false;
2304 }
2305 return true;
2306}
2307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002308bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2309 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002311 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002312 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002313 if (windowHandle == otherHandle) {
2314 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002317 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002318 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 return true;
2320 }
2321 }
2322 return false;
2323}
2324
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002325bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2326 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002327 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002328 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002329 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002330 if (windowHandle == otherHandle) {
2331 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002332 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002333 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002334 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002335 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002336 return true;
2337 }
2338 }
2339 return false;
2340}
2341
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002342std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002343 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002345 if (applicationHandle != nullptr) {
2346 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002347 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 } else {
2349 return applicationHandle->getName();
2350 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002351 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002352 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002354 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356}
2357
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002358void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002359 if (eventEntry.type == EventEntry::Type::FOCUS) {
2360 // Focus events are passed to apps, but do not represent user activity.
2361 return;
2362 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002363 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002364 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002365 if (focusedWindowHandle != nullptr) {
2366 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002367 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002369 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370#endif
2371 return;
2372 }
2373 }
2374
2375 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002376 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002377 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002378 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2379 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 return;
2381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002383 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 eventType = USER_ACTIVITY_EVENT_TOUCH;
2385 }
2386 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002388 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002389 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2390 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002391 return;
2392 }
2393 eventType = USER_ACTIVITY_EVENT_BUTTON;
2394 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002396 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002397 case EventEntry::Type::CONFIGURATION_CHANGED:
2398 case EventEntry::Type::DEVICE_RESET: {
2399 LOG_ALWAYS_FATAL("%s events are not user activity",
2400 EventEntry::typeToString(eventEntry.type));
2401 break;
2402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
2404
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002405 std::unique_ptr<CommandEntry> commandEntry =
2406 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002407 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002409 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410}
2411
2412void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413 const sp<Connection>& connection,
2414 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002415 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002416 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002418 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002419 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002420 ATRACE_NAME(message.c_str());
2421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422#if DEBUG_DISPATCH_CYCLE
2423 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002424 "globalScaleFactor=%f, pointerIds=0x%x %s",
2425 connection->getInputChannelName().c_str(), inputTarget.flags,
2426 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2427 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428#endif
2429
2430 // Skip this event if the connection status is not normal.
2431 // We don't want to enqueue additional outbound events if the connection is broken.
2432 if (connection->status != Connection::STATUS_NORMAL) {
2433#if DEBUG_DISPATCH_CYCLE
2434 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002435 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436#endif
2437 return;
2438 }
2439
2440 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002441 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2442 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2443 "Entry type %s should not have FLAG_SPLIT",
2444 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002446 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002447 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002448 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002449 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 if (!splitMotionEntry) {
2451 return; // split event was dropped
2452 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002453 if (DEBUG_FOCUS) {
2454 ALOGD("channel '%s' ~ Split motion event.",
2455 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002456 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002457 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002458 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 splitMotionEntry->release();
2460 return;
2461 }
2462 }
2463
2464 // Not splitting. Enqueue dispatch entries for the event as is.
2465 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2466}
2467
2468void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469 const sp<Connection>& connection,
2470 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002471 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002472 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002474 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002475 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002476 ATRACE_NAME(message.c_str());
2477 }
2478
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002479 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480
2481 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002482 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002484 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002486 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002488 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002490 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002492 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494
2495 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002496 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 startDispatchCycleLocked(currentTime, connection);
2498 }
2499}
2500
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002501void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2502 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002503 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002505 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2507 connection->getInputChannelName().c_str(),
2508 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002509 ATRACE_NAME(message.c_str());
2510 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002511 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 if (!(inputTargetFlags & dispatchMode)) {
2513 return;
2514 }
2515 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2516
2517 // This is a new event.
2518 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002519 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002520 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002522 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2523 // different EventEntry than what was passed in.
2524 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002526 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002527 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002528 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002529 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002530 dispatchEntry->resolvedAction = keyEntry.action;
2531 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2534 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2537 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 return; // skip the inconsistent event
2540 }
2541 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002544 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002545 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002546 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2547 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2548 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2549 static_cast<int32_t>(IdGenerator::Source::OTHER);
2550 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2552 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2553 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2554 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2555 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2556 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2557 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2558 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2559 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2560 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2561 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002562 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002563 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 }
2565 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002566 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2567 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2570 "event",
2571 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002576 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2578 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2579 }
2580 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2581 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2585 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2588 "event",
2589 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 return; // skip the inconsistent event
2592 }
2593
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002594 dispatchEntry->resolvedEventId =
2595 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2596 ? mIdGenerator.nextId()
2597 : motionEntry.id;
2598 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2599 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2600 ") to MotionEvent(id=0x%" PRIx32 ").",
2601 motionEntry.id, dispatchEntry->resolvedEventId);
2602 ATRACE_NAME(message.c_str());
2603 }
2604
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002605 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002606 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002607
2608 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002610 case EventEntry::Type::FOCUS: {
2611 break;
2612 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002613 case EventEntry::Type::CONFIGURATION_CHANGED:
2614 case EventEntry::Type::DEVICE_RESET: {
2615 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002616 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002617 break;
2618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
2620
2621 // Remember that we are waiting for this dispatch to complete.
2622 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002623 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 }
2625
2626 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002627 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002628 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002629}
2630
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002631/**
2632 * This function is purely for debugging. It helps us understand where the user interaction
2633 * was taking place. For example, if user is touching launcher, we will see a log that user
2634 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2635 * We will see both launcher and wallpaper in that list.
2636 * Once the interaction with a particular set of connections starts, no new logs will be printed
2637 * until the set of interacted connections changes.
2638 *
2639 * The following items are skipped, to reduce the logspam:
2640 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2641 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2642 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2643 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2644 * Both of those ACTION_UP events would not be logged
2645 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2646 * will not be logged. This is omitted to reduce the amount of data printed.
2647 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2648 * gesture monitor is the only connection receiving the remainder of the gesture.
2649 */
2650void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2651 const std::vector<InputTarget>& targets) {
2652 // Skip ACTION_UP events, and all events other than keys and motions
2653 if (entry.type == EventEntry::Type::KEY) {
2654 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2655 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2656 return;
2657 }
2658 } else if (entry.type == EventEntry::Type::MOTION) {
2659 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2660 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2661 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2662 return;
2663 }
2664 } else {
2665 return; // Not a key or a motion
2666 }
2667
2668 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2669 std::vector<sp<Connection>> newConnections;
2670 for (const InputTarget& target : targets) {
2671 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2672 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2673 continue; // Skip windows that receive ACTION_OUTSIDE
2674 }
2675
2676 sp<IBinder> token = target.inputChannel->getConnectionToken();
2677 sp<Connection> connection = getConnectionLocked(token);
2678 if (connection == nullptr || connection->monitor) {
2679 continue; // We only need to keep track of the non-monitor connections.
2680 }
2681 newConnectionTokens.insert(std::move(token));
2682 newConnections.emplace_back(connection);
2683 }
2684 if (newConnectionTokens == mInteractionConnectionTokens) {
2685 return; // no change
2686 }
2687 mInteractionConnectionTokens = newConnectionTokens;
2688
2689 std::string windowList;
2690 for (const sp<Connection>& connection : newConnections) {
2691 windowList += connection->getWindowName() + ", ";
2692 }
2693 std::string message = "Interaction with windows: " + windowList;
2694 if (windowList.empty()) {
2695 message += "<none>";
2696 }
2697 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2698}
2699
chaviwfd6d3512019-03-25 13:23:49 -07002700void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002701 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002702 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002703 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2704 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002705 return;
2706 }
2707
Vishnu Nairad321cd2020-08-20 16:40:21 -07002708 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2709 if (focusedToken == token) {
2710 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002711 return;
2712 }
2713
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002714 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2715 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002716 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002717 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718}
2719
2720void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002722 if (ATRACE_ENABLED()) {
2723 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002725 ATRACE_NAME(message.c_str());
2726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729#endif
2730
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002731 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2732 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002734 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002735 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002736 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737
2738 // Publish the event.
2739 status_t status;
2740 EventEntry* eventEntry = dispatchEntry->eventEntry;
2741 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002742 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002743 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2744 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002746 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002747 status =
2748 connection->inputPublisher
2749 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2750 keyEntry->deviceId, keyEntry->source,
2751 keyEntry->displayId, std::move(hmac),
2752 dispatchEntry->resolvedAction,
2753 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2754 keyEntry->scanCode, keyEntry->metaState,
2755 keyEntry->repeatCount, keyEntry->downTime,
2756 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002757 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 }
2759
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002760 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 PointerCoords scaledCoords[MAX_POINTERS];
2764 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2765
chaviw82357092020-01-28 13:13:06 -08002766 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002767 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2768 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2769 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002770 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002771 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2772 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002773 // Don't apply window scale here since we don't want scale to affect raw
2774 // coordinates. The scale will be sent back to the client and applied
2775 // later when requesting relative coordinates.
2776 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2777 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 }
2779 usingCoords = scaledCoords;
2780 }
2781 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002782 // We don't want the dispatch target to know.
2783 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2784 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2785 scaledCoords[i].clear();
2786 }
2787 usingCoords = scaledCoords;
2788 }
2789 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002790
2791 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002792
2793 // Publish the motion event.
2794 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002795 .publishMotionEvent(dispatchEntry->seq,
2796 dispatchEntry->resolvedEventId,
2797 motionEntry->deviceId, motionEntry->source,
2798 motionEntry->displayId, std::move(hmac),
2799 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002800 motionEntry->actionButton,
2801 dispatchEntry->resolvedFlags,
2802 motionEntry->edgeFlags, motionEntry->metaState,
2803 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002804 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002805 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002806 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807 motionEntry->yPrecision,
2808 motionEntry->xCursorPosition,
2809 motionEntry->yCursorPosition,
2810 motionEntry->downTime, motionEntry->eventTime,
2811 motionEntry->pointerCount,
2812 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002813 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002814 break;
2815 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002816 case EventEntry::Type::FOCUS: {
2817 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2818 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002819 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002820 focusEntry->hasFocus,
2821 mInTouchMode);
2822 break;
2823 }
2824
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002825 case EventEntry::Type::CONFIGURATION_CHANGED:
2826 case EventEntry::Type::DEVICE_RESET: {
2827 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2828 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 }
2832
2833 // Check the result.
2834 if (status) {
2835 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002836 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 "This is unexpected because the wait queue is empty, so the pipe "
2839 "should be empty and we shouldn't have any problems writing an "
2840 "event to it, status=%d",
2841 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2843 } else {
2844 // Pipe is full and we are waiting for the app to finish process some events
2845 // before sending more events to it.
2846#if DEBUG_DISPATCH_CYCLE
2847 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848 "waiting for the application to catch up",
2849 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 }
2852 } else {
2853 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 "status=%d",
2855 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2857 }
2858 return;
2859 }
2860
2861 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002862 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2863 connection->outboundQueue.end(),
2864 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002865 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002866 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002867 if (connection->responsive) {
2868 mAnrTracker.insert(dispatchEntry->timeoutTime,
2869 connection->inputChannel->getConnectionToken());
2870 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002871 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 }
2873}
2874
chaviw09c8d2d2020-08-24 15:48:26 -07002875std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2876 size_t size;
2877 switch (event.type) {
2878 case VerifiedInputEvent::Type::KEY: {
2879 size = sizeof(VerifiedKeyEvent);
2880 break;
2881 }
2882 case VerifiedInputEvent::Type::MOTION: {
2883 size = sizeof(VerifiedMotionEvent);
2884 break;
2885 }
2886 }
2887 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2888 return mHmacKeyManager.sign(start, size);
2889}
2890
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002891const std::array<uint8_t, 32> InputDispatcher::getSignature(
2892 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2893 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2894 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2895 // Only sign events up and down events as the purely move events
2896 // are tied to their up/down counterparts so signing would be redundant.
2897 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2898 verifiedEvent.actionMasked = actionMasked;
2899 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002900 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002901 }
2902 return INVALID_HMAC;
2903}
2904
2905const std::array<uint8_t, 32> InputDispatcher::getSignature(
2906 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2907 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2908 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2909 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002910 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002911}
2912
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 const sp<Connection>& connection, uint32_t seq,
2915 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916#if DEBUG_DISPATCH_CYCLE
2917 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919#endif
2920
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 if (connection->status == Connection::STATUS_BROKEN ||
2922 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 return;
2924 }
2925
2926 // Notify other system components and prepare to start the next dispatch cycle.
2927 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2928}
2929
2930void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 const sp<Connection>& connection,
2932 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933#if DEBUG_DISPATCH_CYCLE
2934 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936#endif
2937
2938 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002939 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002940 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002941 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002942 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943
2944 // The connection appears to be unrecoverably broken.
2945 // Ignore already broken or zombie connections.
2946 if (connection->status == Connection::STATUS_NORMAL) {
2947 connection->status = Connection::STATUS_BROKEN;
2948
2949 if (notify) {
2950 // Notify other system components.
2951 onDispatchCycleBrokenLocked(currentTime, connection);
2952 }
2953 }
2954}
2955
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002956void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2957 while (!queue.empty()) {
2958 DispatchEntry* dispatchEntry = queue.front();
2959 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002960 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 }
2962}
2963
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002964void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002966 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 }
2968 delete dispatchEntry;
2969}
2970
2971int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2972 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2973
2974 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002975 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002977 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979 "fd=%d, events=0x%x",
2980 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981 return 0; // remove the callback
2982 }
2983
2984 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002985 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2987 if (!(events & ALOOPER_EVENT_INPUT)) {
2988 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 "events=0x%x",
2990 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991 return 1;
2992 }
2993
2994 nsecs_t currentTime = now();
2995 bool gotOne = false;
2996 status_t status;
2997 for (;;) {
2998 uint32_t seq;
2999 bool handled;
3000 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3001 if (status) {
3002 break;
3003 }
3004 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3005 gotOne = true;
3006 }
3007 if (gotOne) {
3008 d->runCommandsLockedInterruptible();
3009 if (status == WOULD_BLOCK) {
3010 return 1;
3011 }
3012 }
3013
3014 notify = status != DEAD_OBJECT || !connection->monitor;
3015 if (notify) {
3016 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018 }
3019 } else {
3020 // Monitor channels are never explicitly unregistered.
3021 // We do it automatically when the remote endpoint is closed so don't warn
3022 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003023 const bool stillHaveWindowHandle =
3024 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3025 nullptr;
3026 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 if (notify) {
3028 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003029 "events=0x%x",
3030 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 }
3032 }
3033
Garfield Tan15601662020-09-22 15:32:38 -07003034 // Remove the channel.
3035 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003037 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038}
3039
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003042 for (const auto& pair : mConnectionsByFd) {
3043 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 }
3045}
3046
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003048 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003049 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3050 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3051}
3052
3053void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3054 const CancelationOptions& options,
3055 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3056 for (const auto& it : monitorsByDisplay) {
3057 const std::vector<Monitor>& monitors = it.second;
3058 for (const Monitor& monitor : monitors) {
3059 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003060 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003061 }
3062}
3063
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003065 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003066 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003067 if (connection == nullptr) {
3068 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003070
3071 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072}
3073
3074void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3075 const sp<Connection>& connection, const CancelationOptions& options) {
3076 if (connection->status == Connection::STATUS_BROKEN) {
3077 return;
3078 }
3079
3080 nsecs_t currentTime = now();
3081
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003082 std::vector<EventEntry*> cancelationEvents =
3083 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003085 if (cancelationEvents.empty()) {
3086 return;
3087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003089 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3090 "with reality: %s, mode=%d.",
3091 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3092 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003094
3095 InputTarget target;
3096 sp<InputWindowHandle> windowHandle =
3097 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3098 if (windowHandle != nullptr) {
3099 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003100 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003101 target.globalScaleFactor = windowInfo->globalScaleFactor;
3102 }
3103 target.inputChannel = connection->inputChannel;
3104 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3105
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003106 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3107 EventEntry* cancelationEventEntry = cancelationEvents[i];
3108 switch (cancelationEventEntry->type) {
3109 case EventEntry::Type::KEY: {
3110 logOutboundKeyDetails("cancel - ",
3111 static_cast<const KeyEntry&>(*cancelationEventEntry));
3112 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003114 case EventEntry::Type::MOTION: {
3115 logOutboundMotionDetails("cancel - ",
3116 static_cast<const MotionEntry&>(*cancelationEventEntry));
3117 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003119 case EventEntry::Type::FOCUS: {
3120 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3121 break;
3122 }
3123 case EventEntry::Type::CONFIGURATION_CHANGED:
3124 case EventEntry::Type::DEVICE_RESET: {
3125 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3126 EventEntry::typeToString(cancelationEventEntry->type));
3127 break;
3128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 }
3130
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003131 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3132 target, InputTarget::FLAG_DISPATCH_AS_IS);
3133
3134 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003136
3137 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138}
3139
Svet Ganov5d3bc372020-01-26 23:11:07 -08003140void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3141 const sp<Connection>& connection) {
3142 if (connection->status == Connection::STATUS_BROKEN) {
3143 return;
3144 }
3145
3146 nsecs_t currentTime = now();
3147
3148 std::vector<EventEntry*> downEvents =
3149 connection->inputState.synthesizePointerDownEvents(currentTime);
3150
3151 if (downEvents.empty()) {
3152 return;
3153 }
3154
3155#if DEBUG_OUTBOUND_EVENT_DETAILS
3156 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3157 connection->getInputChannelName().c_str(), downEvents.size());
3158#endif
3159
3160 InputTarget target;
3161 sp<InputWindowHandle> windowHandle =
3162 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3163 if (windowHandle != nullptr) {
3164 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003165 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003166 target.globalScaleFactor = windowInfo->globalScaleFactor;
3167 }
3168 target.inputChannel = connection->inputChannel;
3169 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3170
3171 for (EventEntry* downEventEntry : downEvents) {
3172 switch (downEventEntry->type) {
3173 case EventEntry::Type::MOTION: {
3174 logOutboundMotionDetails("down - ",
3175 static_cast<const MotionEntry&>(*downEventEntry));
3176 break;
3177 }
3178
3179 case EventEntry::Type::KEY:
3180 case EventEntry::Type::FOCUS:
3181 case EventEntry::Type::CONFIGURATION_CHANGED:
3182 case EventEntry::Type::DEVICE_RESET: {
3183 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3184 EventEntry::typeToString(downEventEntry->type));
3185 break;
3186 }
3187 }
3188
3189 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3190 target, InputTarget::FLAG_DISPATCH_AS_IS);
3191
3192 downEventEntry->release();
3193 }
3194
3195 startDispatchCycleLocked(currentTime, connection);
3196}
3197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003198MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003199 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 ALOG_ASSERT(pointerIds.value != 0);
3201
3202 uint32_t splitPointerIndexMap[MAX_POINTERS];
3203 PointerProperties splitPointerProperties[MAX_POINTERS];
3204 PointerCoords splitPointerCoords[MAX_POINTERS];
3205
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003206 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 uint32_t splitPointerCount = 0;
3208
3209 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003210 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003212 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 uint32_t pointerId = uint32_t(pointerProperties.id);
3214 if (pointerIds.hasBit(pointerId)) {
3215 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3216 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3217 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003218 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 splitPointerCount += 1;
3220 }
3221 }
3222
3223 if (splitPointerCount != pointerIds.count()) {
3224 // This is bad. We are missing some of the pointers that we expected to deliver.
3225 // Most likely this indicates that we received an ACTION_MOVE events that has
3226 // different pointer ids than we expected based on the previous ACTION_DOWN
3227 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3228 // in this way.
3229 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003230 "we expected there to be %d pointers. This probably means we received "
3231 "a broken sequence of pointer ids from the input device.",
3232 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003233 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 }
3235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003236 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3239 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3241 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003242 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 uint32_t pointerId = uint32_t(pointerProperties.id);
3244 if (pointerIds.hasBit(pointerId)) {
3245 if (pointerIds.count() == 1) {
3246 // The first/last pointer went down/up.
3247 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 ? AMOTION_EVENT_ACTION_DOWN
3249 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 } else {
3251 // A secondary pointer went down/up.
3252 uint32_t splitPointerIndex = 0;
3253 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3254 splitPointerIndex += 1;
3255 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 action = maskedAction |
3257 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 }
3259 } else {
3260 // An unrelated pointer changed.
3261 action = AMOTION_EVENT_ACTION_MOVE;
3262 }
3263 }
3264
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003265 int32_t newId = mIdGenerator.nextId();
3266 if (ATRACE_ENABLED()) {
3267 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3268 ") to MotionEvent(id=0x%" PRIx32 ").",
3269 originalMotionEntry.id, newId);
3270 ATRACE_NAME(message.c_str());
3271 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003272 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003273 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3274 originalMotionEntry.source, originalMotionEntry.displayId,
3275 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003276 originalMotionEntry.actionButton, originalMotionEntry.flags,
3277 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3278 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3279 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3280 originalMotionEntry.xCursorPosition,
3281 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003282 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003284 if (originalMotionEntry.injectionState) {
3285 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 splitMotionEntry->injectionState->refCount += 1;
3287 }
3288
3289 return splitMotionEntry;
3290}
3291
3292void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3293#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003294 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295#endif
3296
3297 bool needWake;
3298 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003299 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300
Prabir Pradhan42611e02018-11-27 14:04:02 -08003301 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003302 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 needWake = enqueueInboundEventLocked(newEntry);
3304 } // release lock
3305
3306 if (needWake) {
3307 mLooper->wake();
3308 }
3309}
3310
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003311/**
3312 * If one of the meta shortcuts is detected, process them here:
3313 * Meta + Backspace -> generate BACK
3314 * Meta + Enter -> generate HOME
3315 * This will potentially overwrite keyCode and metaState.
3316 */
3317void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003319 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3320 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3321 if (keyCode == AKEYCODE_DEL) {
3322 newKeyCode = AKEYCODE_BACK;
3323 } else if (keyCode == AKEYCODE_ENTER) {
3324 newKeyCode = AKEYCODE_HOME;
3325 }
3326 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003327 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003328 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003329 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003330 keyCode = newKeyCode;
3331 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3332 }
3333 } else if (action == AKEY_EVENT_ACTION_UP) {
3334 // In order to maintain a consistent stream of up and down events, check to see if the key
3335 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3336 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003337 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003338 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003339 auto replacementIt = mReplacedKeys.find(replacement);
3340 if (replacementIt != mReplacedKeys.end()) {
3341 keyCode = replacementIt->second;
3342 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003343 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3344 }
3345 }
3346}
3347
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3349#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3351 "policyFlags=0x%x, action=0x%x, "
3352 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3353 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3354 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3355 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356#endif
3357 if (!validateKeyEvent(args->action)) {
3358 return;
3359 }
3360
3361 uint32_t policyFlags = args->policyFlags;
3362 int32_t flags = args->flags;
3363 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003364 // InputDispatcher tracks and generates key repeats on behalf of
3365 // whatever notifies it, so repeatCount should always be set to 0
3366 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3368 policyFlags |= POLICY_FLAG_VIRTUAL;
3369 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 if (policyFlags & POLICY_FLAG_FUNCTION) {
3372 metaState |= AMETA_FUNCTION_ON;
3373 }
3374
3375 policyFlags |= POLICY_FLAG_TRUSTED;
3376
Michael Wright78f24442014-08-06 15:55:28 -07003377 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003378 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003379
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003381 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003382 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3383 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384
Michael Wright2b3c3302018-03-02 17:19:13 +00003385 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003387 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3388 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 bool needWake;
3393 { // acquire lock
3394 mLock.lock();
3395
3396 if (shouldSendKeyToInputFilterLocked(args)) {
3397 mLock.unlock();
3398
3399 policyFlags |= POLICY_FLAG_FILTERED;
3400 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3401 return; // event was consumed by the filter
3402 }
3403
3404 mLock.lock();
3405 }
3406
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003408 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003409 args->displayId, policyFlags, args->action, flags, keyCode,
3410 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
3412 needWake = enqueueInboundEventLocked(newEntry);
3413 mLock.unlock();
3414 } // release lock
3415
3416 if (needWake) {
3417 mLooper->wake();
3418 }
3419}
3420
3421bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3422 return mInputFilterEnabled;
3423}
3424
3425void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3426#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003427 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3428 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003429 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3430 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003431 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003432 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3433 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3434 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3435 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 for (uint32_t i = 0; i < args->pointerCount; i++) {
3437 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 "x=%f, y=%f, pressure=%f, size=%f, "
3439 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3440 "orientation=%f",
3441 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3442 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3443 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3444 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3445 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3446 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3447 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3448 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3449 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3450 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
3452#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3454 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 return;
3456 }
3457
3458 uint32_t policyFlags = args->policyFlags;
3459 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003460
3461 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003462 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003463 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3464 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003465 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
3468 bool needWake;
3469 { // acquire lock
3470 mLock.lock();
3471
3472 if (shouldSendMotionToInputFilterLocked(args)) {
3473 mLock.unlock();
3474
3475 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003476 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003477 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3478 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003479 args->metaState, args->buttonState, args->classification, transform,
3480 args->xPrecision, args->yPrecision, args->xCursorPosition,
3481 args->yCursorPosition, args->downTime, args->eventTime,
3482 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
3484 policyFlags |= POLICY_FLAG_FILTERED;
3485 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3486 return; // event was consumed by the filter
3487 }
3488
3489 mLock.lock();
3490 }
3491
3492 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003493 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003494 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003495 args->displayId, policyFlags, args->action, args->actionButton,
3496 args->flags, args->metaState, args->buttonState,
3497 args->classification, args->edgeFlags, args->xPrecision,
3498 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3499 args->downTime, args->pointerCount, args->pointerProperties,
3500 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501
3502 needWake = enqueueInboundEventLocked(newEntry);
3503 mLock.unlock();
3504 } // release lock
3505
3506 if (needWake) {
3507 mLooper->wake();
3508 }
3509}
3510
3511bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003512 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513}
3514
3515void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3516#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003517 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518 "switchMask=0x%08x",
3519 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520#endif
3521
3522 uint32_t policyFlags = args->policyFlags;
3523 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003524 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525}
3526
3527void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3528#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3530 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531#endif
3532
3533 bool needWake;
3534 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003535 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536
Prabir Pradhan42611e02018-11-27 14:04:02 -08003537 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003538 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 needWake = enqueueInboundEventLocked(newEntry);
3540 } // release lock
3541
3542 if (needWake) {
3543 mLooper->wake();
3544 }
3545}
3546
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003547InputEventInjectionResult InputDispatcher::injectInputEvent(
3548 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3549 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550#if DEBUG_INBOUND_EVENT_DETAILS
3551 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003552 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3553 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003555 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556
3557 policyFlags |= POLICY_FLAG_INJECTED;
3558 if (hasInjectionPermission(injectorPid, injectorUid)) {
3559 policyFlags |= POLICY_FLAG_TRUSTED;
3560 }
3561
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003562 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003564 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003565 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3566 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003567 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003568 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003571 int32_t flags = incomingKey.getFlags();
3572 int32_t keyCode = incomingKey.getKeyCode();
3573 int32_t metaState = incomingKey.getMetaState();
3574 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003575 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003576 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003577 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003578 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3579 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3580 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3583 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003584 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003585
3586 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3587 android::base::Timer t;
3588 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3589 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3590 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3591 std::to_string(t.duration().count()).c_str());
3592 }
3593 }
3594
3595 mLock.lock();
3596 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003597 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3598 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003599 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3600 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003601 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003602 injectedEntries.push(injectedEntry);
3603 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
3605
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003606 case AINPUT_EVENT_TYPE_MOTION: {
3607 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3608 int32_t action = motionEvent->getAction();
3609 size_t pointerCount = motionEvent->getPointerCount();
3610 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3611 int32_t actionButton = motionEvent->getActionButton();
3612 int32_t displayId = motionEvent->getDisplayId();
3613 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003614 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615 }
3616
3617 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3618 nsecs_t eventTime = motionEvent->getEventTime();
3619 android::base::Timer t;
3620 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3621 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3622 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3623 std::to_string(t.duration().count()).c_str());
3624 }
3625 }
3626
3627 mLock.lock();
3628 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3629 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3630 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003631 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3632 motionEvent->getSource(), motionEvent->getDisplayId(),
3633 policyFlags, action, actionButton, motionEvent->getFlags(),
3634 motionEvent->getMetaState(), motionEvent->getButtonState(),
3635 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3636 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003637 motionEvent->getRawXCursorPosition(),
3638 motionEvent->getRawYCursorPosition(),
3639 motionEvent->getDownTime(), uint32_t(pointerCount),
3640 pointerProperties, samplePointerCoords,
3641 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003642 injectedEntries.push(injectedEntry);
3643 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3644 sampleEventTimes += 1;
3645 samplePointerCoords += pointerCount;
3646 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003647 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003648 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003649 motionEvent->getDisplayId(), policyFlags, action,
3650 actionButton, motionEvent->getFlags(),
3651 motionEvent->getMetaState(), motionEvent->getButtonState(),
3652 motionEvent->getClassification(),
3653 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3654 motionEvent->getYPrecision(),
3655 motionEvent->getRawXCursorPosition(),
3656 motionEvent->getRawYCursorPosition(),
3657 motionEvent->getDownTime(), uint32_t(pointerCount),
3658 pointerProperties, samplePointerCoords,
3659 motionEvent->getXOffset(), motionEvent->getYOffset());
3660 injectedEntries.push(nextInjectedEntry);
3661 }
3662 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003665 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003666 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003667 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 }
3669
3670 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003671 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 injectionState->injectionIsAsync = true;
3673 }
3674
3675 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003676 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677
3678 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003679 while (!injectedEntries.empty()) {
3680 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3681 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 }
3683
3684 mLock.unlock();
3685
3686 if (needWake) {
3687 mLooper->wake();
3688 }
3689
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003690 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003692 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003694 if (syncMode == InputEventInjectionSync::NONE) {
3695 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 } else {
3697 for (;;) {
3698 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003699 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 break;
3701 }
3702
3703 nsecs_t remainingTimeout = endTime - now();
3704 if (remainingTimeout <= 0) {
3705#if DEBUG_INJECTION
3706 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003707 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003709 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 break;
3711 }
3712
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003713 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 }
3715
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003716 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3717 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 while (injectionState->pendingForegroundDispatches != 0) {
3719#if DEBUG_INJECTION
3720 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003721 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722#endif
3723 nsecs_t remainingTimeout = endTime - now();
3724 if (remainingTimeout <= 0) {
3725#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003726 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3727 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003729 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 break;
3731 }
3732
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003733 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 }
3735 }
3736 }
3737
3738 injectionState->release();
3739 } // release lock
3740
3741#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003742 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003743 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744#endif
3745
3746 return injectionResult;
3747}
3748
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003749std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003750 std::array<uint8_t, 32> calculatedHmac;
3751 std::unique_ptr<VerifiedInputEvent> result;
3752 switch (event.getType()) {
3753 case AINPUT_EVENT_TYPE_KEY: {
3754 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3755 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3756 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003757 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003758 break;
3759 }
3760 case AINPUT_EVENT_TYPE_MOTION: {
3761 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3762 VerifiedMotionEvent verifiedMotionEvent =
3763 verifiedMotionEventFromMotionEvent(motionEvent);
3764 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003765 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003766 break;
3767 }
3768 default: {
3769 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3770 return nullptr;
3771 }
3772 }
3773 if (calculatedHmac == INVALID_HMAC) {
3774 return nullptr;
3775 }
3776 if (calculatedHmac != event.getHmac()) {
3777 return nullptr;
3778 }
3779 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003780}
3781
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 return injectorUid == 0 ||
3784 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785}
3786
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003787void InputDispatcher::setInjectionResult(EventEntry* entry,
3788 InputEventInjectionResult injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 InjectionState* injectionState = entry->injectionState;
3790 if (injectionState) {
3791#if DEBUG_INJECTION
3792 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 "injectorPid=%d, injectorUid=%d",
3794 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795#endif
3796
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003797 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 // Log the outcome since the injector did not wait for the injection result.
3799 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003800 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003801 ALOGV("Asynchronous input event injection succeeded.");
3802 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003803 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 ALOGW("Asynchronous input event injection failed.");
3805 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003806 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003807 ALOGW("Asynchronous input event injection permission denied.");
3808 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003809 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003810 ALOGW("Asynchronous input event injection timed out.");
3811 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003812 case InputEventInjectionResult::PENDING:
3813 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3814 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816 }
3817
3818 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003819 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
3821}
3822
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003823void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 InjectionState* injectionState = entry->injectionState;
3825 if (injectionState) {
3826 injectionState->pendingForegroundDispatches += 1;
3827 }
3828}
3829
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003830void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 InjectionState* injectionState = entry->injectionState;
3832 if (injectionState) {
3833 injectionState->pendingForegroundDispatches -= 1;
3834
3835 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003836 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 }
3838 }
3839}
3840
Vishnu Nairad321cd2020-08-20 16:40:21 -07003841const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003842 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003843 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3844 auto it = mWindowHandlesByDisplay.find(displayId);
3845 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003846}
3847
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003849 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003850 if (windowHandleToken == nullptr) {
3851 return nullptr;
3852 }
3853
Arthur Hungb92218b2018-08-14 12:00:21 +08003854 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003855 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003856 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003857 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003858 return windowHandle;
3859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 }
3861 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003862 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863}
3864
Vishnu Nairad321cd2020-08-20 16:40:21 -07003865sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3866 int displayId) const {
3867 if (windowHandleToken == nullptr) {
3868 return nullptr;
3869 }
3870
3871 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3872 if (windowHandle->getToken() == windowHandleToken) {
3873 return windowHandle;
3874 }
3875 }
3876 return nullptr;
3877}
3878
3879sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3880 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3881 return getWindowHandleLocked(focusedToken, displayId);
3882}
3883
Mady Mellor017bcd12020-06-23 19:12:00 +00003884bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3885 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003886 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003887 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003888 if (handle->getId() == windowHandle->getId() &&
3889 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003890 if (windowHandle->getInfo()->displayId != it.first) {
3891 ALOGE("Found window %s in display %" PRId32
3892 ", but it should belong to display %" PRId32,
3893 windowHandle->getName().c_str(), it.first,
3894 windowHandle->getInfo()->displayId);
3895 }
3896 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 }
3899 }
3900 return false;
3901}
3902
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003903bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3904 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3905 const bool noInputChannel =
3906 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3907 if (connection != nullptr && noInputChannel) {
3908 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3909 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3910 return false;
3911 }
3912
3913 if (connection == nullptr) {
3914 if (!noInputChannel) {
3915 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3916 }
3917 return false;
3918 }
3919 if (!connection->responsive) {
3920 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3921 return false;
3922 }
3923 return true;
3924}
3925
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003926std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3927 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003928 size_t count = mInputChannelsByToken.count(token);
3929 if (count == 0) {
3930 return nullptr;
3931 }
3932 return mInputChannelsByToken.at(token);
3933}
3934
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003935void InputDispatcher::updateWindowHandlesForDisplayLocked(
3936 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3937 if (inputWindowHandles.empty()) {
3938 // Remove all handles on a display if there are no windows left.
3939 mWindowHandlesByDisplay.erase(displayId);
3940 return;
3941 }
3942
3943 // Since we compare the pointer of input window handles across window updates, we need
3944 // to make sure the handle object for the same window stays unchanged across updates.
3945 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003946 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003947 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003948 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003949 }
3950
3951 std::vector<sp<InputWindowHandle>> newHandles;
3952 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3953 if (!handle->updateInfo()) {
3954 // handle no longer valid
3955 continue;
3956 }
3957
3958 const InputWindowInfo* info = handle->getInfo();
3959 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3960 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3961 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003962 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3963 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3964 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003965 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003966 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003967 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003968 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003969 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003970 }
3971
3972 if (info->displayId != displayId) {
3973 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3974 handle->getName().c_str(), displayId, info->displayId);
3975 continue;
3976 }
3977
Robert Carredd13602020-04-13 17:24:34 -07003978 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3979 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003980 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003981 oldHandle->updateFrom(handle);
3982 newHandles.push_back(oldHandle);
3983 } else {
3984 newHandles.push_back(handle);
3985 }
3986 }
3987
3988 // Insert or replace
3989 mWindowHandlesByDisplay[displayId] = newHandles;
3990}
3991
Arthur Hung72d8dc32020-03-28 00:48:39 +00003992void InputDispatcher::setInputWindows(
3993 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3994 { // acquire lock
3995 std::scoped_lock _l(mLock);
3996 for (auto const& i : handlesPerDisplay) {
3997 setInputWindowsLocked(i.second, i.first);
3998 }
3999 }
4000 // Wake up poll loop since it may need to make new input dispatching choices.
4001 mLooper->wake();
4002}
4003
Arthur Hungb92218b2018-08-14 12:00:21 +08004004/**
4005 * Called from InputManagerService, update window handle list by displayId that can receive input.
4006 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4007 * If set an empty list, remove all handles from the specific display.
4008 * For focused handle, check if need to change and send a cancel event to previous one.
4009 * For removed handle, check if need to send a cancel event if already in touch.
4010 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004011void InputDispatcher::setInputWindowsLocked(
4012 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004013 if (DEBUG_FOCUS) {
4014 std::string windowList;
4015 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4016 windowList += iwh->getName() + " ";
4017 }
4018 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004021 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4022 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4023 const bool noInputWindow =
4024 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4025 if (noInputWindow && window->getToken() != nullptr) {
4026 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4027 window->getName().c_str());
4028 window->releaseChannel();
4029 }
4030 }
4031
Arthur Hung72d8dc32020-03-28 00:48:39 +00004032 // Copy old handles for release if they are no longer present.
4033 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034
Arthur Hung72d8dc32020-03-28 00:48:39 +00004035 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004036
Vishnu Nair958da932020-08-21 17:12:37 -07004037 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4038 if (mLastHoverWindowHandle &&
4039 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4040 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004041 mLastHoverWindowHandle = nullptr;
4042 }
4043
Vishnu Nair958da932020-08-21 17:12:37 -07004044 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4045 if (focusedToken) {
4046 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4047 if (result != FocusResult::OK) {
4048 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4049 }
4050 }
4051
4052 std::optional<FocusRequest> focusRequest =
4053 getOptionalValueByKey(mPendingFocusRequests, displayId);
4054 if (focusRequest) {
4055 // If the window from the pending request is now visible, provide it focus.
4056 FocusResult result = handleFocusRequestLocked(*focusRequest);
4057 if (result != FocusResult::NOT_VISIBLE) {
4058 // Drop the request if we were able to change the focus or we cannot change
4059 // it for another reason.
4060 mPendingFocusRequests.erase(displayId);
4061 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004064 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4065 mTouchStatesByDisplay.find(displayId);
4066 if (stateIt != mTouchStatesByDisplay.end()) {
4067 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004068 for (size_t i = 0; i < state.windows.size();) {
4069 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004070 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004071 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004072 ALOGD("Touched window was removed: %s in display %" PRId32,
4073 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004074 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004075 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004076 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4077 if (touchedInputChannel != nullptr) {
4078 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4079 "touched window was removed");
4080 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004082 state.windows.erase(state.windows.begin() + i);
4083 } else {
4084 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 }
4086 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004087 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004088
Arthur Hung72d8dc32020-03-28 00:48:39 +00004089 // Release information for windows that are no longer present.
4090 // This ensures that unused input channels are released promptly.
4091 // Otherwise, they might stick around until the window handle is destroyed
4092 // which might not happen until the next GC.
4093 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004094 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004095 if (DEBUG_FOCUS) {
4096 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004097 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004098 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004099 }
chaviw291d88a2019-02-14 10:33:58 -08004100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101}
4102
4103void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004104 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004105 if (DEBUG_FOCUS) {
4106 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4107 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4108 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004109 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004110 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Chris Yea209fde2020-07-22 13:54:51 -07004112 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004113 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004114
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004115 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4116 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004117 }
4118
Chris Yea209fde2020-07-22 13:54:51 -07004119 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004120 if (inputApplicationHandle != nullptr) {
4121 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4122 } else {
4123 mFocusedApplicationHandlesByDisplay.erase(displayId);
4124 }
4125
4126 // No matter what the old focused application was, stop waiting on it because it is
4127 // no longer focused.
4128 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 } // release lock
4130
4131 // Wake up poll loop since it may need to make new input dispatching choices.
4132 mLooper->wake();
4133}
4134
Tiger Huang721e26f2018-07-24 22:26:19 +08004135/**
4136 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4137 * the display not specified.
4138 *
4139 * We track any unreleased events for each window. If a window loses the ability to receive the
4140 * released event, we will send a cancel event to it. So when the focused display is changed, we
4141 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4142 * display. The display-specified events won't be affected.
4143 */
4144void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004145 if (DEBUG_FOCUS) {
4146 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4147 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004148 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004149 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004150
4151 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004152 sp<IBinder> oldFocusedWindowToken =
4153 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4154 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004155 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004156 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004157 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004158 CancelationOptions
4159 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4160 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004161 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004162 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4163 }
4164 }
4165 mFocusedDisplayId = displayId;
4166
Chris Ye3c2d6f52020-08-09 10:39:48 -07004167 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004168 sp<IBinder> newFocusedWindowToken =
4169 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4170 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004171
Vishnu Nairad321cd2020-08-20 16:40:21 -07004172 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004173 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004174 if (!mFocusedWindowTokenByDisplay.empty()) {
4175 ALOGE("But another display has a focused window\n%s",
4176 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004177 }
4178 }
4179 }
4180
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004181 if (DEBUG_FOCUS) {
4182 logDispatchStateLocked();
4183 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004184 } // release lock
4185
4186 // Wake up poll loop since it may need to make new input dispatching choices.
4187 mLooper->wake();
4188}
4189
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004191 if (DEBUG_FOCUS) {
4192 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194
4195 bool changed;
4196 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004197 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198
4199 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4200 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004201 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 }
4203
4204 if (mDispatchEnabled && !enabled) {
4205 resetAndDropEverythingLocked("dispatcher is being disabled");
4206 }
4207
4208 mDispatchEnabled = enabled;
4209 mDispatchFrozen = frozen;
4210 changed = true;
4211 } else {
4212 changed = false;
4213 }
4214
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004215 if (DEBUG_FOCUS) {
4216 logDispatchStateLocked();
4217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 } // release lock
4219
4220 if (changed) {
4221 // Wake up poll loop since it may need to make new input dispatching choices.
4222 mLooper->wake();
4223 }
4224}
4225
4226void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004227 if (DEBUG_FOCUS) {
4228 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230
4231 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004232 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233
4234 if (mInputFilterEnabled == enabled) {
4235 return;
4236 }
4237
4238 mInputFilterEnabled = enabled;
4239 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4240 } // release lock
4241
4242 // Wake up poll loop since there might be work to do to drop everything.
4243 mLooper->wake();
4244}
4245
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004246void InputDispatcher::setInTouchMode(bool inTouchMode) {
4247 std::scoped_lock lock(mLock);
4248 mInTouchMode = inTouchMode;
4249}
4250
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004251void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4252 if (opacity < 0 || opacity > 1) {
4253 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4254 return;
4255 }
4256
4257 std::scoped_lock lock(mLock);
4258 mMaximumObscuringOpacityForTouch = opacity;
4259}
4260
4261void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4262 std::scoped_lock lock(mLock);
4263 mBlockUntrustedTouchesMode = mode;
4264}
4265
chaviwfbe5d9c2018-12-26 12:23:37 -08004266bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4267 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004268 if (DEBUG_FOCUS) {
4269 ALOGD("Trivial transfer to same window.");
4270 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004271 return true;
4272 }
4273
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004275 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276
chaviwfbe5d9c2018-12-26 12:23:37 -08004277 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4278 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004279 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004280 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 return false;
4282 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004283 if (DEBUG_FOCUS) {
4284 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4285 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004288 if (DEBUG_FOCUS) {
4289 ALOGD("Cannot transfer focus because windows are on different displays.");
4290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 return false;
4292 }
4293
4294 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004295 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4296 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004297 for (size_t i = 0; i < state.windows.size(); i++) {
4298 const TouchedWindow& touchedWindow = state.windows[i];
4299 if (touchedWindow.windowHandle == fromWindowHandle) {
4300 int32_t oldTargetFlags = touchedWindow.targetFlags;
4301 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004303 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004305 int32_t newTargetFlags = oldTargetFlags &
4306 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4307 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004308 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309
Jeff Brownf086ddb2014-02-11 14:28:48 -08004310 found = true;
4311 goto Found;
4312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004318 if (DEBUG_FOCUS) {
4319 ALOGD("Focus transfer failed because from window did not have focus.");
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 return false;
4322 }
4323
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004324 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4325 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004326 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004327 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004328 CancelationOptions
4329 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4330 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004332 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
4334
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004335 if (DEBUG_FOCUS) {
4336 logDispatchStateLocked();
4337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 } // release lock
4339
4340 // Wake up poll loop since it may need to make new input dispatching choices.
4341 mLooper->wake();
4342 return true;
4343}
4344
4345void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004346 if (DEBUG_FOCUS) {
4347 ALOGD("Resetting and dropping all events (%s).", reason);
4348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349
4350 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4351 synthesizeCancelationEventsForAllConnectionsLocked(options);
4352
4353 resetKeyRepeatLocked();
4354 releasePendingEventLocked();
4355 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004356 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004358 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004359 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004361 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362}
4363
4364void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004365 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 dumpDispatchStateLocked(dump);
4367
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004368 std::istringstream stream(dump);
4369 std::string line;
4370
4371 while (std::getline(stream, line, '\n')) {
4372 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374}
4375
Vishnu Nairad321cd2020-08-20 16:40:21 -07004376std::string InputDispatcher::dumpFocusedWindowsLocked() {
4377 if (mFocusedWindowTokenByDisplay.empty()) {
4378 return INDENT "FocusedWindows: <none>\n";
4379 }
4380
4381 std::string dump;
4382 dump += INDENT "FocusedWindows:\n";
4383 for (auto& it : mFocusedWindowTokenByDisplay) {
4384 const int32_t displayId = it.first;
4385 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4386 if (windowHandle) {
4387 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4388 windowHandle->getName().c_str());
4389 } else {
4390 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4391 " has focused token without a window'\n",
4392 displayId);
4393 }
4394 }
4395 return dump;
4396}
4397
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004398void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004399 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4400 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4401 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004402 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
Tiger Huang721e26f2018-07-24 22:26:19 +08004404 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4405 dump += StringPrintf(INDENT "FocusedApplications:\n");
4406 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4407 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004408 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004409 const std::chrono::duration timeout =
4410 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004412 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004413 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004416 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004418
Vishnu Nairad321cd2020-08-20 16:40:21 -07004419 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004421 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004422 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004423 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4424 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004425 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004426 state.displayId, toString(state.down), toString(state.split),
4427 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004428 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004429 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004430 for (size_t i = 0; i < state.windows.size(); i++) {
4431 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004432 dump += StringPrintf(INDENT4
4433 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4434 i, touchedWindow.windowHandle->getName().c_str(),
4435 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004436 }
4437 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004438 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004439 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004440 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004441 dump += INDENT3 "Portal windows:\n";
4442 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004443 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4445 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004446 }
4447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 }
4449 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004450 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 }
4452
Arthur Hungb92218b2018-08-14 12:00:21 +08004453 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004454 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004455 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004456 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004457 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004458 dump += INDENT2 "Windows:\n";
4459 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004460 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004461 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462
Arthur Hungb92218b2018-08-14 12:00:21 +08004463 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004464 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4465 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004466 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004467 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004468 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004469 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004470 i, windowInfo->name.c_str(), windowInfo->displayId,
4471 windowInfo->portalToDisplayId,
4472 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004473 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 toString(windowInfo->hasWallpaper),
4475 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004476 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004477 static_cast<int32_t>(windowInfo->type),
4478 windowInfo->frameLeft, windowInfo->frameTop,
4479 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004480 windowInfo->globalScaleFactor,
4481 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004482 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004483 dump += StringPrintf(", inputFeatures=%s",
4484 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004485 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4486 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004487 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004488 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004489 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004490 }
4491 } else {
4492 dump += INDENT2 "Windows: <none>\n";
4493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494 }
4495 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004496 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 }
4498
Michael Wright3dd60e22019-03-27 22:06:44 +00004499 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004500 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004501 const std::vector<Monitor>& monitors = it.second;
4502 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4503 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004504 }
4505 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004506 const std::vector<Monitor>& monitors = it.second;
4507 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4508 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004511 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
4513
4514 nsecs_t currentTime = now();
4515
4516 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004517 if (!mRecentQueue.empty()) {
4518 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4519 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004520 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004521 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004522 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004525 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 }
4527
4528 // Dump event currently being dispatched.
4529 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004530 dump += INDENT "PendingEvent:\n";
4531 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004532 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004533 dump += StringPrintf(", age=%" PRId64 "ms\n",
4534 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004536 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 }
4538
4539 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004540 if (!mInboundQueue.empty()) {
4541 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4542 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004543 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004544 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004545 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 }
4547 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004548 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 }
4550
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004551 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004552 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004553 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4554 const KeyReplacement& replacement = pair.first;
4555 int32_t newKeyCode = pair.second;
4556 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004557 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004558 }
4559 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004560 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004561 }
4562
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004563 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004564 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004565 for (const auto& pair : mConnectionsByFd) {
4566 const sp<Connection>& connection = pair.second;
4567 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004568 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004569 pair.first, connection->getInputChannelName().c_str(),
4570 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004573 if (!connection->outboundQueue.empty()) {
4574 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4575 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004576 dump += dumpQueue(connection->outboundQueue, currentTime);
4577
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004579 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 }
4581
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004582 if (!connection->waitQueue.empty()) {
4583 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4584 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004585 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004587 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 }
4589 }
4590 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004591 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 }
4593
4594 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004595 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4596 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004598 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
4600
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004601 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004602 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4603 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4604 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605}
4606
Michael Wright3dd60e22019-03-27 22:06:44 +00004607void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4608 const size_t numMonitors = monitors.size();
4609 for (size_t i = 0; i < numMonitors; i++) {
4610 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004611 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004612 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4613 dump += "\n";
4614 }
4615}
4616
Garfield Tan15601662020-09-22 15:32:38 -07004617base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4618 const std::string& name) {
4619#if DEBUG_CHANNEL_CREATION
4620 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621#endif
4622
Garfield Tan15601662020-09-22 15:32:38 -07004623 std::shared_ptr<InputChannel> serverChannel;
4624 std::unique_ptr<InputChannel> clientChannel;
4625 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4626
4627 if (result) {
4628 return base::Error(result) << "Failed to open input channel pair with name " << name;
4629 }
4630
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004632 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004633 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634
Garfield Tan15601662020-09-22 15:32:38 -07004635 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004636 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004637 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4640 } // release lock
4641
4642 // Wake the looper because some connections have changed.
4643 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004644 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645}
4646
Garfield Tan15601662020-09-22 15:32:38 -07004647base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4648 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4649 std::shared_ptr<InputChannel> serverChannel;
4650 std::unique_ptr<InputChannel> clientChannel;
4651 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4652 if (result) {
4653 return base::Error(result) << "Failed to open input channel pair with name " << name;
4654 }
4655
Michael Wright3dd60e22019-03-27 22:06:44 +00004656 { // acquire lock
4657 std::scoped_lock _l(mLock);
4658
4659 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004660 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4661 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004662 }
4663
Garfield Tan15601662020-09-22 15:32:38 -07004664 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004665
Garfield Tan15601662020-09-22 15:32:38 -07004666 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004667 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004668 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004669
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004670 auto& monitorsByDisplay =
4671 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004672 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004673
4674 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004675 }
Garfield Tan15601662020-09-22 15:32:38 -07004676
Michael Wright3dd60e22019-03-27 22:06:44 +00004677 // Wake the looper because some connections have changed.
4678 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004679 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004680}
4681
Garfield Tan15601662020-09-22 15:32:38 -07004682status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004684 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685
Garfield Tan15601662020-09-22 15:32:38 -07004686 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 if (status) {
4688 return status;
4689 }
4690 } // release lock
4691
4692 // Wake the poll loop because removing the connection may have changed the current
4693 // synchronization state.
4694 mLooper->wake();
4695 return OK;
4696}
4697
Garfield Tan15601662020-09-22 15:32:38 -07004698status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4699 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004700 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004701 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004702 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 return BAD_VALUE;
4704 }
4705
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004706 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004707 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004708
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004710 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 }
4712
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004713 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714
4715 nsecs_t currentTime = now();
4716 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4717
4718 connection->status = Connection::STATUS_ZOMBIE;
4719 return OK;
4720}
4721
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004722void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4723 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4724 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004725}
4726
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004727void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004728 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004729 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004731 std::vector<Monitor>& monitors = it->second;
4732 const size_t numMonitors = monitors.size();
4733 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004734 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735 monitors.erase(monitors.begin() + i);
4736 break;
4737 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004738 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004739 if (monitors.empty()) {
4740 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004741 } else {
4742 ++it;
4743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 }
4745}
4746
Michael Wright3dd60e22019-03-27 22:06:44 +00004747status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4748 { // acquire lock
4749 std::scoped_lock _l(mLock);
4750 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4751
4752 if (!foundDisplayId) {
4753 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4754 return BAD_VALUE;
4755 }
4756 int32_t displayId = foundDisplayId.value();
4757
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004758 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4759 mTouchStatesByDisplay.find(displayId);
4760 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004761 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4762 return BAD_VALUE;
4763 }
4764
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004765 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004766 std::optional<int32_t> foundDeviceId;
4767 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004768 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004769 foundDeviceId = state.deviceId;
4770 }
4771 }
4772 if (!foundDeviceId || !state.down) {
4773 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004774 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004775 return BAD_VALUE;
4776 }
4777 int32_t deviceId = foundDeviceId.value();
4778
4779 // Send cancel events to all the input channels we're stealing from.
4780 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004782 options.deviceId = deviceId;
4783 options.displayId = displayId;
4784 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004785 std::shared_ptr<InputChannel> channel =
4786 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004787 if (channel != nullptr) {
4788 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4789 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004790 }
4791 // Then clear the current touch state so we stop dispatching to them as well.
4792 state.filterNonMonitors();
4793 }
4794 return OK;
4795}
4796
Michael Wright3dd60e22019-03-27 22:06:44 +00004797std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4798 const sp<IBinder>& token) {
4799 for (const auto& it : mGestureMonitorsByDisplay) {
4800 const std::vector<Monitor>& monitors = it.second;
4801 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004802 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004803 return it.first;
4804 }
4805 }
4806 }
4807 return std::nullopt;
4808}
4809
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004810sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004811 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004812 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004813 }
4814
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004815 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004816 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004817 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004818 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
4820 }
Robert Carr4e670e52018-08-15 13:26:12 -07004821
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004822 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823}
4824
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004825void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004827 removeByValue(mConnectionsByFd, connection);
4828}
4829
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004830void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4831 const sp<Connection>& connection, uint32_t seq,
4832 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004833 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4834 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 commandEntry->connection = connection;
4836 commandEntry->eventTime = currentTime;
4837 commandEntry->seq = seq;
4838 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004839 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840}
4841
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4843 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004845 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004847 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4848 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004850 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851}
4852
Vishnu Nairad321cd2020-08-20 16:40:21 -07004853void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4854 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004855 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4856 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004857 commandEntry->oldToken = oldToken;
4858 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004859 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004860}
4861
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004862void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4864 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004865 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004866 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004867 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868 return;
4869 }
4870 /**
4871 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4872 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4873 * has changed. This could cause newer entries to time out before the already dispatched
4874 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4875 * processes the events linearly. So providing information about the oldest entry seems to be
4876 * most useful.
4877 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004878 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4880 std::string reason =
4881 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004882 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004883 ns2ms(currentWait),
4884 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004886 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887 reason);
4888
4889 std::unique_ptr<CommandEntry> commandEntry =
4890 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4891 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004892 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004893 commandEntry->reason = std::move(reason);
4894 postCommandLocked(std::move(commandEntry));
4895}
4896
Chris Yea209fde2020-07-22 13:54:51 -07004897void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004898 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4899 application->getName().c_str());
4900
4901 updateLastAnrStateLocked(application, reason);
4902
4903 std::unique_ptr<CommandEntry> commandEntry =
4904 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4905 commandEntry->inputApplicationHandle = application;
4906 commandEntry->inputChannel = nullptr;
4907 commandEntry->reason = std::move(reason);
4908 postCommandLocked(std::move(commandEntry));
4909}
4910
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004911void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
4912 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4913 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
4914 commandEntry->obscuringPackage = obscuringPackage;
4915 postCommandLocked(std::move(commandEntry));
4916}
4917
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4919 const std::string& reason) {
4920 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4921 updateLastAnrStateLocked(windowLabel, reason);
4922}
4923
Chris Yea209fde2020-07-22 13:54:51 -07004924void InputDispatcher::updateLastAnrStateLocked(
4925 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004926 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4927 updateLastAnrStateLocked(windowLabel, reason);
4928}
4929
4930void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4931 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004933 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 struct tm tm;
4935 localtime_r(&t, &tm);
4936 char timestr[64];
4937 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004938 mLastAnrState.clear();
4939 mLastAnrState += INDENT "ANR:\n";
4940 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4942 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004943 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944}
4945
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004946void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947 mLock.unlock();
4948
4949 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4950
4951 mLock.lock();
4952}
4953
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004954void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 sp<Connection> connection = commandEntry->connection;
4956
4957 if (connection->status != Connection::STATUS_ZOMBIE) {
4958 mLock.unlock();
4959
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004960 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961
4962 mLock.lock();
4963 }
4964}
4965
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004966void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004967 sp<IBinder> oldToken = commandEntry->oldToken;
4968 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004969 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004970 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004971 mLock.lock();
4972}
4973
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004974void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004975 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004976 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 mLock.unlock();
4978
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004979 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004980 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981
4982 mLock.lock();
4983
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004984 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004985 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4986 } else {
4987 // stop waking up for events in this connection, it is already not responding
4988 sp<Connection> connection = getConnectionLocked(token);
4989 if (connection == nullptr) {
4990 return;
4991 }
4992 cancelEventsForAnrLocked(connection);
4993 }
4994}
4995
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004996void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
4997 mLock.unlock();
4998
4999 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5000
5001 mLock.lock();
5002}
5003
Chris Yea209fde2020-07-22 13:54:51 -07005004void InputDispatcher::extendAnrTimeoutsLocked(
5005 const std::shared_ptr<InputApplicationHandle>& application,
5006 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005007 if (connectionToken == nullptr && application != nullptr) {
5008 // The ANR happened because there's no focused window
5009 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
5010 mAwaitedFocusedApplication = application;
5011 }
5012
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005013 sp<Connection> connection = getConnectionLocked(connectionToken);
5014 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005015 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005016 return;
5017 }
5018
5019 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05005020 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005021
5022 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05005023 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005024 for (DispatchEntry* entry : connection->waitQueue) {
5025 if (newTimeout >= entry->timeoutTime) {
5026 // Already removed old entries when connection was marked unresponsive
5027 entry->timeoutTime = newTimeout;
5028 mAnrTracker.insert(entry->timeoutTime, connectionToken);
5029 }
5030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031}
5032
5033void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5034 CommandEntry* commandEntry) {
5035 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005036 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037
5038 mLock.unlock();
5039
Michael Wright2b3c3302018-03-02 17:19:13 +00005040 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005042 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005043 : nullptr;
5044 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005045 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5046 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005047 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049
5050 mLock.lock();
5051
5052 if (delay < 0) {
5053 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5054 } else if (!delay) {
5055 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5056 } else {
5057 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5058 entry->interceptKeyWakeupTime = now() + delay;
5059 }
5060 entry->release();
5061}
5062
chaviwfd6d3512019-03-25 13:23:49 -07005063void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5064 mLock.unlock();
5065 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5066 mLock.lock();
5067}
5068
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005069/**
5070 * Connection is responsive if it has no events in the waitQueue that are older than the
5071 * current time.
5072 */
5073static bool isConnectionResponsive(const Connection& connection) {
5074 const nsecs_t currentTime = now();
5075 for (const DispatchEntry* entry : connection.waitQueue) {
5076 if (entry->timeoutTime < currentTime) {
5077 return false;
5078 }
5079 }
5080 return true;
5081}
5082
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005083void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005085 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005087 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088
5089 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005090 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005091 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005092 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005094 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005095 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005096 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005097 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5098 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005099 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005100 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005101
5102 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005103 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005104 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5105 restartEvent =
5106 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005107 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005108 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5109 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5110 handled);
5111 } else {
5112 restartEvent = false;
5113 }
5114
5115 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005116 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005117 // contents of the wait queue to have been drained, so we need to double-check
5118 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005119 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5120 if (dispatchEntryIt != connection->waitQueue.end()) {
5121 dispatchEntry = *dispatchEntryIt;
5122 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005123 mAnrTracker.erase(dispatchEntry->timeoutTime,
5124 connection->inputChannel->getConnectionToken());
5125 if (!connection->responsive) {
5126 connection->responsive = isConnectionResponsive(*connection);
5127 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005128 traceWaitQueueLength(connection);
5129 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005130 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005131 traceOutboundQueueLength(connection);
5132 } else {
5133 releaseDispatchEntry(dispatchEntry);
5134 }
5135 }
5136
5137 // Start the next dispatch cycle for this connection.
5138 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139}
5140
5141bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005142 DispatchEntry* dispatchEntry,
5143 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005144 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005145 if (!handled) {
5146 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005147 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005148 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005149 return false;
5150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005152 // Get the fallback key state.
5153 // Clear it out after dispatching the UP.
5154 int32_t originalKeyCode = keyEntry->keyCode;
5155 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5156 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5157 connection->inputState.removeFallbackKey(originalKeyCode);
5158 }
5159
5160 if (handled || !dispatchEntry->hasForegroundTarget()) {
5161 // If the application handles the original key for which we previously
5162 // generated a fallback or if the window is not a foreground window,
5163 // then cancel the associated fallback key, if any.
5164 if (fallbackKeyCode != -1) {
5165 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005167 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005168 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5169 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5170 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005172 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005173 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174
5175 mLock.unlock();
5176
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005177 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005178 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179
5180 mLock.lock();
5181
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005182 // Cancel the fallback key.
5183 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005185 "application handled the original non-fallback key "
5186 "or is no longer a foreground target, "
5187 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 options.keyCode = fallbackKeyCode;
5189 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005191 connection->inputState.removeFallbackKey(originalKeyCode);
5192 }
5193 } else {
5194 // If the application did not handle a non-fallback key, first check
5195 // that we are in a good state to perform unhandled key event processing
5196 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005197 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005198 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005200 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005201 "since this is not an initial down. "
5202 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5203 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005204#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005205 return false;
5206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005208 // Dispatch the unhandled key to the policy.
5209#if DEBUG_OUTBOUND_EVENT_DETAILS
5210 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005211 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5212 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005213#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005214 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005215
5216 mLock.unlock();
5217
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005218 bool fallback =
5219 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5220 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005221
5222 mLock.lock();
5223
5224 if (connection->status != Connection::STATUS_NORMAL) {
5225 connection->inputState.removeFallbackKey(originalKeyCode);
5226 return false;
5227 }
5228
5229 // Latch the fallback keycode for this key on an initial down.
5230 // The fallback keycode cannot change at any other point in the lifecycle.
5231 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005233 fallbackKeyCode = event.getKeyCode();
5234 } else {
5235 fallbackKeyCode = AKEYCODE_UNKNOWN;
5236 }
5237 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5238 }
5239
5240 ALOG_ASSERT(fallbackKeyCode != -1);
5241
5242 // Cancel the fallback key if the policy decides not to send it anymore.
5243 // We will continue to dispatch the key to the policy but we will no
5244 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005245 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5246 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005247#if DEBUG_OUTBOUND_EVENT_DETAILS
5248 if (fallback) {
5249 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005250 "as a fallback for %d, but on the DOWN it had requested "
5251 "to send %d instead. Fallback canceled.",
5252 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005253 } else {
5254 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005255 "but on the DOWN it had requested to send %d. "
5256 "Fallback canceled.",
5257 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005258 }
5259#endif
5260
5261 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5262 "canceling fallback, policy no longer desires it");
5263 options.keyCode = fallbackKeyCode;
5264 synthesizeCancelationEventsForConnectionLocked(connection, options);
5265
5266 fallback = false;
5267 fallbackKeyCode = AKEYCODE_UNKNOWN;
5268 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005269 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005270 }
5271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
5273#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005274 {
5275 std::string msg;
5276 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5277 connection->inputState.getFallbackKeys();
5278 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005279 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005281 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005282 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005283 }
5284#endif
5285
5286 if (fallback) {
5287 // Restart the dispatch cycle using the fallback key.
5288 keyEntry->eventTime = event.getEventTime();
5289 keyEntry->deviceId = event.getDeviceId();
5290 keyEntry->source = event.getSource();
5291 keyEntry->displayId = event.getDisplayId();
5292 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5293 keyEntry->keyCode = fallbackKeyCode;
5294 keyEntry->scanCode = event.getScanCode();
5295 keyEntry->metaState = event.getMetaState();
5296 keyEntry->repeatCount = event.getRepeatCount();
5297 keyEntry->downTime = event.getDownTime();
5298 keyEntry->syntheticRepeat = false;
5299
5300#if DEBUG_OUTBOUND_EVENT_DETAILS
5301 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005302 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5303 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005304#endif
5305 return true; // restart the event
5306 } else {
5307#if DEBUG_OUTBOUND_EVENT_DETAILS
5308 ALOGD("Unhandled key event: No fallback key.");
5309#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005310
5311 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005312 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 }
5314 }
5315 return false;
5316}
5317
5318bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005319 DispatchEntry* dispatchEntry,
5320 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 return false;
5322}
5323
5324void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5325 mLock.unlock();
5326
5327 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5328
5329 mLock.lock();
5330}
5331
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005332KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5333 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005334 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005335 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5336 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005337 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338}
5339
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005340void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5341 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 // TODO Write some statistics about how long we spend waiting.
5343}
5344
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005345/**
5346 * Report the touch event latency to the statsd server.
5347 * Input events are reported for statistics if:
5348 * - This is a touchscreen event
5349 * - InputFilter is not enabled
5350 * - Event is not injected or synthesized
5351 *
5352 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5353 * from getting aggregated with the "old" data.
5354 */
5355void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5356 REQUIRES(mLock) {
5357 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5358 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5359 if (!reportForStatistics) {
5360 return;
5361 }
5362
5363 if (mTouchStatistics.shouldReport()) {
5364 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5365 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5366 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5367 mTouchStatistics.reset();
5368 }
5369 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5370 mTouchStatistics.addValue(latencyMicros);
5371}
5372
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373void InputDispatcher::traceInboundQueueLengthLocked() {
5374 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005375 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 }
5377}
5378
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005379void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 if (ATRACE_ENABLED()) {
5381 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005382 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005383 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 }
5385}
5386
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005387void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 if (ATRACE_ENABLED()) {
5389 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005390 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005391 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392 }
5393}
5394
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005395void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005396 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005398 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 dumpDispatchStateLocked(dump);
5400
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005401 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005402 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005403 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 }
5405}
5406
5407void InputDispatcher::monitor() {
5408 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005409 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005411 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412}
5413
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005414/**
5415 * Wake up the dispatcher and wait until it processes all events and commands.
5416 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5417 * this method can be safely called from any thread, as long as you've ensured that
5418 * the work you are interested in completing has already been queued.
5419 */
5420bool InputDispatcher::waitForIdle() {
5421 /**
5422 * Timeout should represent the longest possible time that a device might spend processing
5423 * events and commands.
5424 */
5425 constexpr std::chrono::duration TIMEOUT = 100ms;
5426 std::unique_lock lock(mLock);
5427 mLooper->wake();
5428 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5429 return result == std::cv_status::no_timeout;
5430}
5431
Vishnu Naire798b472020-07-23 13:52:21 -07005432/**
5433 * Sets focus to the window identified by the token. This must be called
5434 * after updating any input window handles.
5435 *
5436 * Params:
5437 * request.token - input channel token used to identify the window that should gain focus.
5438 * request.focusedToken - the token that the caller expects currently to be focused. If the
5439 * specified token does not match the currently focused window, this request will be dropped.
5440 * If the specified focused token matches the currently focused window, the call will succeed.
5441 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5442 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5443 * when requesting the focus change. This determines which request gets
5444 * precedence if there is a focus change request from another source such as pointer down.
5445 */
Vishnu Nair958da932020-08-21 17:12:37 -07005446void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5447 { // acquire lock
5448 std::scoped_lock _l(mLock);
5449
5450 const int32_t displayId = request.displayId;
5451 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5452 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5453 ALOGD_IF(DEBUG_FOCUS,
5454 "setFocusedWindow on display %" PRId32
5455 " ignored, reason: focusedToken is not focused",
5456 displayId);
5457 return;
5458 }
5459
5460 mPendingFocusRequests.erase(displayId);
5461 FocusResult result = handleFocusRequestLocked(request);
5462 if (result == FocusResult::NOT_VISIBLE) {
5463 // The requested window is not currently visible. Wait for the window to become visible
5464 // and then provide it focus. This is to handle situations where a user action triggers
5465 // a new window to appear. We want to be able to queue any key events after the user
5466 // action and deliver it to the newly focused window. In order for this to happen, we
5467 // take focus from the currently focused window so key events can be queued.
5468 ALOGD_IF(DEBUG_FOCUS,
5469 "setFocusedWindow on display %" PRId32
5470 " pending, reason: window is not visible",
5471 displayId);
5472 mPendingFocusRequests[displayId] = request;
5473 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5474 "setFocusedWindow_AwaitingWindowVisibility");
5475 } else if (result != FocusResult::OK) {
5476 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5477 typeToString(result));
5478 }
5479 } // release lock
5480 // Wake up poll loop since it may need to make new input dispatching choices.
5481 mLooper->wake();
5482}
5483
5484InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5485 const FocusRequest& request) {
5486 const int32_t displayId = request.displayId;
5487 const sp<IBinder> newFocusedToken = request.token;
5488 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5489
5490 if (oldFocusedToken == request.token) {
5491 ALOGD_IF(DEBUG_FOCUS,
5492 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5493 displayId);
5494 return FocusResult::OK;
5495 }
5496
5497 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5498 if (result != FocusResult::OK) {
5499 return result;
5500 }
5501
5502 std::string_view reason =
5503 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5504 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5505 return FocusResult::OK;
5506}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005507
Vishnu Nairad321cd2020-08-20 16:40:21 -07005508void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5509 const sp<IBinder>& newFocusedToken, int32_t displayId,
5510 std::string_view reason) {
5511 if (oldFocusedToken) {
5512 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005513 if (focusedInputChannel) {
5514 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5515 "focus left window");
5516 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005517 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005518 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005519 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005520 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005521 if (newFocusedToken) {
5522 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5523 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005524 }
5525
5526 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005527 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005528 }
5529}
Vishnu Nair958da932020-08-21 17:12:37 -07005530
5531/**
5532 * Checks if the window token can be focused on a display. The token can be focused if there is
5533 * at least one window handle that is visible with the same token and all window handles with the
5534 * same token are focusable.
5535 *
5536 * In the case of mirroring, two windows may share the same window token and their visibility
5537 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5538 * we expect the focusability of the windows to match since its hard to reason why one window can
5539 * receive focus events and the other cannot when both are backed by the same input channel.
5540 */
5541InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5542 int32_t displayId) const {
5543 bool allWindowsAreFocusable = true;
5544 bool visibleWindowFound = false;
5545 bool windowFound = false;
5546 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5547 if (window->getToken() != token) {
5548 continue;
5549 }
5550 windowFound = true;
5551 if (window->getInfo()->visible) {
5552 // Check if at least a single window is visible.
5553 visibleWindowFound = true;
5554 }
5555 if (!window->getInfo()->focusable) {
5556 // Check if all windows with the window token are focusable.
5557 allWindowsAreFocusable = false;
5558 break;
5559 }
5560 }
5561
5562 if (!windowFound) {
5563 return FocusResult::NO_WINDOW;
5564 }
5565 if (!allWindowsAreFocusable) {
5566 return FocusResult::NOT_FOCUSABLE;
5567 }
5568 if (!visibleWindowFound) {
5569 return FocusResult::NOT_VISIBLE;
5570 }
5571
5572 return FocusResult::OK;
5573}
Garfield Tane84e6f92019-08-29 17:28:41 -07005574} // namespace android::inputdispatcher