blob: ab25e2b05f1cdfa61cf838c1798817ab0b657a4a [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 {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500564 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700565 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
566 }
567 }
568
569 // Check if any connection ANRs are due
570 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
571 if (currentTime < nextAnrCheck) { // most likely scenario
572 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
573 }
574
575 // If we reached here, we have an unresponsive connection.
576 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
577 if (connection == nullptr) {
578 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
579 return nextAnrCheck;
580 }
581 connection->responsive = false;
582 // Stop waking up for this unresponsive connection
583 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500584 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700585 return LONG_LONG_MIN;
586}
587
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500588std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700589 sp<InputWindowHandle> window = getWindowHandleLocked(token);
590 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500591 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700592 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500593 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700594}
595
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
597 nsecs_t currentTime = now();
598
Jeff Browndc5992e2014-04-11 01:27:26 -0700599 // Reset the key repeat timer whenever normal dispatch is suspended while the
600 // device is in a non-interactive state. This is to ensure that we abort a key
601 // repeat if the device is just coming out of sleep.
602 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 resetKeyRepeatLocked();
604 }
605
606 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
607 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100608 if (DEBUG_FOCUS) {
609 ALOGD("Dispatch frozen. Waiting some more.");
610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 return;
612 }
613
614 // Optimize latency of app switches.
615 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
616 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
617 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
618 if (mAppSwitchDueTime < *nextWakeupTime) {
619 *nextWakeupTime = mAppSwitchDueTime;
620 }
621
622 // Ready to start a new event.
623 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700624 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700625 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 if (isAppSwitchDue) {
627 // The inbound queue is empty so the app switch key we were waiting
628 // for will never arrive. Stop waiting for it.
629 resetPendingAppSwitchLocked(false);
630 isAppSwitchDue = false;
631 }
632
633 // Synthesize a key repeat if appropriate.
634 if (mKeyRepeatState.lastKeyEntry) {
635 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
636 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
637 } else {
638 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
639 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
640 }
641 }
642 }
643
644 // Nothing to do if there is no pending event.
645 if (!mPendingEvent) {
646 return;
647 }
648 } else {
649 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700650 mPendingEvent = mInboundQueue.front();
651 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 traceInboundQueueLengthLocked();
653 }
654
655 // Poke user activity for this event.
656 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700657 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 }
660
661 // Now we have an event to dispatch.
662 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700663 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700667 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700669 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
671
672 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700673 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675
676 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700677 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700678 ConfigurationChangedEntry* typedEntry =
679 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
680 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700681 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700682 break;
683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700685 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700686 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
687 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700688 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700689 break;
690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100692 case EventEntry::Type::FOCUS: {
693 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
694 dispatchFocusLocked(currentTime, typedEntry);
695 done = true;
696 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
697 break;
698 }
699
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700700 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700701 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
702 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700703 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700704 resetPendingAppSwitchLocked(true);
705 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700706 } else if (dropReason == DropReason::NOT_DROPPED) {
707 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700708 }
709 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700710 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700711 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700712 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700713 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
714 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700715 }
716 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
717 break;
718 }
719
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700720 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700721 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700722 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
723 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700725 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700726 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700727 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700728 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
729 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700730 }
731 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
732 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
735
736 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700737 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700738 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 }
Michael Wright3a981722015-06-10 15:26:13 +0100740 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741
742 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700743 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 }
745}
746
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700747/**
748 * Return true if the events preceding this incoming motion event should be dropped
749 * Return false otherwise (the default behaviour)
750 */
751bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700752 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700753 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700754
755 // Optimize case where the current application is unresponsive and the user
756 // decides to touch a window in a different application.
757 // If the application takes too long to catch up then we drop all events preceding
758 // the touch into the other window.
759 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700760 int32_t displayId = motionEntry.displayId;
761 int32_t x = static_cast<int32_t>(
762 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
763 int32_t y = static_cast<int32_t>(
764 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
765 sp<InputWindowHandle> touchedWindowHandle =
766 findTouchedWindowAtLocked(displayId, x, y, nullptr);
767 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700768 touchedWindowHandle->getApplicationToken() !=
769 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700770 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700771 ALOGI("Pruning input queue because user touched a different application while waiting "
772 "for %s",
773 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700774 return true;
775 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700776
777 // Alternatively, maybe there's a gesture monitor that could handle this event
778 std::vector<TouchedMonitor> gestureMonitors =
779 findTouchedGestureMonitorsLocked(displayId, {});
780 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
781 sp<Connection> connection =
782 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000783 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700784 // This monitor could take more input. Drop all events preceding this
785 // event, so that gesture monitor could get a chance to receive the stream
786 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
787 "responsive gesture monitor that may handle the event",
788 mAwaitedFocusedApplication->getName().c_str());
789 return true;
790 }
791 }
792 }
793
794 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
795 // yet been processed by some connections, the dispatcher will wait for these motion
796 // events to be processed before dispatching the key event. This is because these motion events
797 // may cause a new window to be launched, which the user might expect to receive focus.
798 // To prevent waiting forever for such events, just send the key to the currently focused window
799 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
800 ALOGD("Received a new pointer down event, stop waiting for events to process and "
801 "just send the pending key event to the focused window.");
802 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700803 }
804 return false;
805}
806
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700808 bool needWake = mInboundQueue.empty();
809 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 traceInboundQueueLengthLocked();
811
812 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700813 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 // Optimize app switch latency.
815 // If the application takes too long to catch up then we drop all events preceding
816 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700817 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700819 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700821 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700826 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 mAppSwitchSawKeyDown = false;
828 needWake = true;
829 }
830 }
831 }
832 break;
833 }
834
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700835 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700836 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
837 mNextUnblockedEvent = entry;
838 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700840 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100842 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700843 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
844 break;
845 }
846 case EventEntry::Type::CONFIGURATION_CHANGED:
847 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700848 // nothing to do
849 break;
850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
852
853 return needWake;
854}
855
856void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
857 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700858 mRecentQueue.push_back(entry);
859 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
860 mRecentQueue.front()->release();
861 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
863}
864
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700866 int32_t y, TouchState* touchState,
867 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700869 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
870 LOG_ALWAYS_FATAL(
871 "Must provide a valid touch state if adding portal windows or outside targets");
872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700874 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800875 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 const InputWindowInfo* windowInfo = windowHandle->getInfo();
877 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100878 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879
880 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100881 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
882 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
883 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800885 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 if (portalToDisplayId != ADISPLAY_ID_NONE &&
887 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800888 if (addPortalWindows) {
889 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700890 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800891 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700892 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 // Found window.
896 return windowHandle;
897 }
898 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800899
Michael Wright44753b12020-07-08 13:48:11 +0100900 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700901 touchState->addOrUpdateWindow(windowHandle,
902 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
903 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
907 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700908 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909}
910
Garfield Tane84e6f92019-08-29 17:28:41 -0700911std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700912 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000913 std::vector<TouchedMonitor> touchedMonitors;
914
915 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
916 addGestureMonitors(monitors, touchedMonitors);
917 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
918 const InputWindowInfo* windowInfo = portalWindow->getInfo();
919 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700920 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
921 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000922 }
923 return touchedMonitors;
924}
925
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700926void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 const char* reason;
928 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700929 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 reason = "inbound event was dropped because the policy consumed it";
934 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700935 case DropReason::DISABLED:
936 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 ALOGI("Dropped event because input dispatch is disabled.");
938 }
939 reason = "inbound event was dropped because input dispatch is disabled";
940 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700941 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700942 ALOGI("Dropped event because of pending overdue app switch.");
943 reason = "inbound event was dropped because of pending overdue app switch";
944 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700945 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 ALOGI("Dropped event because the current application is not responding and the user "
947 "has started interacting with a different application.");
948 reason = "inbound event was dropped because the current application is not responding "
949 "and the user has started interacting with a different application";
950 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700951 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 ALOGI("Dropped event because it is stale.");
953 reason = "inbound event was dropped because it is stale";
954 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700955 case DropReason::NOT_DROPPED: {
956 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700957 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 }
960
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700961 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700962 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
964 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700965 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700967 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700968 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
969 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700970 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
971 synthesizeCancelationEventsForAllConnectionsLocked(options);
972 } else {
973 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
974 synthesizeCancelationEventsForAllConnectionsLocked(options);
975 }
976 break;
977 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100978 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700979 case EventEntry::Type::CONFIGURATION_CHANGED:
980 case EventEntry::Type::DEVICE_RESET: {
981 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
982 break;
983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 }
985}
986
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800987static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
989 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990}
991
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
993 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
994 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
995 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996}
997
998bool InputDispatcher::isAppSwitchPendingLocked() {
999 return mAppSwitchDueTime != LONG_LONG_MAX;
1000}
1001
1002void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1003 mAppSwitchDueTime = LONG_LONG_MAX;
1004
1005#if DEBUG_APP_SWITCH
1006 if (handled) {
1007 ALOGD("App switch has arrived.");
1008 } else {
1009 ALOGD("App switch was abandoned.");
1010 }
1011#endif
1012}
1013
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001015 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016}
1017
1018bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001019 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 return false;
1021 }
1022
1023 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001024 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001025 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001027 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028
1029 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001030 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 return true;
1032}
1033
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001034void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1035 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036}
1037
1038void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001039 while (!mInboundQueue.empty()) {
1040 EventEntry* entry = mInboundQueue.front();
1041 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 releaseInboundEventLocked(entry);
1043 }
1044 traceInboundQueueLengthLocked();
1045}
1046
1047void InputDispatcher::releasePendingEventLocked() {
1048 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001050 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052}
1053
1054void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1055 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001056 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057#if DEBUG_DISPATCH_CYCLE
1058 ALOGD("Injected inbound event was dropped.");
1059#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001060 setInjectionResult(entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 }
1062 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001063 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
1065 addRecentEventLocked(entry);
1066 entry->release();
1067}
1068
1069void InputDispatcher::resetKeyRepeatLocked() {
1070 if (mKeyRepeatState.lastKeyEntry) {
1071 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001072 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074}
1075
Garfield Tane84e6f92019-08-29 17:28:41 -07001076KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1078
1079 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001080 uint32_t policyFlags = entry->policyFlags &
1081 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 if (entry->refCount == 1) {
1083 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001084 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 entry->eventTime = currentTime;
1086 entry->policyFlags = policyFlags;
1087 entry->repeatCount += 1;
1088 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001090 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001091 entry->displayId, policyFlags, entry->action, entry->flags,
1092 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094
1095 mKeyRepeatState.lastKeyEntry = newEntry;
1096 entry->release();
1097
1098 entry = newEntry;
1099 }
1100 entry->syntheticRepeat = true;
1101
1102 // Increment reference count since we keep a reference to the event in
1103 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1104 entry->refCount += 1;
1105
1106 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1107 return entry;
1108}
1109
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1111 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001113 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#endif
1115
1116 // Reset key repeating in case a keyboard device was added or removed or something.
1117 resetKeyRepeatLocked();
1118
1119 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001120 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1121 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001123 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 return true;
1125}
1126
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001129 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131#endif
1132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 options.deviceId = entry->deviceId;
1135 synthesizeCancelationEventsForAllConnectionsLocked(options);
1136 return true;
1137}
1138
Vishnu Nairad321cd2020-08-20 16:40:21 -07001139void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001140 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001141 if (mPendingEvent != nullptr) {
1142 // Move the pending event to the front of the queue. This will give the chance
1143 // for the pending event to get dispatched to the newly focused window
1144 mInboundQueue.push_front(mPendingEvent);
1145 mPendingEvent = nullptr;
1146 }
1147
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001148 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001149 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001150
1151 // This event should go to the front of the queue, but behind all other focus events
1152 // Find the last focus event, and insert right after it
1153 std::deque<EventEntry*>::reverse_iterator it =
1154 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1155 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1156
1157 // Maintain the order of focus events. Insert the entry after all other focus events.
1158 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001159}
1160
1161void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001162 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001163 if (channel == nullptr) {
1164 return; // Window has gone away
1165 }
1166 InputTarget target;
1167 target.inputChannel = channel;
1168 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1169 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001170 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1171 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001172 std::string reason = std::string("reason=").append(entry->reason);
1173 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001174 dispatchEventLocked(currentTime, entry, {target});
1175}
1176
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 if (!entry->dispatchInProgress) {
1181 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1182 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1183 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1184 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001185 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 // We have seen two identical key downs in a row which indicates that the device
1187 // driver is automatically generating key repeats itself. We take note of the
1188 // repeat here, but we disable our own next key repeat timer since it is clear that
1189 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001190 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1191 // Make sure we don't get key down from a different device. If a different
1192 // device Id has same key pressed down, the new device Id will replace the
1193 // current one to hold the key repeat with repeat count reset.
1194 // In the future when got a KEY_UP on the device id, drop it and do not
1195 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1197 resetKeyRepeatLocked();
1198 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1199 } else {
1200 // Not a repeat. Save key down state in case we do see a repeat later.
1201 resetKeyRepeatLocked();
1202 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1203 }
1204 mKeyRepeatState.lastKeyEntry = entry;
1205 entry->refCount += 1;
Chris Ye2ad95392020-09-01 13:44:44 -07001206 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1207 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1208 // The stale device releases the key, reset staleDeviceId.
1209#if DEBUG_INBOUND_EVENT_DETAILS
1210 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1211#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 resetKeyRepeatLocked();
1214 }
1215
1216 if (entry->repeatCount == 1) {
1217 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1218 } else {
1219 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1220 }
1221
1222 entry->dispatchInProgress = true;
1223
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001224 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 }
1226
1227 // Handle case where the policy asked us to try again later last time.
1228 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1229 if (currentTime < entry->interceptKeyWakeupTime) {
1230 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1231 *nextWakeupTime = entry->interceptKeyWakeupTime;
1232 }
1233 return false; // wait until next wakeup
1234 }
1235 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1236 entry->interceptKeyWakeupTime = 0;
1237 }
1238
1239 // Give the policy a chance to intercept the key.
1240 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1241 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001242 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001243 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001244 sp<IBinder> focusedWindowToken =
1245 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1246 if (focusedWindowToken != nullptr) {
1247 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
1249 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001250 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 entry->refCount += 1;
1252 return false; // wait for the command to run
1253 } else {
1254 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1255 }
1256 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001257 if (*dropReason == DropReason::NOT_DROPPED) {
1258 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 }
1260 }
1261
1262 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001263 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001265 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1266 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001267 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 return true;
1269 }
1270
1271 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001272 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001273 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001274 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001275 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 return false;
1277 }
1278
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001279 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001280 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 return true;
1282 }
1283
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001284 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001285 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
1287 // Dispatch the key.
1288 dispatchEventLocked(currentTime, entry, inputTargets);
1289 return true;
1290}
1291
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001292void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001294 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1296 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001297 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1298 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1299 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300#endif
1301}
1302
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1304 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001305 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 entry->dispatchInProgress = true;
1309
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001310 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 }
1312
1313 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001314 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 setInjectionResult(entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001316 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1317 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 return true;
1319 }
1320
1321 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1322
1323 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001324 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325
1326 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001327 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 if (isPointerEvent) {
1329 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001330 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001331 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001332 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 } else {
1334 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001335 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001336 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001338 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 return false;
1340 }
1341
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001342 setInjectionResult(entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001343 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001344 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1345 return true;
1346 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001347 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001348 CancelationOptions::Mode mode(isPointerEvent
1349 ? CancelationOptions::CANCEL_POINTER_EVENTS
1350 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1351 CancelationOptions options(mode, "input event injection failed");
1352 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 return true;
1354 }
1355
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001356 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001359 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001360 std::unordered_map<int32_t, TouchState>::iterator it =
1361 mTouchStatesByDisplay.find(entry->displayId);
1362 if (it != mTouchStatesByDisplay.end()) {
1363 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001364 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001365 // The event has gone through these portal windows, so we add monitoring targets of
1366 // the corresponding displays as well.
1367 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001368 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001369 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001371 }
1372 }
1373 }
1374 }
1375
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 // Dispatch the motion.
1377 if (conflictingPointerActions) {
1378 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001379 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 synthesizeCancelationEventsForAllConnectionsLocked(options);
1381 }
1382 dispatchEventLocked(currentTime, entry, inputTargets);
1383 return true;
1384}
1385
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001386void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001388 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001389 ", policyFlags=0x%x, "
1390 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1391 "metaState=0x%x, buttonState=0x%x,"
1392 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001393 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1394 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1395 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001397 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001399 "x=%f, y=%f, pressure=%f, size=%f, "
1400 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1401 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1403 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1404 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1405 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1406 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1407 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1408 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1409 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1410 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1411 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 }
1413#endif
1414}
1415
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001416void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1417 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001418 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419#if DEBUG_DISPATCH_CYCLE
1420 ALOGD("dispatchEventToCurrentInputTargets");
1421#endif
1422
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001423 updateInteractionTokensLocked(*eventEntry, inputTargets);
1424
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1426
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001427 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001429 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001430 sp<Connection> connection =
1431 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001432 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001433 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001435 if (DEBUG_FOCUS) {
1436 ALOGD("Dropping event delivery to target with channel '%s' because it "
1437 "is no longer registered with the input dispatcher.",
1438 inputTarget.inputChannel->getName().c_str());
1439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 }
1441 }
1442}
1443
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001444void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1445 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1446 // If the policy decides to close the app, we will get a channel removal event via
1447 // unregisterInputChannel, and will clean up the connection that way. We are already not
1448 // sending new pointers to the connection when it blocked, but focused events will continue to
1449 // pile up.
1450 ALOGW("Canceling events for %s because it is unresponsive",
1451 connection->inputChannel->getName().c_str());
1452 if (connection->status == Connection::STATUS_NORMAL) {
1453 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1454 "application not responding");
1455 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 }
1457}
1458
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001459void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001460 if (DEBUG_FOCUS) {
1461 ALOGD("Resetting ANR timeouts.");
1462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463
1464 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001466 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467}
1468
Tiger Huang721e26f2018-07-24 22:26:19 +08001469/**
1470 * Get the display id that the given event should go to. If this event specifies a valid display id,
1471 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1472 * Focused display is the display that the user most recently interacted with.
1473 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001474int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001475 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001476 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001477 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1479 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001480 break;
1481 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001482 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001483 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1484 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001485 break;
1486 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001487 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001488 case EventEntry::Type::CONFIGURATION_CHANGED:
1489 case EventEntry::Type::DEVICE_RESET: {
1490 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001491 return ADISPLAY_ID_NONE;
1492 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001493 }
1494 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1495}
1496
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001497bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1498 const char* focusedWindowName) {
1499 if (mAnrTracker.empty()) {
1500 // already processed all events that we waited for
1501 mKeyIsWaitingForEventsTimeout = std::nullopt;
1502 return false;
1503 }
1504
1505 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1506 // Start the timer
1507 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1508 "focus to change",
1509 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001510 mKeyIsWaitingForEventsTimeout = currentTime +
1511 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1512 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001513 return true;
1514 }
1515
1516 // We still have pending events, and already started the timer
1517 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1518 return true; // Still waiting
1519 }
1520
1521 // Waited too long, and some connection still hasn't processed all motions
1522 // Just send the key to the focused window
1523 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1524 focusedWindowName);
1525 mKeyIsWaitingForEventsTimeout = std::nullopt;
1526 return false;
1527}
1528
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001529InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1530 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1531 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001532 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533
Tiger Huang721e26f2018-07-24 22:26:19 +08001534 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001535 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001536 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001537 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1538
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 // If there is no currently focused window and no focused application
1540 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001541 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1542 ALOGI("Dropping %s event because there is no focused window or focused application in "
1543 "display %" PRId32 ".",
1544 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001545 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001548 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1549 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1550 // start interacting with another application via touch (app switch). This code can be removed
1551 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1552 // an app is expected to have a focused window.
1553 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1554 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1555 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001556 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1557 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1558 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001559 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001560 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001561 ALOGW("Waiting because no window has focus but %s may eventually add a "
1562 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001563 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001564 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001566 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1567 // Already raised ANR. Drop the event
1568 ALOGE("Dropping %s event because there is no focused window",
1569 EventEntry::typeToString(entry.type));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001570 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001571 } else {
1572 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001574 }
1575 }
1576
1577 // we have a valid, non-null focused window
1578 resetNoFocusedWindowTimeoutLocked();
1579
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001581 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 }
1584
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001585 if (focusedWindowHandle->getInfo()->paused) {
1586 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001587 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001588 }
1589
1590 // If the event is a key event, then we must wait for all previous events to
1591 // complete before delivering it because previous events may have the
1592 // side-effect of transferring focus to a different window and we want to
1593 // ensure that the following keys are sent to the new window.
1594 //
1595 // Suppose the user touches a button in a window then immediately presses "A".
1596 // If the button causes a pop-up window to appear then we want to ensure that
1597 // the "A" key is delivered to the new pop-up window. This is because users
1598 // often anticipate pending UI changes when typing on a keyboard.
1599 // To obtain this behavior, we must serialize key events with respect to all
1600 // prior input events.
1601 if (entry.type == EventEntry::Type::KEY) {
1602 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1603 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001604 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 }
1607
1608 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001609 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1611 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612
1613 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001614 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615}
1616
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001617/**
1618 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1619 * that are currently unresponsive.
1620 */
1621std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1622 const std::vector<TouchedMonitor>& monitors) const {
1623 std::vector<TouchedMonitor> responsiveMonitors;
1624 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1625 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1626 sp<Connection> connection = getConnectionLocked(
1627 monitor.monitor.inputChannel->getConnectionToken());
1628 if (connection == nullptr) {
1629 ALOGE("Could not find connection for monitor %s",
1630 monitor.monitor.inputChannel->getName().c_str());
1631 return false;
1632 }
1633 if (!connection->responsive) {
1634 ALOGW("Unresponsive monitor %s will not get the new gesture",
1635 connection->inputChannel->getName().c_str());
1636 return false;
1637 }
1638 return true;
1639 });
1640 return responsiveMonitors;
1641}
1642
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001643InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1644 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1645 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001646 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 enum InjectionPermission {
1648 INJECTION_PERMISSION_UNKNOWN,
1649 INJECTION_PERMISSION_GRANTED,
1650 INJECTION_PERMISSION_DENIED
1651 };
1652
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 // For security reasons, we defer updating the touch state until we are sure that
1654 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001655 int32_t displayId = entry.displayId;
1656 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1658
1659 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001660 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001662 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1663 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001665 // Copy current touch state into tempTouchState.
1666 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1667 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001668 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001669 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001670 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1671 mTouchStatesByDisplay.find(displayId);
1672 if (oldStateIt != mTouchStatesByDisplay.end()) {
1673 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001674 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001675 }
1676
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001677 bool isSplit = tempTouchState.split;
1678 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1679 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1680 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001681 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1682 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1683 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1684 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1685 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001686 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 bool wrongDevice = false;
1688 if (newGesture) {
1689 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001690 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001691 ALOGI("Dropping event because a pointer for a different device is already down "
1692 "in display %" PRId32,
1693 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001694 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001695 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 switchedDevice = false;
1697 wrongDevice = true;
1698 goto Failed;
1699 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001700 tempTouchState.reset();
1701 tempTouchState.down = down;
1702 tempTouchState.deviceId = entry.deviceId;
1703 tempTouchState.source = entry.source;
1704 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001706 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001707 ALOGI("Dropping move event because a pointer for a different device is already active "
1708 "in display %" PRId32,
1709 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001710 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001711 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001712 switchedDevice = false;
1713 wrongDevice = true;
1714 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
1716
1717 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1718 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1719
Garfield Tan00f511d2019-06-12 16:55:40 -07001720 int32_t x;
1721 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001723 // Always dispatch mouse events to cursor position.
1724 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001725 x = int32_t(entry.xCursorPosition);
1726 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001727 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001728 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1729 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001730 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001731 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001732 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001733 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1734 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001735
1736 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001737 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001738 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 if (newTouchedWindowHandle != nullptr &&
1742 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001743 // New window supports splitting, but we should never split mouse events.
1744 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 } else if (isSplit) {
1746 // New window does not support splitting but we have already split events.
1747 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001748 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 }
1750
1751 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001752 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001754 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001755 }
1756
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1758 ALOGI("Not sending touch event to %s because it is paused",
1759 newTouchedWindowHandle->getName().c_str());
1760 newTouchedWindowHandle = nullptr;
1761 }
1762
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001763 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001764 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001765 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1766 if (!isResponsive) {
1767 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001768 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1769 newTouchedWindowHandle = nullptr;
1770 }
1771 }
1772
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001773 // Drop events that can't be trusted due to occlusion
1774 if (newTouchedWindowHandle != nullptr &&
1775 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1776 TouchOcclusionInfo occlusionInfo =
1777 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001778 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001779 if (DEBUG_TOUCH_OCCLUSION) {
1780 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1781 for (const auto& log : occlusionInfo.debugInfo) {
1782 ALOGD("%s", log.c_str());
1783 }
1784 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001785 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1786 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1787 ALOGW("Dropping untrusted touch event due to %s/%d",
1788 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1789 newTouchedWindowHandle = nullptr;
1790 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001791 }
1792 }
1793
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001794 // Also don't send the new touch event to unresponsive gesture monitors
1795 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1796
Michael Wright3dd60e22019-03-27 22:06:44 +00001797 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1798 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001799 "(%d, %d) in display %" PRId32 ".",
1800 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001801 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001802 goto Failed;
1803 }
1804
1805 if (newTouchedWindowHandle != nullptr) {
1806 // Set target flags.
1807 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1808 if (isSplit) {
1809 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001811 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1812 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1813 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1814 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1815 }
1816
1817 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001818 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1819 newHoverWindowHandle = nullptr;
1820 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001821 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001822 }
1823
1824 // Update the temporary touch state.
1825 BitSet32 pointerIds;
1826 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001828 pointerIds.markBit(pointerId);
1829 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001830 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
1832
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001833 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 } else {
1835 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1836
1837 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001838 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001839 if (DEBUG_FOCUS) {
1840 ALOGD("Dropping event because the pointer is not down or we previously "
1841 "dropped the pointer down event in display %" PRId32,
1842 displayId);
1843 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 goto Failed;
1846 }
1847
1848 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001849 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001850 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1852 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
1854 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001855 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001856 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001857 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1858 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001859 if (DEBUG_FOCUS) {
1860 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1861 oldTouchedWindowHandle->getName().c_str(),
1862 newTouchedWindowHandle->getName().c_str(), displayId);
1863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001865 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1866 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1867 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868
1869 // Make a slippery entrance into the new window.
1870 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1871 isSplit = true;
1872 }
1873
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001874 int32_t targetFlags =
1875 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 if (isSplit) {
1877 targetFlags |= InputTarget::FLAG_SPLIT;
1878 }
1879 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1880 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1881 }
1882
1883 BitSet32 pointerIds;
1884 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001885 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001887 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
1889 }
1890 }
1891
1892 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001893 // Let the previous window know that the hover sequence is over, unless we already did it
1894 // when dispatching it as is to newTouchedWindowHandle.
1895 if (mLastHoverWindowHandle != nullptr &&
1896 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1897 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898#if DEBUG_HOVER
1899 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001900 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001902 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1903 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905
Garfield Tandf26e862020-07-01 20:18:19 -07001906 // Let the new window know that the hover sequence is starting, unless we already did it
1907 // when dispatching it as is to newTouchedWindowHandle.
1908 if (newHoverWindowHandle != nullptr &&
1909 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1910 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911#if DEBUG_HOVER
1912 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001913 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001915 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1916 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1917 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 }
1919 }
1920
1921 // Check permission to inject into all touched foreground windows and ensure there
1922 // is at least one touched foreground window.
1923 {
1924 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001925 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1927 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001928 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 injectionPermission = INJECTION_PERMISSION_DENIED;
1931 goto Failed;
1932 }
1933 }
1934 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001935 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001936 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001937 ALOGI("Dropping event because there is no touched foreground window in display "
1938 "%" PRId32 " or gesture monitor to receive it.",
1939 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001940 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 goto Failed;
1942 }
1943
1944 // Permission granted to injection into all touched foreground windows.
1945 injectionPermission = INJECTION_PERMISSION_GRANTED;
1946 }
1947
1948 // Check whether windows listening for outside touches are owned by the same UID. If it is
1949 // set the policy flag that we will not reveal coordinate information to this window.
1950 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1951 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001952 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001953 if (foregroundWindowHandle) {
1954 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001955 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001956 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1957 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1958 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001959 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1960 InputTarget::FLAG_ZERO_COORDS,
1961 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 }
1964 }
1965 }
1966 }
1967
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 // If this is the first pointer going down and the touched window has a wallpaper
1969 // then also add the touched wallpaper windows so they are locked in for the duration
1970 // of the touch gesture.
1971 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1972 // engine only supports touch events. We would need to add a mechanism similar
1973 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1974 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1975 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001976 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001977 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001978 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001979 getWindowHandlesLocked(displayId);
1980 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001982 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001983 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001984 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001985 .addOrUpdateWindow(windowHandle,
1986 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1987 InputTarget::
1988 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1989 InputTarget::FLAG_DISPATCH_AS_IS,
1990 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
1992 }
1993 }
1994 }
1995
1996 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001997 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002001 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 }
2003
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002004 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002005 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002006 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002007 }
2008
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 // Drop the outside or hover touch windows since we will not care about them
2010 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002011 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012
2013Failed:
2014 // Check injection permission once and for all.
2015 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002016 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 injectionPermission = INJECTION_PERMISSION_GRANTED;
2018 } else {
2019 injectionPermission = INJECTION_PERMISSION_DENIED;
2020 }
2021 }
2022
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002023 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2024 return injectionResult;
2025 }
2026
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002028 if (!wrongDevice) {
2029 if (switchedDevice) {
2030 if (DEBUG_FOCUS) {
2031 ALOGD("Conflicting pointer actions: Switched to a different device.");
2032 }
2033 *outConflictingPointerActions = true;
2034 }
2035
2036 if (isHoverAction) {
2037 // Started hovering, therefore no longer down.
2038 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002039 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002040 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2041 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 *outConflictingPointerActions = true;
2044 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002045 tempTouchState.reset();
2046 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2047 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2048 tempTouchState.deviceId = entry.deviceId;
2049 tempTouchState.source = entry.source;
2050 tempTouchState.displayId = displayId;
2051 }
2052 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2053 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2054 // All pointers up or canceled.
2055 tempTouchState.reset();
2056 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2057 // First pointer went down.
2058 if (oldState && oldState->down) {
2059 if (DEBUG_FOCUS) {
2060 ALOGD("Conflicting pointer actions: Down received while already down.");
2061 }
2062 *outConflictingPointerActions = true;
2063 }
2064 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2065 // One pointer went up.
2066 if (isSplit) {
2067 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2068 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002070 for (size_t i = 0; i < tempTouchState.windows.size();) {
2071 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2072 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2073 touchedWindow.pointerIds.clearBit(pointerId);
2074 if (touchedWindow.pointerIds.isEmpty()) {
2075 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2076 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002079 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002081 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002082 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002083
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002084 // Save changes unless the action was scroll in which case the temporary touch
2085 // state was only valid for this one action.
2086 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2087 if (tempTouchState.displayId >= 0) {
2088 mTouchStatesByDisplay[displayId] = tempTouchState;
2089 } else {
2090 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002094 // Update hover state.
2095 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
2097
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 return injectionResult;
2099}
2100
2101void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002102 int32_t targetFlags, BitSet32 pointerIds,
2103 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002104 std::vector<InputTarget>::iterator it =
2105 std::find_if(inputTargets.begin(), inputTargets.end(),
2106 [&windowHandle](const InputTarget& inputTarget) {
2107 return inputTarget.inputChannel->getConnectionToken() ==
2108 windowHandle->getToken();
2109 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002110
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002111 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002112
2113 if (it == inputTargets.end()) {
2114 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002115 std::shared_ptr<InputChannel> inputChannel =
2116 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002117 if (inputChannel == nullptr) {
2118 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2119 return;
2120 }
2121 inputTarget.inputChannel = inputChannel;
2122 inputTarget.flags = targetFlags;
2123 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2124 inputTargets.push_back(inputTarget);
2125 it = inputTargets.end() - 1;
2126 }
2127
2128 ALOG_ASSERT(it->flags == targetFlags);
2129 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2130
chaviw1ff3d1e2020-07-01 15:53:47 -07002131 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132}
2133
Michael Wright3dd60e22019-03-27 22:06:44 +00002134void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002135 int32_t displayId, float xOffset,
2136 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002137 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2138 mGlobalMonitorsByDisplay.find(displayId);
2139
2140 if (it != mGlobalMonitorsByDisplay.end()) {
2141 const std::vector<Monitor>& monitors = it->second;
2142 for (const Monitor& monitor : monitors) {
2143 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 }
2146}
2147
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002148void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2149 float yOffset,
2150 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002151 InputTarget target;
2152 target.inputChannel = monitor.inputChannel;
2153 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002154 ui::Transform t;
2155 t.set(xOffset, yOffset);
2156 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002157 inputTargets.push_back(target);
2158}
2159
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002161 const InjectionState* injectionState) {
2162 if (injectionState &&
2163 (windowHandle == nullptr ||
2164 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2165 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002166 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002168 "owned by uid %d",
2169 injectionState->injectorPid, injectionState->injectorUid,
2170 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 } else {
2172 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002173 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 }
2175 return false;
2176 }
2177 return true;
2178}
2179
Robert Carrc9bf1d32020-04-13 17:21:08 -07002180/**
2181 * Indicate whether one window handle should be considered as obscuring
2182 * another window handle. We only check a few preconditions. Actually
2183 * checking the bounds is left to the caller.
2184 */
2185static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2186 const sp<InputWindowHandle>& otherHandle) {
2187 // Compare by token so cloned layers aren't counted
2188 if (haveSameToken(windowHandle, otherHandle)) {
2189 return false;
2190 }
2191 auto info = windowHandle->getInfo();
2192 auto otherInfo = otherHandle->getInfo();
2193 if (!otherInfo->visible) {
2194 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002195 } else if (info->ownerUid == otherInfo->ownerUid) {
2196 // If ownerUid is the same we don't generate occlusion events as there
2197 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002198 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002199 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002200 return false;
2201 } else if (otherInfo->displayId != info->displayId) {
2202 return false;
2203 }
2204 return true;
2205}
2206
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002207/**
2208 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2209 * untrusted, one should check:
2210 *
2211 * 1. If result.hasBlockingOcclusion is true.
2212 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2213 * BLOCK_UNTRUSTED.
2214 *
2215 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2216 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2217 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2218 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2219 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2220 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2221 *
2222 * If neither of those is true, then it means the touch can be allowed.
2223 */
2224InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2225 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002226 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2227 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002228 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2229 TouchOcclusionInfo info;
2230 info.hasBlockingOcclusion = false;
2231 info.obscuringOpacity = 0;
2232 info.obscuringUid = -1;
2233 std::map<int32_t, float> opacityByUid;
2234 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2235 if (windowHandle == otherHandle) {
2236 break; // All future windows are below us. Exit early.
2237 }
2238 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2239 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002240 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2241 if (DEBUG_TOUCH_OCCLUSION) {
2242 info.debugInfo.push_back(
2243 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2244 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002245 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2246 // we perform the checks below to see if the touch can be propagated or not based on the
2247 // window's touch occlusion mode
2248 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2249 info.hasBlockingOcclusion = true;
2250 info.obscuringUid = otherInfo->ownerUid;
2251 info.obscuringPackage = otherInfo->packageName;
2252 break;
2253 }
2254 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2255 uint32_t uid = otherInfo->ownerUid;
2256 float opacity =
2257 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2258 // Given windows A and B:
2259 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2260 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2261 opacityByUid[uid] = opacity;
2262 if (opacity > info.obscuringOpacity) {
2263 info.obscuringOpacity = opacity;
2264 info.obscuringUid = uid;
2265 info.obscuringPackage = otherInfo->packageName;
2266 }
2267 }
2268 }
2269 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002270 if (DEBUG_TOUCH_OCCLUSION) {
2271 info.debugInfo.push_back(
2272 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2273 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002274 return info;
2275}
2276
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002277std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2278 bool isTouchedWindow) const {
2279 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", mode=%s, alpha=%.2f, "
2280 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2281 "], window=%s, applicationInfo=%s, flags=%s\n",
2282 (isTouchedWindow) ? "[TOUCHED] " : "",
2283 NamedEnum::string(info->type).c_str(), info->packageName.c_str(),
2284 info->ownerUid, toString(info->touchOcclusionMode).c_str(), info->alpha,
2285 info->frameLeft, info->frameTop, info->frameRight, info->frameBottom,
2286 info->name.c_str(), info->applicationInfo.name.c_str(),
2287 info->flags.string().c_str());
2288}
2289
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002290bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2291 if (occlusionInfo.hasBlockingOcclusion) {
2292 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2293 occlusionInfo.obscuringUid);
2294 return false;
2295 }
2296 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2297 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2298 "%.2f, maximum allowed = %.2f)",
2299 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2300 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2301 return false;
2302 }
2303 return true;
2304}
2305
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2307 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002309 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002310 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002311 if (windowHandle == otherHandle) {
2312 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002315 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002316 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 return true;
2318 }
2319 }
2320 return false;
2321}
2322
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002323bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2324 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002325 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002326 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002327 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002328 if (windowHandle == otherHandle) {
2329 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002330 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002331 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002332 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002333 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002334 return true;
2335 }
2336 }
2337 return false;
2338}
2339
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002340std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002341 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002343 if (applicationHandle != nullptr) {
2344 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002345 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 } else {
2347 return applicationHandle->getName();
2348 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002349 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002350 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002352 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 }
2354}
2355
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002356void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002357 if (eventEntry.type == EventEntry::Type::FOCUS) {
2358 // Focus events are passed to apps, but do not represent user activity.
2359 return;
2360 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002361 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002362 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002363 if (focusedWindowHandle != nullptr) {
2364 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002365 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002367 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#endif
2369 return;
2370 }
2371 }
2372
2373 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002374 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002375 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002376 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2377 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002378 return;
2379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002381 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002382 eventType = USER_ACTIVITY_EVENT_TOUCH;
2383 }
2384 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002386 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002387 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2388 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002389 return;
2390 }
2391 eventType = USER_ACTIVITY_EVENT_BUTTON;
2392 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002394 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002395 case EventEntry::Type::CONFIGURATION_CHANGED:
2396 case EventEntry::Type::DEVICE_RESET: {
2397 LOG_ALWAYS_FATAL("%s events are not user activity",
2398 EventEntry::typeToString(eventEntry.type));
2399 break;
2400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 }
2402
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002403 std::unique_ptr<CommandEntry> commandEntry =
2404 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002405 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002407 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408}
2409
2410void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002411 const sp<Connection>& connection,
2412 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002413 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002414 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002416 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002417 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002418 ATRACE_NAME(message.c_str());
2419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420#if DEBUG_DISPATCH_CYCLE
2421 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002422 "globalScaleFactor=%f, pointerIds=0x%x %s",
2423 connection->getInputChannelName().c_str(), inputTarget.flags,
2424 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2425 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426#endif
2427
2428 // Skip this event if the connection status is not normal.
2429 // We don't want to enqueue additional outbound events if the connection is broken.
2430 if (connection->status != Connection::STATUS_NORMAL) {
2431#if DEBUG_DISPATCH_CYCLE
2432 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002433 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434#endif
2435 return;
2436 }
2437
2438 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002439 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2440 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2441 "Entry type %s should not have FLAG_SPLIT",
2442 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002444 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002445 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002446 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002447 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 if (!splitMotionEntry) {
2449 return; // split event was dropped
2450 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002451 if (DEBUG_FOCUS) {
2452 ALOGD("channel '%s' ~ Split motion event.",
2453 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002454 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002455 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 splitMotionEntry->release();
2458 return;
2459 }
2460 }
2461
2462 // Not splitting. Enqueue dispatch entries for the event as is.
2463 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2464}
2465
2466void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 const sp<Connection>& connection,
2468 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002469 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002470 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002471 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002472 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002473 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002474 ATRACE_NAME(message.c_str());
2475 }
2476
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002477 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478
2479 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002480 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002481 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002482 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002484 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002486 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002488 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002490 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492
2493 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002494 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 startDispatchCycleLocked(currentTime, connection);
2496 }
2497}
2498
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2500 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002501 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002503 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2505 connection->getInputChannelName().c_str(),
2506 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002507 ATRACE_NAME(message.c_str());
2508 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002509 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 if (!(inputTargetFlags & dispatchMode)) {
2511 return;
2512 }
2513 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2514
2515 // This is a new event.
2516 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002517 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002518 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002520 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2521 // different EventEntry than what was passed in.
2522 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002524 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002525 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002526 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002527 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002528 dispatchEntry->resolvedAction = keyEntry.action;
2529 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2532 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2535 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002537 return; // skip the inconsistent event
2538 }
2539 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002542 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002543 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002544 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2545 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2546 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2547 static_cast<int32_t>(IdGenerator::Source::OTHER);
2548 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002549 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2550 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2551 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2552 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2553 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2554 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2555 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2556 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2557 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2558 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2559 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002560 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002561 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002562 }
2563 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002564 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2565 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2568 "event",
2569 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002574 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2576 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2577 }
2578 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2579 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002582 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2583 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2586 "event",
2587 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 return; // skip the inconsistent event
2590 }
2591
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002592 dispatchEntry->resolvedEventId =
2593 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2594 ? mIdGenerator.nextId()
2595 : motionEntry.id;
2596 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2597 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2598 ") to MotionEvent(id=0x%" PRIx32 ").",
2599 motionEntry.id, dispatchEntry->resolvedEventId);
2600 ATRACE_NAME(message.c_str());
2601 }
2602
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002603 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002604 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002605
2606 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002608 case EventEntry::Type::FOCUS: {
2609 break;
2610 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002611 case EventEntry::Type::CONFIGURATION_CHANGED:
2612 case EventEntry::Type::DEVICE_RESET: {
2613 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002614 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002615 break;
2616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 }
2618
2619 // Remember that we are waiting for this dispatch to complete.
2620 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002621 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 }
2623
2624 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002625 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002626 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002627}
2628
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002629/**
2630 * This function is purely for debugging. It helps us understand where the user interaction
2631 * was taking place. For example, if user is touching launcher, we will see a log that user
2632 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2633 * We will see both launcher and wallpaper in that list.
2634 * Once the interaction with a particular set of connections starts, no new logs will be printed
2635 * until the set of interacted connections changes.
2636 *
2637 * The following items are skipped, to reduce the logspam:
2638 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2639 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2640 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2641 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2642 * Both of those ACTION_UP events would not be logged
2643 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2644 * will not be logged. This is omitted to reduce the amount of data printed.
2645 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2646 * gesture monitor is the only connection receiving the remainder of the gesture.
2647 */
2648void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2649 const std::vector<InputTarget>& targets) {
2650 // Skip ACTION_UP events, and all events other than keys and motions
2651 if (entry.type == EventEntry::Type::KEY) {
2652 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2653 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2654 return;
2655 }
2656 } else if (entry.type == EventEntry::Type::MOTION) {
2657 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2658 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2659 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2660 return;
2661 }
2662 } else {
2663 return; // Not a key or a motion
2664 }
2665
2666 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2667 std::vector<sp<Connection>> newConnections;
2668 for (const InputTarget& target : targets) {
2669 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2670 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2671 continue; // Skip windows that receive ACTION_OUTSIDE
2672 }
2673
2674 sp<IBinder> token = target.inputChannel->getConnectionToken();
2675 sp<Connection> connection = getConnectionLocked(token);
2676 if (connection == nullptr || connection->monitor) {
2677 continue; // We only need to keep track of the non-monitor connections.
2678 }
2679 newConnectionTokens.insert(std::move(token));
2680 newConnections.emplace_back(connection);
2681 }
2682 if (newConnectionTokens == mInteractionConnectionTokens) {
2683 return; // no change
2684 }
2685 mInteractionConnectionTokens = newConnectionTokens;
2686
2687 std::string windowList;
2688 for (const sp<Connection>& connection : newConnections) {
2689 windowList += connection->getWindowName() + ", ";
2690 }
2691 std::string message = "Interaction with windows: " + windowList;
2692 if (windowList.empty()) {
2693 message += "<none>";
2694 }
2695 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2696}
2697
chaviwfd6d3512019-03-25 13:23:49 -07002698void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002699 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002700 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002701 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2702 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002703 return;
2704 }
2705
Vishnu Nairad321cd2020-08-20 16:40:21 -07002706 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2707 if (focusedToken == token) {
2708 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002709 return;
2710 }
2711
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002712 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2713 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002714 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002715 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716}
2717
2718void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002720 if (ATRACE_ENABLED()) {
2721 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002723 ATRACE_NAME(message.c_str());
2724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#endif
2728
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002729 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2730 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002732 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002733 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002734 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735
2736 // Publish the event.
2737 status_t status;
2738 EventEntry* eventEntry = dispatchEntry->eventEntry;
2739 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002740 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002741 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2742 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002744 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002745 status =
2746 connection->inputPublisher
2747 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2748 keyEntry->deviceId, keyEntry->source,
2749 keyEntry->displayId, std::move(hmac),
2750 dispatchEntry->resolvedAction,
2751 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2752 keyEntry->scanCode, keyEntry->metaState,
2753 keyEntry->repeatCount, keyEntry->downTime,
2754 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002755 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 }
2757
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002758 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761 PointerCoords scaledCoords[MAX_POINTERS];
2762 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2763
chaviw82357092020-01-28 13:13:06 -08002764 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2766 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2767 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002768 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2770 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002771 // Don't apply window scale here since we don't want scale to affect raw
2772 // coordinates. The scale will be sent back to the client and applied
2773 // later when requesting relative coordinates.
2774 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2775 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002776 }
2777 usingCoords = scaledCoords;
2778 }
2779 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 // We don't want the dispatch target to know.
2781 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2782 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2783 scaledCoords[i].clear();
2784 }
2785 usingCoords = scaledCoords;
2786 }
2787 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002788
2789 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790
2791 // Publish the motion event.
2792 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002793 .publishMotionEvent(dispatchEntry->seq,
2794 dispatchEntry->resolvedEventId,
2795 motionEntry->deviceId, motionEntry->source,
2796 motionEntry->displayId, std::move(hmac),
2797 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002798 motionEntry->actionButton,
2799 dispatchEntry->resolvedFlags,
2800 motionEntry->edgeFlags, motionEntry->metaState,
2801 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002802 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002803 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002804 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 motionEntry->yPrecision,
2806 motionEntry->xCursorPosition,
2807 motionEntry->yCursorPosition,
2808 motionEntry->downTime, motionEntry->eventTime,
2809 motionEntry->pointerCount,
2810 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002811 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 break;
2813 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002814 case EventEntry::Type::FOCUS: {
2815 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2816 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002817 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002818 focusEntry->hasFocus,
2819 mInTouchMode);
2820 break;
2821 }
2822
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002823 case EventEntry::Type::CONFIGURATION_CHANGED:
2824 case EventEntry::Type::DEVICE_RESET: {
2825 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2826 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002827 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
2830
2831 // Check the result.
2832 if (status) {
2833 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002834 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 "This is unexpected because the wait queue is empty, so the pipe "
2837 "should be empty and we shouldn't have any problems writing an "
2838 "event to it, status=%d",
2839 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2841 } else {
2842 // Pipe is full and we are waiting for the app to finish process some events
2843 // before sending more events to it.
2844#if DEBUG_DISPATCH_CYCLE
2845 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 "waiting for the application to catch up",
2847 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 }
2850 } else {
2851 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002852 "status=%d",
2853 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2855 }
2856 return;
2857 }
2858
2859 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002860 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2861 connection->outboundQueue.end(),
2862 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002863 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002864 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002865 if (connection->responsive) {
2866 mAnrTracker.insert(dispatchEntry->timeoutTime,
2867 connection->inputChannel->getConnectionToken());
2868 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002869 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
2871}
2872
chaviw09c8d2d2020-08-24 15:48:26 -07002873std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2874 size_t size;
2875 switch (event.type) {
2876 case VerifiedInputEvent::Type::KEY: {
2877 size = sizeof(VerifiedKeyEvent);
2878 break;
2879 }
2880 case VerifiedInputEvent::Type::MOTION: {
2881 size = sizeof(VerifiedMotionEvent);
2882 break;
2883 }
2884 }
2885 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2886 return mHmacKeyManager.sign(start, size);
2887}
2888
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002889const std::array<uint8_t, 32> InputDispatcher::getSignature(
2890 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2891 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2892 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2893 // Only sign events up and down events as the purely move events
2894 // are tied to their up/down counterparts so signing would be redundant.
2895 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2896 verifiedEvent.actionMasked = actionMasked;
2897 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002898 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002899 }
2900 return INVALID_HMAC;
2901}
2902
2903const std::array<uint8_t, 32> InputDispatcher::getSignature(
2904 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2905 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2906 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2907 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002908 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002909}
2910
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 const sp<Connection>& connection, uint32_t seq,
2913 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914#if DEBUG_DISPATCH_CYCLE
2915 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917#endif
2918
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 if (connection->status == Connection::STATUS_BROKEN ||
2920 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 return;
2922 }
2923
2924 // Notify other system components and prepare to start the next dispatch cycle.
2925 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2926}
2927
2928void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 const sp<Connection>& connection,
2930 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931#if DEBUG_DISPATCH_CYCLE
2932 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934#endif
2935
2936 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002937 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002938 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002939 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002940 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941
2942 // The connection appears to be unrecoverably broken.
2943 // Ignore already broken or zombie connections.
2944 if (connection->status == Connection::STATUS_NORMAL) {
2945 connection->status = Connection::STATUS_BROKEN;
2946
2947 if (notify) {
2948 // Notify other system components.
2949 onDispatchCycleBrokenLocked(currentTime, connection);
2950 }
2951 }
2952}
2953
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002954void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2955 while (!queue.empty()) {
2956 DispatchEntry* dispatchEntry = queue.front();
2957 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002958 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 }
2960}
2961
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002962void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002964 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 }
2966 delete dispatchEntry;
2967}
2968
2969int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2970 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2971
2972 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002973 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002975 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 "fd=%d, events=0x%x",
2978 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 return 0; // remove the callback
2980 }
2981
2982 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002983 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2985 if (!(events & ALOOPER_EVENT_INPUT)) {
2986 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 "events=0x%x",
2988 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989 return 1;
2990 }
2991
2992 nsecs_t currentTime = now();
2993 bool gotOne = false;
2994 status_t status;
2995 for (;;) {
2996 uint32_t seq;
2997 bool handled;
2998 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2999 if (status) {
3000 break;
3001 }
3002 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3003 gotOne = true;
3004 }
3005 if (gotOne) {
3006 d->runCommandsLockedInterruptible();
3007 if (status == WOULD_BLOCK) {
3008 return 1;
3009 }
3010 }
3011
3012 notify = status != DEAD_OBJECT || !connection->monitor;
3013 if (notify) {
3014 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016 }
3017 } else {
3018 // Monitor channels are never explicitly unregistered.
3019 // We do it automatically when the remote endpoint is closed so don't warn
3020 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003021 const bool stillHaveWindowHandle =
3022 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3023 nullptr;
3024 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 if (notify) {
3026 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003027 "events=0x%x",
3028 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 }
3030 }
3031
Garfield Tan15601662020-09-22 15:32:38 -07003032 // Remove the channel.
3033 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036}
3037
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003040 for (const auto& pair : mConnectionsByFd) {
3041 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 }
3043}
3044
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003046 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003047 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3048 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3049}
3050
3051void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3052 const CancelationOptions& options,
3053 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3054 for (const auto& it : monitorsByDisplay) {
3055 const std::vector<Monitor>& monitors = it.second;
3056 for (const Monitor& monitor : monitors) {
3057 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003058 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003059 }
3060}
3061
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003063 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003064 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003065 if (connection == nullptr) {
3066 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003068
3069 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070}
3071
3072void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3073 const sp<Connection>& connection, const CancelationOptions& options) {
3074 if (connection->status == Connection::STATUS_BROKEN) {
3075 return;
3076 }
3077
3078 nsecs_t currentTime = now();
3079
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003080 std::vector<EventEntry*> cancelationEvents =
3081 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003083 if (cancelationEvents.empty()) {
3084 return;
3085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003087 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3088 "with reality: %s, mode=%d.",
3089 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3090 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003092
3093 InputTarget target;
3094 sp<InputWindowHandle> windowHandle =
3095 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3096 if (windowHandle != nullptr) {
3097 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003098 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003099 target.globalScaleFactor = windowInfo->globalScaleFactor;
3100 }
3101 target.inputChannel = connection->inputChannel;
3102 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3103
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003104 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3105 EventEntry* cancelationEventEntry = cancelationEvents[i];
3106 switch (cancelationEventEntry->type) {
3107 case EventEntry::Type::KEY: {
3108 logOutboundKeyDetails("cancel - ",
3109 static_cast<const KeyEntry&>(*cancelationEventEntry));
3110 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003112 case EventEntry::Type::MOTION: {
3113 logOutboundMotionDetails("cancel - ",
3114 static_cast<const MotionEntry&>(*cancelationEventEntry));
3115 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003117 case EventEntry::Type::FOCUS: {
3118 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3119 break;
3120 }
3121 case EventEntry::Type::CONFIGURATION_CHANGED:
3122 case EventEntry::Type::DEVICE_RESET: {
3123 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3124 EventEntry::typeToString(cancelationEventEntry->type));
3125 break;
3126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 }
3128
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003129 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
3130 target, InputTarget::FLAG_DISPATCH_AS_IS);
3131
3132 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003134
3135 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136}
3137
Svet Ganov5d3bc372020-01-26 23:11:07 -08003138void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3139 const sp<Connection>& connection) {
3140 if (connection->status == Connection::STATUS_BROKEN) {
3141 return;
3142 }
3143
3144 nsecs_t currentTime = now();
3145
3146 std::vector<EventEntry*> downEvents =
3147 connection->inputState.synthesizePointerDownEvents(currentTime);
3148
3149 if (downEvents.empty()) {
3150 return;
3151 }
3152
3153#if DEBUG_OUTBOUND_EVENT_DETAILS
3154 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3155 connection->getInputChannelName().c_str(), downEvents.size());
3156#endif
3157
3158 InputTarget target;
3159 sp<InputWindowHandle> windowHandle =
3160 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3161 if (windowHandle != nullptr) {
3162 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003163 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003164 target.globalScaleFactor = windowInfo->globalScaleFactor;
3165 }
3166 target.inputChannel = connection->inputChannel;
3167 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3168
3169 for (EventEntry* downEventEntry : downEvents) {
3170 switch (downEventEntry->type) {
3171 case EventEntry::Type::MOTION: {
3172 logOutboundMotionDetails("down - ",
3173 static_cast<const MotionEntry&>(*downEventEntry));
3174 break;
3175 }
3176
3177 case EventEntry::Type::KEY:
3178 case EventEntry::Type::FOCUS:
3179 case EventEntry::Type::CONFIGURATION_CHANGED:
3180 case EventEntry::Type::DEVICE_RESET: {
3181 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3182 EventEntry::typeToString(downEventEntry->type));
3183 break;
3184 }
3185 }
3186
3187 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3188 target, InputTarget::FLAG_DISPATCH_AS_IS);
3189
3190 downEventEntry->release();
3191 }
3192
3193 startDispatchCycleLocked(currentTime, connection);
3194}
3195
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003196MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003197 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 ALOG_ASSERT(pointerIds.value != 0);
3199
3200 uint32_t splitPointerIndexMap[MAX_POINTERS];
3201 PointerProperties splitPointerProperties[MAX_POINTERS];
3202 PointerCoords splitPointerCoords[MAX_POINTERS];
3203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 uint32_t splitPointerCount = 0;
3206
3207 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003210 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 uint32_t pointerId = uint32_t(pointerProperties.id);
3212 if (pointerIds.hasBit(pointerId)) {
3213 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3214 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3215 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003216 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 splitPointerCount += 1;
3218 }
3219 }
3220
3221 if (splitPointerCount != pointerIds.count()) {
3222 // This is bad. We are missing some of the pointers that we expected to deliver.
3223 // Most likely this indicates that we received an ACTION_MOVE events that has
3224 // different pointer ids than we expected based on the previous ACTION_DOWN
3225 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3226 // in this way.
3227 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 "we expected there to be %d pointers. This probably means we received "
3229 "a broken sequence of pointer ids from the input device.",
3230 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003231 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 }
3233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003234 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3237 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3239 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003240 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 uint32_t pointerId = uint32_t(pointerProperties.id);
3242 if (pointerIds.hasBit(pointerId)) {
3243 if (pointerIds.count() == 1) {
3244 // The first/last pointer went down/up.
3245 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246 ? AMOTION_EVENT_ACTION_DOWN
3247 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 } else {
3249 // A secondary pointer went down/up.
3250 uint32_t splitPointerIndex = 0;
3251 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3252 splitPointerIndex += 1;
3253 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 action = maskedAction |
3255 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 }
3257 } else {
3258 // An unrelated pointer changed.
3259 action = AMOTION_EVENT_ACTION_MOVE;
3260 }
3261 }
3262
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003263 int32_t newId = mIdGenerator.nextId();
3264 if (ATRACE_ENABLED()) {
3265 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3266 ") to MotionEvent(id=0x%" PRIx32 ").",
3267 originalMotionEntry.id, newId);
3268 ATRACE_NAME(message.c_str());
3269 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003270 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003271 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3272 originalMotionEntry.source, originalMotionEntry.displayId,
3273 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003274 originalMotionEntry.actionButton, originalMotionEntry.flags,
3275 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3276 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3277 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3278 originalMotionEntry.xCursorPosition,
3279 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003280 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003282 if (originalMotionEntry.injectionState) {
3283 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 splitMotionEntry->injectionState->refCount += 1;
3285 }
3286
3287 return splitMotionEntry;
3288}
3289
3290void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3291#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003292 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293#endif
3294
3295 bool needWake;
3296 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003297 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Prabir Pradhan42611e02018-11-27 14:04:02 -08003299 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003300 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 needWake = enqueueInboundEventLocked(newEntry);
3302 } // release lock
3303
3304 if (needWake) {
3305 mLooper->wake();
3306 }
3307}
3308
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003309/**
3310 * If one of the meta shortcuts is detected, process them here:
3311 * Meta + Backspace -> generate BACK
3312 * Meta + Enter -> generate HOME
3313 * This will potentially overwrite keyCode and metaState.
3314 */
3315void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003317 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3318 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3319 if (keyCode == AKEYCODE_DEL) {
3320 newKeyCode = AKEYCODE_BACK;
3321 } else if (keyCode == AKEYCODE_ENTER) {
3322 newKeyCode = AKEYCODE_HOME;
3323 }
3324 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003325 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003326 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003327 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003328 keyCode = newKeyCode;
3329 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3330 }
3331 } else if (action == AKEY_EVENT_ACTION_UP) {
3332 // In order to maintain a consistent stream of up and down events, check to see if the key
3333 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3334 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003335 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003336 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003337 auto replacementIt = mReplacedKeys.find(replacement);
3338 if (replacementIt != mReplacedKeys.end()) {
3339 keyCode = replacementIt->second;
3340 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003341 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3342 }
3343 }
3344}
3345
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3347#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3349 "policyFlags=0x%x, action=0x%x, "
3350 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3351 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3352 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3353 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354#endif
3355 if (!validateKeyEvent(args->action)) {
3356 return;
3357 }
3358
3359 uint32_t policyFlags = args->policyFlags;
3360 int32_t flags = args->flags;
3361 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003362 // InputDispatcher tracks and generates key repeats on behalf of
3363 // whatever notifies it, so repeatCount should always be set to 0
3364 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3366 policyFlags |= POLICY_FLAG_VIRTUAL;
3367 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 if (policyFlags & POLICY_FLAG_FUNCTION) {
3370 metaState |= AMETA_FUNCTION_ON;
3371 }
3372
3373 policyFlags |= POLICY_FLAG_TRUSTED;
3374
Michael Wright78f24442014-08-06 15:55:28 -07003375 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003376 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003377
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003379 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003380 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3381 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382
Michael Wright2b3c3302018-03-02 17:19:13 +00003383 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003385 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3386 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 bool needWake;
3391 { // acquire lock
3392 mLock.lock();
3393
3394 if (shouldSendKeyToInputFilterLocked(args)) {
3395 mLock.unlock();
3396
3397 policyFlags |= POLICY_FLAG_FILTERED;
3398 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3399 return; // event was consumed by the filter
3400 }
3401
3402 mLock.lock();
3403 }
3404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003406 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 args->displayId, policyFlags, args->action, flags, keyCode,
3408 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409
3410 needWake = enqueueInboundEventLocked(newEntry);
3411 mLock.unlock();
3412 } // release lock
3413
3414 if (needWake) {
3415 mLooper->wake();
3416 }
3417}
3418
3419bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3420 return mInputFilterEnabled;
3421}
3422
3423void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3424#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003425 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3426 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003427 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3428 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003429 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003430 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3431 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3432 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3433 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 for (uint32_t i = 0; i < args->pointerCount; i++) {
3435 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003436 "x=%f, y=%f, pressure=%f, size=%f, "
3437 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3438 "orientation=%f",
3439 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3440 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3441 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3442 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3443 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3444 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3445 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3446 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3447 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3448 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 }
3450#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3452 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 return;
3454 }
3455
3456 uint32_t policyFlags = args->policyFlags;
3457 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003458
3459 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003460 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003461 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3462 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
3466 bool needWake;
3467 { // acquire lock
3468 mLock.lock();
3469
3470 if (shouldSendMotionToInputFilterLocked(args)) {
3471 mLock.unlock();
3472
3473 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003474 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003475 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3476 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003477 args->metaState, args->buttonState, args->classification, transform,
3478 args->xPrecision, args->yPrecision, args->xCursorPosition,
3479 args->yCursorPosition, args->downTime, args->eventTime,
3480 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481
3482 policyFlags |= POLICY_FLAG_FILTERED;
3483 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3484 return; // event was consumed by the filter
3485 }
3486
3487 mLock.lock();
3488 }
3489
3490 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003491 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003492 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003493 args->displayId, policyFlags, args->action, args->actionButton,
3494 args->flags, args->metaState, args->buttonState,
3495 args->classification, args->edgeFlags, args->xPrecision,
3496 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3497 args->downTime, args->pointerCount, args->pointerProperties,
3498 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
3500 needWake = enqueueInboundEventLocked(newEntry);
3501 mLock.unlock();
3502 } // release lock
3503
3504 if (needWake) {
3505 mLooper->wake();
3506 }
3507}
3508
3509bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003510 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511}
3512
3513void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3514#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003515 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003516 "switchMask=0x%08x",
3517 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518#endif
3519
3520 uint32_t policyFlags = args->policyFlags;
3521 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523}
3524
3525void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3526#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3528 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529#endif
3530
3531 bool needWake;
3532 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003533 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
Prabir Pradhan42611e02018-11-27 14:04:02 -08003535 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003536 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 needWake = enqueueInboundEventLocked(newEntry);
3538 } // release lock
3539
3540 if (needWake) {
3541 mLooper->wake();
3542 }
3543}
3544
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003545InputEventInjectionResult InputDispatcher::injectInputEvent(
3546 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3547 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548#if DEBUG_INBOUND_EVENT_DETAILS
3549 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003550 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3551 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003553 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554
3555 policyFlags |= POLICY_FLAG_INJECTED;
3556 if (hasInjectionPermission(injectorPid, injectorUid)) {
3557 policyFlags |= POLICY_FLAG_TRUSTED;
3558 }
3559
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003560 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003562 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003563 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3564 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003565 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003566 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003569 int32_t flags = incomingKey.getFlags();
3570 int32_t keyCode = incomingKey.getKeyCode();
3571 int32_t metaState = incomingKey.getMetaState();
3572 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003573 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003574 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003575 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003576 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3577 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3578 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003580 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3581 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003582 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003583
3584 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3585 android::base::Timer t;
3586 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3587 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3588 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3589 std::to_string(t.duration().count()).c_str());
3590 }
3591 }
3592
3593 mLock.lock();
3594 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003595 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3596 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003597 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3598 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003599 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600 injectedEntries.push(injectedEntry);
3601 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 }
3603
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003604 case AINPUT_EVENT_TYPE_MOTION: {
3605 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3606 int32_t action = motionEvent->getAction();
3607 size_t pointerCount = motionEvent->getPointerCount();
3608 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3609 int32_t actionButton = motionEvent->getActionButton();
3610 int32_t displayId = motionEvent->getDisplayId();
3611 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003612 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003613 }
3614
3615 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3616 nsecs_t eventTime = motionEvent->getEventTime();
3617 android::base::Timer t;
3618 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3619 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3620 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3621 std::to_string(t.duration().count()).c_str());
3622 }
3623 }
3624
3625 mLock.lock();
3626 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3627 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3628 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003629 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3630 motionEvent->getSource(), motionEvent->getDisplayId(),
3631 policyFlags, action, actionButton, motionEvent->getFlags(),
3632 motionEvent->getMetaState(), motionEvent->getButtonState(),
3633 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3634 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003635 motionEvent->getRawXCursorPosition(),
3636 motionEvent->getRawYCursorPosition(),
3637 motionEvent->getDownTime(), uint32_t(pointerCount),
3638 pointerProperties, samplePointerCoords,
3639 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003640 injectedEntries.push(injectedEntry);
3641 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3642 sampleEventTimes += 1;
3643 samplePointerCoords += pointerCount;
3644 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003645 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003646 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 motionEvent->getDisplayId(), policyFlags, action,
3648 actionButton, motionEvent->getFlags(),
3649 motionEvent->getMetaState(), motionEvent->getButtonState(),
3650 motionEvent->getClassification(),
3651 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3652 motionEvent->getYPrecision(),
3653 motionEvent->getRawXCursorPosition(),
3654 motionEvent->getRawYCursorPosition(),
3655 motionEvent->getDownTime(), uint32_t(pointerCount),
3656 pointerProperties, samplePointerCoords,
3657 motionEvent->getXOffset(), motionEvent->getYOffset());
3658 injectedEntries.push(nextInjectedEntry);
3659 }
3660 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003663 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003664 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003665 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 }
3667
3668 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003669 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 injectionState->injectionIsAsync = true;
3671 }
3672
3673 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003674 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
3676 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003677 while (!injectedEntries.empty()) {
3678 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3679 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 }
3681
3682 mLock.unlock();
3683
3684 if (needWake) {
3685 mLooper->wake();
3686 }
3687
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003688 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003690 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003692 if (syncMode == InputEventInjectionSync::NONE) {
3693 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 } else {
3695 for (;;) {
3696 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003697 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 break;
3699 }
3700
3701 nsecs_t remainingTimeout = endTime - now();
3702 if (remainingTimeout <= 0) {
3703#if DEBUG_INJECTION
3704 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003705 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003707 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 break;
3709 }
3710
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003711 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003714 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3715 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 while (injectionState->pendingForegroundDispatches != 0) {
3717#if DEBUG_INJECTION
3718 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003719 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720#endif
3721 nsecs_t remainingTimeout = endTime - now();
3722 if (remainingTimeout <= 0) {
3723#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3725 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003727 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 break;
3729 }
3730
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003731 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 }
3733 }
3734 }
3735
3736 injectionState->release();
3737 } // release lock
3738
3739#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003740 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742#endif
3743
3744 return injectionResult;
3745}
3746
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003747std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003748 std::array<uint8_t, 32> calculatedHmac;
3749 std::unique_ptr<VerifiedInputEvent> result;
3750 switch (event.getType()) {
3751 case AINPUT_EVENT_TYPE_KEY: {
3752 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3753 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3754 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003755 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003756 break;
3757 }
3758 case AINPUT_EVENT_TYPE_MOTION: {
3759 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3760 VerifiedMotionEvent verifiedMotionEvent =
3761 verifiedMotionEventFromMotionEvent(motionEvent);
3762 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003763 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003764 break;
3765 }
3766 default: {
3767 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3768 return nullptr;
3769 }
3770 }
3771 if (calculatedHmac == INVALID_HMAC) {
3772 return nullptr;
3773 }
3774 if (calculatedHmac != event.getHmac()) {
3775 return nullptr;
3776 }
3777 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003778}
3779
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003781 return injectorUid == 0 ||
3782 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783}
3784
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003785void InputDispatcher::setInjectionResult(EventEntry* entry,
3786 InputEventInjectionResult injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 InjectionState* injectionState = entry->injectionState;
3788 if (injectionState) {
3789#if DEBUG_INJECTION
3790 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003791 "injectorPid=%d, injectorUid=%d",
3792 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793#endif
3794
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003795 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 // Log the outcome since the injector did not wait for the injection result.
3797 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003798 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003799 ALOGV("Asynchronous input event injection succeeded.");
3800 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003801 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003802 ALOGW("Asynchronous input event injection failed.");
3803 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003804 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003805 ALOGW("Asynchronous input event injection permission denied.");
3806 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003807 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003808 ALOGW("Asynchronous input event injection timed out.");
3809 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003810 case InputEventInjectionResult::PENDING:
3811 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3812 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814 }
3815
3816 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003817 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
3819}
3820
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003821void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 InjectionState* injectionState = entry->injectionState;
3823 if (injectionState) {
3824 injectionState->pendingForegroundDispatches += 1;
3825 }
3826}
3827
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003828void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 InjectionState* injectionState = entry->injectionState;
3830 if (injectionState) {
3831 injectionState->pendingForegroundDispatches -= 1;
3832
3833 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003834 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836 }
3837}
3838
Vishnu Nairad321cd2020-08-20 16:40:21 -07003839const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003840 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003841 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3842 auto it = mWindowHandlesByDisplay.find(displayId);
3843 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003844}
3845
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003847 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003848 if (windowHandleToken == nullptr) {
3849 return nullptr;
3850 }
3851
Arthur Hungb92218b2018-08-14 12:00:21 +08003852 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003853 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003854 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003855 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003856 return windowHandle;
3857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
3859 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003860 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861}
3862
Vishnu Nairad321cd2020-08-20 16:40:21 -07003863sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3864 int displayId) const {
3865 if (windowHandleToken == nullptr) {
3866 return nullptr;
3867 }
3868
3869 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3870 if (windowHandle->getToken() == windowHandleToken) {
3871 return windowHandle;
3872 }
3873 }
3874 return nullptr;
3875}
3876
3877sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3878 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3879 return getWindowHandleLocked(focusedToken, displayId);
3880}
3881
Mady Mellor017bcd12020-06-23 19:12:00 +00003882bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3883 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003884 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003885 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003886 if (handle->getId() == windowHandle->getId() &&
3887 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003888 if (windowHandle->getInfo()->displayId != it.first) {
3889 ALOGE("Found window %s in display %" PRId32
3890 ", but it should belong to display %" PRId32,
3891 windowHandle->getName().c_str(), it.first,
3892 windowHandle->getInfo()->displayId);
3893 }
3894 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 }
3897 }
3898 return false;
3899}
3900
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003901bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3902 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3903 const bool noInputChannel =
3904 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3905 if (connection != nullptr && noInputChannel) {
3906 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3907 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3908 return false;
3909 }
3910
3911 if (connection == nullptr) {
3912 if (!noInputChannel) {
3913 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3914 }
3915 return false;
3916 }
3917 if (!connection->responsive) {
3918 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3919 return false;
3920 }
3921 return true;
3922}
3923
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003924std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3925 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003926 size_t count = mInputChannelsByToken.count(token);
3927 if (count == 0) {
3928 return nullptr;
3929 }
3930 return mInputChannelsByToken.at(token);
3931}
3932
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003933void InputDispatcher::updateWindowHandlesForDisplayLocked(
3934 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3935 if (inputWindowHandles.empty()) {
3936 // Remove all handles on a display if there are no windows left.
3937 mWindowHandlesByDisplay.erase(displayId);
3938 return;
3939 }
3940
3941 // Since we compare the pointer of input window handles across window updates, we need
3942 // to make sure the handle object for the same window stays unchanged across updates.
3943 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003944 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003945 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003946 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003947 }
3948
3949 std::vector<sp<InputWindowHandle>> newHandles;
3950 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3951 if (!handle->updateInfo()) {
3952 // handle no longer valid
3953 continue;
3954 }
3955
3956 const InputWindowInfo* info = handle->getInfo();
3957 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3958 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3959 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003960 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3961 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3962 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003963 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003964 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003965 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003966 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003967 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003968 }
3969
3970 if (info->displayId != displayId) {
3971 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3972 handle->getName().c_str(), displayId, info->displayId);
3973 continue;
3974 }
3975
Robert Carredd13602020-04-13 17:24:34 -07003976 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3977 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003978 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003979 oldHandle->updateFrom(handle);
3980 newHandles.push_back(oldHandle);
3981 } else {
3982 newHandles.push_back(handle);
3983 }
3984 }
3985
3986 // Insert or replace
3987 mWindowHandlesByDisplay[displayId] = newHandles;
3988}
3989
Arthur Hung72d8dc32020-03-28 00:48:39 +00003990void InputDispatcher::setInputWindows(
3991 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3992 { // acquire lock
3993 std::scoped_lock _l(mLock);
3994 for (auto const& i : handlesPerDisplay) {
3995 setInputWindowsLocked(i.second, i.first);
3996 }
3997 }
3998 // Wake up poll loop since it may need to make new input dispatching choices.
3999 mLooper->wake();
4000}
4001
Arthur Hungb92218b2018-08-14 12:00:21 +08004002/**
4003 * Called from InputManagerService, update window handle list by displayId that can receive input.
4004 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4005 * If set an empty list, remove all handles from the specific display.
4006 * For focused handle, check if need to change and send a cancel event to previous one.
4007 * For removed handle, check if need to send a cancel event if already in touch.
4008 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004009void InputDispatcher::setInputWindowsLocked(
4010 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004011 if (DEBUG_FOCUS) {
4012 std::string windowList;
4013 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4014 windowList += iwh->getName() + " ";
4015 }
4016 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004019 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4020 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4021 const bool noInputWindow =
4022 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4023 if (noInputWindow && window->getToken() != nullptr) {
4024 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4025 window->getName().c_str());
4026 window->releaseChannel();
4027 }
4028 }
4029
Arthur Hung72d8dc32020-03-28 00:48:39 +00004030 // Copy old handles for release if they are no longer present.
4031 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032
Arthur Hung72d8dc32020-03-28 00:48:39 +00004033 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004034
Vishnu Nair958da932020-08-21 17:12:37 -07004035 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4036 if (mLastHoverWindowHandle &&
4037 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4038 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004039 mLastHoverWindowHandle = nullptr;
4040 }
4041
Vishnu Nair958da932020-08-21 17:12:37 -07004042 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4043 if (focusedToken) {
4044 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4045 if (result != FocusResult::OK) {
4046 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4047 }
4048 }
4049
4050 std::optional<FocusRequest> focusRequest =
4051 getOptionalValueByKey(mPendingFocusRequests, displayId);
4052 if (focusRequest) {
4053 // If the window from the pending request is now visible, provide it focus.
4054 FocusResult result = handleFocusRequestLocked(*focusRequest);
4055 if (result != FocusResult::NOT_VISIBLE) {
4056 // Drop the request if we were able to change the focus or we cannot change
4057 // it for another reason.
4058 mPendingFocusRequests.erase(displayId);
4059 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004062 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4063 mTouchStatesByDisplay.find(displayId);
4064 if (stateIt != mTouchStatesByDisplay.end()) {
4065 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004066 for (size_t i = 0; i < state.windows.size();) {
4067 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004068 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004069 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004070 ALOGD("Touched window was removed: %s in display %" PRId32,
4071 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004072 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004073 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004074 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4075 if (touchedInputChannel != nullptr) {
4076 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4077 "touched window was removed");
4078 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004080 state.windows.erase(state.windows.begin() + i);
4081 } else {
4082 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 }
4084 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004085 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004086
Arthur Hung72d8dc32020-03-28 00:48:39 +00004087 // Release information for windows that are no longer present.
4088 // This ensures that unused input channels are released promptly.
4089 // Otherwise, they might stick around until the window handle is destroyed
4090 // which might not happen until the next GC.
4091 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004092 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004093 if (DEBUG_FOCUS) {
4094 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004095 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004096 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004097 }
chaviw291d88a2019-02-14 10:33:58 -08004098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099}
4100
4101void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004102 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004103 if (DEBUG_FOCUS) {
4104 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4105 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4106 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004107 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004108 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109
Chris Yea209fde2020-07-22 13:54:51 -07004110 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004111 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004112
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004113 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4114 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004115 }
4116
Chris Yea209fde2020-07-22 13:54:51 -07004117 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004118 if (inputApplicationHandle != nullptr) {
4119 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4120 } else {
4121 mFocusedApplicationHandlesByDisplay.erase(displayId);
4122 }
4123
4124 // No matter what the old focused application was, stop waiting on it because it is
4125 // no longer focused.
4126 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 } // release lock
4128
4129 // Wake up poll loop since it may need to make new input dispatching choices.
4130 mLooper->wake();
4131}
4132
Tiger Huang721e26f2018-07-24 22:26:19 +08004133/**
4134 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4135 * the display not specified.
4136 *
4137 * We track any unreleased events for each window. If a window loses the ability to receive the
4138 * released event, we will send a cancel event to it. So when the focused display is changed, we
4139 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4140 * display. The display-specified events won't be affected.
4141 */
4142void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004143 if (DEBUG_FOCUS) {
4144 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4145 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004146 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004147 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004148
4149 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004150 sp<IBinder> oldFocusedWindowToken =
4151 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4152 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004153 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004154 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004155 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156 CancelationOptions
4157 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4158 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004159 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004160 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4161 }
4162 }
4163 mFocusedDisplayId = displayId;
4164
Chris Ye3c2d6f52020-08-09 10:39:48 -07004165 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004166 sp<IBinder> newFocusedWindowToken =
4167 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4168 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004169
Vishnu Nairad321cd2020-08-20 16:40:21 -07004170 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004171 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004172 if (!mFocusedWindowTokenByDisplay.empty()) {
4173 ALOGE("But another display has a focused window\n%s",
4174 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004175 }
4176 }
4177 }
4178
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004179 if (DEBUG_FOCUS) {
4180 logDispatchStateLocked();
4181 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004182 } // release lock
4183
4184 // Wake up poll loop since it may need to make new input dispatching choices.
4185 mLooper->wake();
4186}
4187
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004189 if (DEBUG_FOCUS) {
4190 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192
4193 bool changed;
4194 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004195 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
4197 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4198 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004199 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 }
4201
4202 if (mDispatchEnabled && !enabled) {
4203 resetAndDropEverythingLocked("dispatcher is being disabled");
4204 }
4205
4206 mDispatchEnabled = enabled;
4207 mDispatchFrozen = frozen;
4208 changed = true;
4209 } else {
4210 changed = false;
4211 }
4212
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004213 if (DEBUG_FOCUS) {
4214 logDispatchStateLocked();
4215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 } // release lock
4217
4218 if (changed) {
4219 // Wake up poll loop since it may need to make new input dispatching choices.
4220 mLooper->wake();
4221 }
4222}
4223
4224void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004225 if (DEBUG_FOCUS) {
4226 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
4229 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004230 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
4232 if (mInputFilterEnabled == enabled) {
4233 return;
4234 }
4235
4236 mInputFilterEnabled = enabled;
4237 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4238 } // release lock
4239
4240 // Wake up poll loop since there might be work to do to drop everything.
4241 mLooper->wake();
4242}
4243
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004244void InputDispatcher::setInTouchMode(bool inTouchMode) {
4245 std::scoped_lock lock(mLock);
4246 mInTouchMode = inTouchMode;
4247}
4248
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004249void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4250 if (opacity < 0 || opacity > 1) {
4251 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4252 return;
4253 }
4254
4255 std::scoped_lock lock(mLock);
4256 mMaximumObscuringOpacityForTouch = opacity;
4257}
4258
4259void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4260 std::scoped_lock lock(mLock);
4261 mBlockUntrustedTouchesMode = mode;
4262}
4263
chaviwfbe5d9c2018-12-26 12:23:37 -08004264bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4265 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004266 if (DEBUG_FOCUS) {
4267 ALOGD("Trivial transfer to same window.");
4268 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004269 return true;
4270 }
4271
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004273 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
chaviwfbe5d9c2018-12-26 12:23:37 -08004275 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4276 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004277 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004278 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 return false;
4280 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004281 if (DEBUG_FOCUS) {
4282 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4283 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004286 if (DEBUG_FOCUS) {
4287 ALOGD("Cannot transfer focus because windows are on different displays.");
4288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 return false;
4290 }
4291
4292 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004293 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4294 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004295 for (size_t i = 0; i < state.windows.size(); i++) {
4296 const TouchedWindow& touchedWindow = state.windows[i];
4297 if (touchedWindow.windowHandle == fromWindowHandle) {
4298 int32_t oldTargetFlags = touchedWindow.targetFlags;
4299 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004301 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004303 int32_t newTargetFlags = oldTargetFlags &
4304 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4305 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004306 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Jeff Brownf086ddb2014-02-11 14:28:48 -08004308 found = true;
4309 goto Found;
4310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004313 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004316 if (DEBUG_FOCUS) {
4317 ALOGD("Focus transfer failed because from window did not have focus.");
4318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 return false;
4320 }
4321
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004322 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4323 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004324 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004325 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004326 CancelationOptions
4327 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4328 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004330 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004333 if (DEBUG_FOCUS) {
4334 logDispatchStateLocked();
4335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 } // release lock
4337
4338 // Wake up poll loop since it may need to make new input dispatching choices.
4339 mLooper->wake();
4340 return true;
4341}
4342
4343void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004344 if (DEBUG_FOCUS) {
4345 ALOGD("Resetting and dropping all events (%s).", reason);
4346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
4348 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4349 synthesizeCancelationEventsForAllConnectionsLocked(options);
4350
4351 resetKeyRepeatLocked();
4352 releasePendingEventLocked();
4353 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004354 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004356 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004357 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004359 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360}
4361
4362void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004363 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 dumpDispatchStateLocked(dump);
4365
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004366 std::istringstream stream(dump);
4367 std::string line;
4368
4369 while (std::getline(stream, line, '\n')) {
4370 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372}
4373
Vishnu Nairad321cd2020-08-20 16:40:21 -07004374std::string InputDispatcher::dumpFocusedWindowsLocked() {
4375 if (mFocusedWindowTokenByDisplay.empty()) {
4376 return INDENT "FocusedWindows: <none>\n";
4377 }
4378
4379 std::string dump;
4380 dump += INDENT "FocusedWindows:\n";
4381 for (auto& it : mFocusedWindowTokenByDisplay) {
4382 const int32_t displayId = it.first;
4383 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4384 if (windowHandle) {
4385 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4386 windowHandle->getName().c_str());
4387 } else {
4388 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4389 " has focused token without a window'\n",
4390 displayId);
4391 }
4392 }
4393 return dump;
4394}
4395
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004396void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004397 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4398 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4399 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004400 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401
Tiger Huang721e26f2018-07-24 22:26:19 +08004402 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4403 dump += StringPrintf(INDENT "FocusedApplications:\n");
4404 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4405 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004406 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004407 const std::chrono::duration timeout =
4408 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004410 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004411 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004414 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004416
Vishnu Nairad321cd2020-08-20 16:40:21 -07004417 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004419 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004420 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004421 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4422 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004423 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004424 state.displayId, toString(state.down), toString(state.split),
4425 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004426 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004427 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004428 for (size_t i = 0; i < state.windows.size(); i++) {
4429 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004430 dump += StringPrintf(INDENT4
4431 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4432 i, touchedWindow.windowHandle->getName().c_str(),
4433 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004434 }
4435 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004436 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004437 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004438 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004439 dump += INDENT3 "Portal windows:\n";
4440 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004441 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4443 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004444 }
4445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446 }
4447 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004448 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 }
4450
Arthur Hungb92218b2018-08-14 12:00:21 +08004451 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004453 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004454 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004455 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004456 dump += INDENT2 "Windows:\n";
4457 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004458 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004459 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
Arthur Hungb92218b2018-08-14 12:00:21 +08004461 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004462 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4463 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004464 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004465 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004466 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004467 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004468 i, windowInfo->name.c_str(), windowInfo->displayId,
4469 windowInfo->portalToDisplayId,
4470 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004471 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004472 toString(windowInfo->hasWallpaper),
4473 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004474 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004475 static_cast<int32_t>(windowInfo->type),
4476 windowInfo->frameLeft, windowInfo->frameTop,
4477 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004478 windowInfo->globalScaleFactor,
4479 windowInfo->applicationInfo.name.c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004480 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004481 dump += StringPrintf(", inputFeatures=%s",
4482 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004483 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4484 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004485 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004486 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004487 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004488 }
4489 } else {
4490 dump += INDENT2 "Windows: <none>\n";
4491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 }
4493 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004494 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 }
4496
Michael Wright3dd60e22019-03-27 22:06:44 +00004497 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004499 const std::vector<Monitor>& monitors = it.second;
4500 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4501 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004502 }
4503 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004504 const std::vector<Monitor>& monitors = it.second;
4505 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4506 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004509 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 }
4511
4512 nsecs_t currentTime = now();
4513
4514 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004515 if (!mRecentQueue.empty()) {
4516 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4517 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004518 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004519 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004520 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 }
4522 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004523 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 }
4525
4526 // Dump event currently being dispatched.
4527 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004528 dump += INDENT "PendingEvent:\n";
4529 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004530 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004531 dump += StringPrintf(", age=%" PRId64 "ms\n",
4532 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004534 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 }
4536
4537 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004538 if (!mInboundQueue.empty()) {
4539 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4540 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004541 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004542 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004543 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 }
4545 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004546 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 }
4548
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004549 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004550 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004551 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4552 const KeyReplacement& replacement = pair.first;
4553 int32_t newKeyCode = pair.second;
4554 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004555 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004556 }
4557 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004558 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004559 }
4560
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004561 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004562 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004563 for (const auto& pair : mConnectionsByFd) {
4564 const sp<Connection>& connection = pair.second;
4565 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004567 pair.first, connection->getInputChannelName().c_str(),
4568 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004569 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004571 if (!connection->outboundQueue.empty()) {
4572 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4573 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004574 dump += dumpQueue(connection->outboundQueue, currentTime);
4575
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004577 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 }
4579
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004580 if (!connection->waitQueue.empty()) {
4581 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4582 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004583 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004585 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 }
4587 }
4588 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004589 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 }
4591
4592 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004593 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4594 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004596 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 }
4598
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004599 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004600 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4601 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4602 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603}
4604
Michael Wright3dd60e22019-03-27 22:06:44 +00004605void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4606 const size_t numMonitors = monitors.size();
4607 for (size_t i = 0; i < numMonitors; i++) {
4608 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004609 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004610 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4611 dump += "\n";
4612 }
4613}
4614
Garfield Tan15601662020-09-22 15:32:38 -07004615base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4616 const std::string& name) {
4617#if DEBUG_CHANNEL_CREATION
4618 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619#endif
4620
Garfield Tan15601662020-09-22 15:32:38 -07004621 std::shared_ptr<InputChannel> serverChannel;
4622 std::unique_ptr<InputChannel> clientChannel;
4623 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4624
4625 if (result) {
4626 return base::Error(result) << "Failed to open input channel pair with name " << name;
4627 }
4628
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004630 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004631 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632
Garfield Tan15601662020-09-22 15:32:38 -07004633 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004634 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004635 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4638 } // release lock
4639
4640 // Wake the looper because some connections have changed.
4641 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004642 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643}
4644
Garfield Tan15601662020-09-22 15:32:38 -07004645base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4646 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4647 std::shared_ptr<InputChannel> serverChannel;
4648 std::unique_ptr<InputChannel> clientChannel;
4649 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4650 if (result) {
4651 return base::Error(result) << "Failed to open input channel pair with name " << name;
4652 }
4653
Michael Wright3dd60e22019-03-27 22:06:44 +00004654 { // acquire lock
4655 std::scoped_lock _l(mLock);
4656
4657 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004658 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4659 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004660 }
4661
Garfield Tan15601662020-09-22 15:32:38 -07004662 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004663
Garfield Tan15601662020-09-22 15:32:38 -07004664 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004665 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004666 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004667
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004668 auto& monitorsByDisplay =
4669 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004670 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004671
4672 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004673 }
Garfield Tan15601662020-09-22 15:32:38 -07004674
Michael Wright3dd60e22019-03-27 22:06:44 +00004675 // Wake the looper because some connections have changed.
4676 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004677 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004678}
4679
Garfield Tan15601662020-09-22 15:32:38 -07004680status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004682 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683
Garfield Tan15601662020-09-22 15:32:38 -07004684 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685 if (status) {
4686 return status;
4687 }
4688 } // release lock
4689
4690 // Wake the poll loop because removing the connection may have changed the current
4691 // synchronization state.
4692 mLooper->wake();
4693 return OK;
4694}
4695
Garfield Tan15601662020-09-22 15:32:38 -07004696status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4697 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004698 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004699 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004700 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 return BAD_VALUE;
4702 }
4703
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004704 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004705 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004706
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004708 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 }
4710
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004711 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712
4713 nsecs_t currentTime = now();
4714 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4715
4716 connection->status = Connection::STATUS_ZOMBIE;
4717 return OK;
4718}
4719
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004720void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4721 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4722 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004723}
4724
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004726 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004727 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004728 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004729 std::vector<Monitor>& monitors = it->second;
4730 const size_t numMonitors = monitors.size();
4731 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004732 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004733 monitors.erase(monitors.begin() + i);
4734 break;
4735 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004736 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004737 if (monitors.empty()) {
4738 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004739 } else {
4740 ++it;
4741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 }
4743}
4744
Michael Wright3dd60e22019-03-27 22:06:44 +00004745status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4746 { // acquire lock
4747 std::scoped_lock _l(mLock);
4748 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4749
4750 if (!foundDisplayId) {
4751 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4752 return BAD_VALUE;
4753 }
4754 int32_t displayId = foundDisplayId.value();
4755
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004756 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4757 mTouchStatesByDisplay.find(displayId);
4758 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004759 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4760 return BAD_VALUE;
4761 }
4762
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004763 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004764 std::optional<int32_t> foundDeviceId;
4765 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004766 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004767 foundDeviceId = state.deviceId;
4768 }
4769 }
4770 if (!foundDeviceId || !state.down) {
4771 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004772 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004773 return BAD_VALUE;
4774 }
4775 int32_t deviceId = foundDeviceId.value();
4776
4777 // Send cancel events to all the input channels we're stealing from.
4778 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004779 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004780 options.deviceId = deviceId;
4781 options.displayId = displayId;
4782 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004783 std::shared_ptr<InputChannel> channel =
4784 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004785 if (channel != nullptr) {
4786 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4787 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004788 }
4789 // Then clear the current touch state so we stop dispatching to them as well.
4790 state.filterNonMonitors();
4791 }
4792 return OK;
4793}
4794
Michael Wright3dd60e22019-03-27 22:06:44 +00004795std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4796 const sp<IBinder>& token) {
4797 for (const auto& it : mGestureMonitorsByDisplay) {
4798 const std::vector<Monitor>& monitors = it.second;
4799 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004800 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004801 return it.first;
4802 }
4803 }
4804 }
4805 return std::nullopt;
4806}
4807
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004808sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004809 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004810 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004811 }
4812
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004813 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004814 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004815 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004816 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 }
4818 }
Robert Carr4e670e52018-08-15 13:26:12 -07004819
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004820 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821}
4822
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004823void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004824 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004825 removeByValue(mConnectionsByFd, connection);
4826}
4827
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004828void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4829 const sp<Connection>& connection, uint32_t seq,
4830 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004831 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4832 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 commandEntry->connection = connection;
4834 commandEntry->eventTime = currentTime;
4835 commandEntry->seq = seq;
4836 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004837 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838}
4839
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004840void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4841 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004843 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004845 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4846 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004848 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849}
4850
Vishnu Nairad321cd2020-08-20 16:40:21 -07004851void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4852 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004853 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4854 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004855 commandEntry->oldToken = oldToken;
4856 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004857 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004858}
4859
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004860void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4862 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004863 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004865 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004866 return;
4867 }
4868 /**
4869 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4870 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4871 * has changed. This could cause newer entries to time out before the already dispatched
4872 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4873 * processes the events linearly. So providing information about the oldest entry seems to be
4874 * most useful.
4875 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004876 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4878 std::string reason =
4879 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004880 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004881 ns2ms(currentWait),
4882 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004884 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004885 reason);
4886
4887 std::unique_ptr<CommandEntry> commandEntry =
4888 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4889 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004890 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004891 commandEntry->reason = std::move(reason);
4892 postCommandLocked(std::move(commandEntry));
4893}
4894
Chris Yea209fde2020-07-22 13:54:51 -07004895void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4897 application->getName().c_str());
4898
4899 updateLastAnrStateLocked(application, reason);
4900
4901 std::unique_ptr<CommandEntry> commandEntry =
4902 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4903 commandEntry->inputApplicationHandle = application;
4904 commandEntry->inputChannel = nullptr;
4905 commandEntry->reason = std::move(reason);
4906 postCommandLocked(std::move(commandEntry));
4907}
4908
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004909void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
4910 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4911 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
4912 commandEntry->obscuringPackage = obscuringPackage;
4913 postCommandLocked(std::move(commandEntry));
4914}
4915
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4917 const std::string& reason) {
4918 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4919 updateLastAnrStateLocked(windowLabel, reason);
4920}
4921
Chris Yea209fde2020-07-22 13:54:51 -07004922void InputDispatcher::updateLastAnrStateLocked(
4923 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4925 updateLastAnrStateLocked(windowLabel, reason);
4926}
4927
4928void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4929 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004931 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 struct tm tm;
4933 localtime_r(&t, &tm);
4934 char timestr[64];
4935 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004936 mLastAnrState.clear();
4937 mLastAnrState += INDENT "ANR:\n";
4938 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004939 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4940 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004941 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942}
4943
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004944void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 mLock.unlock();
4946
4947 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4948
4949 mLock.lock();
4950}
4951
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004952void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 sp<Connection> connection = commandEntry->connection;
4954
4955 if (connection->status != Connection::STATUS_ZOMBIE) {
4956 mLock.unlock();
4957
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004958 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959
4960 mLock.lock();
4961 }
4962}
4963
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004964void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004965 sp<IBinder> oldToken = commandEntry->oldToken;
4966 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004967 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004968 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004969 mLock.lock();
4970}
4971
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004972void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004973 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004974 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 mLock.unlock();
4976
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004977 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004978 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979
4980 mLock.lock();
4981
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004982 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004983 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4984 } else {
4985 // stop waking up for events in this connection, it is already not responding
4986 sp<Connection> connection = getConnectionLocked(token);
4987 if (connection == nullptr) {
4988 return;
4989 }
4990 cancelEventsForAnrLocked(connection);
4991 }
4992}
4993
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004994void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
4995 mLock.unlock();
4996
4997 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
4998
4999 mLock.lock();
5000}
5001
Chris Yea209fde2020-07-22 13:54:51 -07005002void InputDispatcher::extendAnrTimeoutsLocked(
5003 const std::shared_ptr<InputApplicationHandle>& application,
5004 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005005 if (connectionToken == nullptr && application != nullptr) {
5006 // The ANR happened because there's no focused window
5007 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
5008 mAwaitedFocusedApplication = application;
5009 }
5010
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005011 sp<Connection> connection = getConnectionLocked(connectionToken);
5012 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005013 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005014 return;
5015 }
5016
5017 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05005018 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005019
5020 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05005021 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005022 for (DispatchEntry* entry : connection->waitQueue) {
5023 if (newTimeout >= entry->timeoutTime) {
5024 // Already removed old entries when connection was marked unresponsive
5025 entry->timeoutTime = newTimeout;
5026 mAnrTracker.insert(entry->timeoutTime, connectionToken);
5027 }
5028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029}
5030
5031void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5032 CommandEntry* commandEntry) {
5033 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005034 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035
5036 mLock.unlock();
5037
Michael Wright2b3c3302018-03-02 17:19:13 +00005038 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005039 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005040 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 : nullptr;
5042 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005043 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5044 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005045 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047
5048 mLock.lock();
5049
5050 if (delay < 0) {
5051 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5052 } else if (!delay) {
5053 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5054 } else {
5055 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5056 entry->interceptKeyWakeupTime = now() + delay;
5057 }
5058 entry->release();
5059}
5060
chaviwfd6d3512019-03-25 13:23:49 -07005061void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5062 mLock.unlock();
5063 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5064 mLock.lock();
5065}
5066
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005067/**
5068 * Connection is responsive if it has no events in the waitQueue that are older than the
5069 * current time.
5070 */
5071static bool isConnectionResponsive(const Connection& connection) {
5072 const nsecs_t currentTime = now();
5073 for (const DispatchEntry* entry : connection.waitQueue) {
5074 if (entry->timeoutTime < currentTime) {
5075 return false;
5076 }
5077 }
5078 return true;
5079}
5080
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005081void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005083 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005085 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086
5087 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005088 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005089 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005090 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005092 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005093 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005094 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005095 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5096 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005097 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005098 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005099
5100 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005101 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005102 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
5103 restartEvent =
5104 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005105 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005106 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
5107 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5108 handled);
5109 } else {
5110 restartEvent = false;
5111 }
5112
5113 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005114 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005115 // contents of the wait queue to have been drained, so we need to double-check
5116 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005117 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5118 if (dispatchEntryIt != connection->waitQueue.end()) {
5119 dispatchEntry = *dispatchEntryIt;
5120 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005121 mAnrTracker.erase(dispatchEntry->timeoutTime,
5122 connection->inputChannel->getConnectionToken());
5123 if (!connection->responsive) {
5124 connection->responsive = isConnectionResponsive(*connection);
5125 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005126 traceWaitQueueLength(connection);
5127 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005128 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005129 traceOutboundQueueLength(connection);
5130 } else {
5131 releaseDispatchEntry(dispatchEntry);
5132 }
5133 }
5134
5135 // Start the next dispatch cycle for this connection.
5136 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137}
5138
5139bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005140 DispatchEntry* dispatchEntry,
5141 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005142 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005143 if (!handled) {
5144 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005145 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005146 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005147 return false;
5148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005150 // Get the fallback key state.
5151 // Clear it out after dispatching the UP.
5152 int32_t originalKeyCode = keyEntry->keyCode;
5153 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5154 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
5155 connection->inputState.removeFallbackKey(originalKeyCode);
5156 }
5157
5158 if (handled || !dispatchEntry->hasForegroundTarget()) {
5159 // If the application handles the original key for which we previously
5160 // generated a fallback or if the window is not a foreground window,
5161 // then cancel the associated fallback key, if any.
5162 if (fallbackKeyCode != -1) {
5163 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005165 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005166 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5167 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
5168 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005170 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005171 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172
5173 mLock.unlock();
5174
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005175 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005176 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177
5178 mLock.lock();
5179
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005180 // Cancel the fallback key.
5181 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005183 "application handled the original non-fallback key "
5184 "or is no longer a foreground target, "
5185 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 options.keyCode = fallbackKeyCode;
5187 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005189 connection->inputState.removeFallbackKey(originalKeyCode);
5190 }
5191 } else {
5192 // If the application did not handle a non-fallback key, first check
5193 // that we are in a good state to perform unhandled key event processing
5194 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005195 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005196 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005198 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005199 "since this is not an initial down. "
5200 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5201 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005203 return false;
5204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005206 // Dispatch the unhandled key to the policy.
5207#if DEBUG_OUTBOUND_EVENT_DETAILS
5208 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005209 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5210 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005211#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005212 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005213
5214 mLock.unlock();
5215
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005216 bool fallback =
5217 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5218 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005219
5220 mLock.lock();
5221
5222 if (connection->status != Connection::STATUS_NORMAL) {
5223 connection->inputState.removeFallbackKey(originalKeyCode);
5224 return false;
5225 }
5226
5227 // Latch the fallback keycode for this key on an initial down.
5228 // The fallback keycode cannot change at any other point in the lifecycle.
5229 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005231 fallbackKeyCode = event.getKeyCode();
5232 } else {
5233 fallbackKeyCode = AKEYCODE_UNKNOWN;
5234 }
5235 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5236 }
5237
5238 ALOG_ASSERT(fallbackKeyCode != -1);
5239
5240 // Cancel the fallback key if the policy decides not to send it anymore.
5241 // We will continue to dispatch the key to the policy but we will no
5242 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005243 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5244 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005245#if DEBUG_OUTBOUND_EVENT_DETAILS
5246 if (fallback) {
5247 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005248 "as a fallback for %d, but on the DOWN it had requested "
5249 "to send %d instead. Fallback canceled.",
5250 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005251 } else {
5252 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005253 "but on the DOWN it had requested to send %d. "
5254 "Fallback canceled.",
5255 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005256 }
5257#endif
5258
5259 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5260 "canceling fallback, policy no longer desires it");
5261 options.keyCode = fallbackKeyCode;
5262 synthesizeCancelationEventsForConnectionLocked(connection, options);
5263
5264 fallback = false;
5265 fallbackKeyCode = AKEYCODE_UNKNOWN;
5266 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005267 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005268 }
5269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270
5271#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005272 {
5273 std::string msg;
5274 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5275 connection->inputState.getFallbackKeys();
5276 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005277 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005279 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005280 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005281 }
5282#endif
5283
5284 if (fallback) {
5285 // Restart the dispatch cycle using the fallback key.
5286 keyEntry->eventTime = event.getEventTime();
5287 keyEntry->deviceId = event.getDeviceId();
5288 keyEntry->source = event.getSource();
5289 keyEntry->displayId = event.getDisplayId();
5290 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5291 keyEntry->keyCode = fallbackKeyCode;
5292 keyEntry->scanCode = event.getScanCode();
5293 keyEntry->metaState = event.getMetaState();
5294 keyEntry->repeatCount = event.getRepeatCount();
5295 keyEntry->downTime = event.getDownTime();
5296 keyEntry->syntheticRepeat = false;
5297
5298#if DEBUG_OUTBOUND_EVENT_DETAILS
5299 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005300 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5301 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005302#endif
5303 return true; // restart the event
5304 } else {
5305#if DEBUG_OUTBOUND_EVENT_DETAILS
5306 ALOGD("Unhandled key event: No fallback key.");
5307#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005308
5309 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005310 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 }
5312 }
5313 return false;
5314}
5315
5316bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005317 DispatchEntry* dispatchEntry,
5318 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 return false;
5320}
5321
5322void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5323 mLock.unlock();
5324
5325 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5326
5327 mLock.lock();
5328}
5329
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005330KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5331 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005332 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005333 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5334 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005335 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336}
5337
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005338void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5339 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 // TODO Write some statistics about how long we spend waiting.
5341}
5342
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005343/**
5344 * Report the touch event latency to the statsd server.
5345 * Input events are reported for statistics if:
5346 * - This is a touchscreen event
5347 * - InputFilter is not enabled
5348 * - Event is not injected or synthesized
5349 *
5350 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5351 * from getting aggregated with the "old" data.
5352 */
5353void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5354 REQUIRES(mLock) {
5355 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5356 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5357 if (!reportForStatistics) {
5358 return;
5359 }
5360
5361 if (mTouchStatistics.shouldReport()) {
5362 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5363 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5364 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5365 mTouchStatistics.reset();
5366 }
5367 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5368 mTouchStatistics.addValue(latencyMicros);
5369}
5370
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371void InputDispatcher::traceInboundQueueLengthLocked() {
5372 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005373 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 }
5375}
5376
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005377void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378 if (ATRACE_ENABLED()) {
5379 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005380 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005381 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 }
5383}
5384
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005385void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 if (ATRACE_ENABLED()) {
5387 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005388 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005389 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 }
5391}
5392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005393void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005394 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005396 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 dumpDispatchStateLocked(dump);
5398
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005399 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005400 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005401 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403}
5404
5405void InputDispatcher::monitor() {
5406 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005407 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005409 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410}
5411
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005412/**
5413 * Wake up the dispatcher and wait until it processes all events and commands.
5414 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5415 * this method can be safely called from any thread, as long as you've ensured that
5416 * the work you are interested in completing has already been queued.
5417 */
5418bool InputDispatcher::waitForIdle() {
5419 /**
5420 * Timeout should represent the longest possible time that a device might spend processing
5421 * events and commands.
5422 */
5423 constexpr std::chrono::duration TIMEOUT = 100ms;
5424 std::unique_lock lock(mLock);
5425 mLooper->wake();
5426 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5427 return result == std::cv_status::no_timeout;
5428}
5429
Vishnu Naire798b472020-07-23 13:52:21 -07005430/**
5431 * Sets focus to the window identified by the token. This must be called
5432 * after updating any input window handles.
5433 *
5434 * Params:
5435 * request.token - input channel token used to identify the window that should gain focus.
5436 * request.focusedToken - the token that the caller expects currently to be focused. If the
5437 * specified token does not match the currently focused window, this request will be dropped.
5438 * If the specified focused token matches the currently focused window, the call will succeed.
5439 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5440 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5441 * when requesting the focus change. This determines which request gets
5442 * precedence if there is a focus change request from another source such as pointer down.
5443 */
Vishnu Nair958da932020-08-21 17:12:37 -07005444void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5445 { // acquire lock
5446 std::scoped_lock _l(mLock);
5447
5448 const int32_t displayId = request.displayId;
5449 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5450 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5451 ALOGD_IF(DEBUG_FOCUS,
5452 "setFocusedWindow on display %" PRId32
5453 " ignored, reason: focusedToken is not focused",
5454 displayId);
5455 return;
5456 }
5457
5458 mPendingFocusRequests.erase(displayId);
5459 FocusResult result = handleFocusRequestLocked(request);
5460 if (result == FocusResult::NOT_VISIBLE) {
5461 // The requested window is not currently visible. Wait for the window to become visible
5462 // and then provide it focus. This is to handle situations where a user action triggers
5463 // a new window to appear. We want to be able to queue any key events after the user
5464 // action and deliver it to the newly focused window. In order for this to happen, we
5465 // take focus from the currently focused window so key events can be queued.
5466 ALOGD_IF(DEBUG_FOCUS,
5467 "setFocusedWindow on display %" PRId32
5468 " pending, reason: window is not visible",
5469 displayId);
5470 mPendingFocusRequests[displayId] = request;
5471 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5472 "setFocusedWindow_AwaitingWindowVisibility");
5473 } else if (result != FocusResult::OK) {
5474 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5475 typeToString(result));
5476 }
5477 } // release lock
5478 // Wake up poll loop since it may need to make new input dispatching choices.
5479 mLooper->wake();
5480}
5481
5482InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5483 const FocusRequest& request) {
5484 const int32_t displayId = request.displayId;
5485 const sp<IBinder> newFocusedToken = request.token;
5486 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5487
5488 if (oldFocusedToken == request.token) {
5489 ALOGD_IF(DEBUG_FOCUS,
5490 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5491 displayId);
5492 return FocusResult::OK;
5493 }
5494
5495 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5496 if (result != FocusResult::OK) {
5497 return result;
5498 }
5499
5500 std::string_view reason =
5501 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5502 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5503 return FocusResult::OK;
5504}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005505
Vishnu Nairad321cd2020-08-20 16:40:21 -07005506void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5507 const sp<IBinder>& newFocusedToken, int32_t displayId,
5508 std::string_view reason) {
5509 if (oldFocusedToken) {
5510 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005511 if (focusedInputChannel) {
5512 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5513 "focus left window");
5514 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005515 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005516 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005517 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005518 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005519 if (newFocusedToken) {
5520 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5521 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005522 }
5523
5524 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005525 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005526 }
5527}
Vishnu Nair958da932020-08-21 17:12:37 -07005528
5529/**
5530 * Checks if the window token can be focused on a display. The token can be focused if there is
5531 * at least one window handle that is visible with the same token and all window handles with the
5532 * same token are focusable.
5533 *
5534 * In the case of mirroring, two windows may share the same window token and their visibility
5535 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5536 * we expect the focusability of the windows to match since its hard to reason why one window can
5537 * receive focus events and the other cannot when both are backed by the same input channel.
5538 */
5539InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5540 int32_t displayId) const {
5541 bool allWindowsAreFocusable = true;
5542 bool visibleWindowFound = false;
5543 bool windowFound = false;
5544 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5545 if (window->getToken() != token) {
5546 continue;
5547 }
5548 windowFound = true;
5549 if (window->getInfo()->visible) {
5550 // Check if at least a single window is visible.
5551 visibleWindowFound = true;
5552 }
5553 if (!window->getInfo()->focusable) {
5554 // Check if all windows with the window token are focusable.
5555 allWindowsAreFocusable = false;
5556 break;
5557 }
5558 }
5559
5560 if (!windowFound) {
5561 return FocusResult::NO_WINDOW;
5562 }
5563 if (!allWindowsAreFocusable) {
5564 return FocusResult::NOT_FOCUSABLE;
5565 }
5566 if (!visibleWindowFound) {
5567 return FocusResult::NOT_VISIBLE;
5568 }
5569
5570 return FocusResult::OK;
5571}
Garfield Tane84e6f92019-08-29 17:28:41 -07005572} // namespace android::inputdispatcher