blob: 9c8481c99fa39ec47b6c8c8c089b86b1c5321389 [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
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
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
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Gang Wang342c9272020-01-13 13:15:04 -050056#include <openssl/hmac.h>
57#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070058#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010059#include <statslog.h>
60#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
Michael Wright44753b12020-07-08 13:48:11 +010063#include <cerrno>
64#include <cinttypes>
65#include <climits>
66#include <cstddef>
67#include <ctime>
68#include <queue>
69#include <sstream>
70
71#include "Connection.h"
72
Michael Wrightd02c5b62014-02-10 15:10:22 -080073#define INDENT " "
74#define INDENT2 " "
75#define INDENT3 " "
76#define INDENT4 " "
77
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080078using android::base::StringPrintf;
79
Garfield Tane84e6f92019-08-29 17:28:41 -070080namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080081
82// Default input dispatching timeout if there is no focused application or paused window
83// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050084constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
85 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
87// Amount of time to allow for all pending events to be processed when an app switch
88// key is on the way. This is used to preempt input dispatch and drop input events
89// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow for an event to be dispatched (measured since its eventTime)
93// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000094constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Michael Wrightd02c5b62014-02-10 15:10:22 -080096// 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 +000097constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
98
99// Log a warning when an interception call takes longer than this to process.
100constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700102// Additional key latency in case a connection is still processing some motion events.
103// This will help with the case when a user touched a button that opens a new window,
104// and gives us the chance to dispatch the key to this new window.
105constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000108constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
109
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000110// Event log tags. See EventLogTags.logtags for reference
111constexpr int LOGTAG_INPUT_INTERACTION = 62000;
112constexpr int LOGTAG_INPUT_FOCUS = 62001;
113
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114static inline nsecs_t now() {
115 return systemTime(SYSTEM_TIME_MONOTONIC);
116}
117
118static inline const char* toString(bool value) {
119 return value ? "true" : "false";
120}
121
122static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700123 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
124 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125}
126
127static bool isValidKeyAction(int32_t action) {
128 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700129 case AKEY_EVENT_ACTION_DOWN:
130 case AKEY_EVENT_ACTION_UP:
131 return true;
132 default:
133 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 }
135}
136
137static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 ALOGE("Key event has invalid action code 0x%x", action);
140 return false;
141 }
142 return true;
143}
144
Michael Wright7b159c92015-05-14 14:48:03 +0100145static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 case AMOTION_EVENT_ACTION_DOWN:
148 case AMOTION_EVENT_ACTION_UP:
149 case AMOTION_EVENT_ACTION_CANCEL:
150 case AMOTION_EVENT_ACTION_MOVE:
151 case AMOTION_EVENT_ACTION_OUTSIDE:
152 case AMOTION_EVENT_ACTION_HOVER_ENTER:
153 case AMOTION_EVENT_ACTION_HOVER_MOVE:
154 case AMOTION_EVENT_ACTION_HOVER_EXIT:
155 case AMOTION_EVENT_ACTION_SCROLL:
156 return true;
157 case AMOTION_EVENT_ACTION_POINTER_DOWN:
158 case AMOTION_EVENT_ACTION_POINTER_UP: {
159 int32_t index = getMotionEventActionPointerIndex(action);
160 return index >= 0 && index < pointerCount;
161 }
162 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
163 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
164 return actionButton != 0;
165 default:
166 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 }
168}
169
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500170static int64_t millis(std::chrono::nanoseconds t) {
171 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
172}
173
Michael Wright7b159c92015-05-14 14:48:03 +0100174static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 const PointerProperties* pointerProperties) {
176 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 ALOGE("Motion event has invalid action code 0x%x", action);
178 return false;
179 }
180 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000181 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700182 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183 return false;
184 }
185 BitSet32 pointerIdBits;
186 for (size_t i = 0; i < pointerCount; i++) {
187 int32_t id = pointerProperties[i].id;
188 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
190 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 if (pointerIdBits.hasBit(id)) {
194 ALOGE("Motion event has duplicate pointer id %d", id);
195 return false;
196 }
197 pointerIdBits.markBit(id);
198 }
199 return true;
200}
201
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800204 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 return;
206 }
207
208 bool first = true;
209 Region::const_iterator cur = region.begin();
210 Region::const_iterator const tail = region.end();
211 while (cur != tail) {
212 if (first) {
213 first = false;
214 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800217 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 cur++;
219 }
220}
221
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700222/**
223 * Find the entry in std::unordered_map by key, and return it.
224 * If the entry is not found, return a default constructed entry.
225 *
226 * Useful when the entries are vectors, since an empty vector will be returned
227 * if the entry is not found.
228 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
229 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700230template <typename K, typename V>
231static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700232 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700233 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800234}
235
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700236/**
237 * Find the entry in std::unordered_map by value, and remove it.
238 * If more than one entry has the same value, then all matching
239 * key-value pairs will be removed.
240 *
241 * Return true if at least one value has been removed.
242 */
243template <typename K, typename V>
244static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
245 bool removed = false;
246 for (auto it = map.begin(); it != map.end();) {
247 if (it->second == value) {
248 it = map.erase(it);
249 removed = true;
250 } else {
251 it++;
252 }
253 }
254 return removed;
255}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256
chaviwaf87b3e2019-10-01 16:59:28 -0700257static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
258 if (first == second) {
259 return true;
260 }
261
262 if (first == nullptr || second == nullptr) {
263 return false;
264 }
265
266 return first->getToken() == second->getToken();
267}
268
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800269static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
270 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
271}
272
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000273static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
274 EventEntry* eventEntry,
275 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700276 if (inputTarget.useDefaultPointerTransform()) {
277 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000278 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700279 inputTargetFlags, transform,
280 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000281 }
282
283 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
284 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
285
286 PointerCoords pointerCoords[motionEntry.pointerCount];
287
288 // Use the first pointer information to normalize all other pointers. This could be any pointer
289 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700290 // uses the transform for the normalized pointer.
291 const ui::Transform& firstPointerTransform =
292 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
293 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000294
295 // Iterate through all pointers in the event to normalize against the first.
296 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
297 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
298 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700299 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000300
301 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700302 // First, apply the current pointer's transform to update the coordinates into
303 // window space.
304 pointerCoords[pointerIndex].transform(currTransform);
305 // Next, apply the inverse transform of the normalized coordinates so the
306 // current coordinates are transformed into the normalized coordinate space.
307 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000308 }
309
310 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800311 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000312 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
313 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
314 motionEntry.metaState, motionEntry.buttonState,
315 motionEntry.classification, motionEntry.edgeFlags,
316 motionEntry.xPrecision, motionEntry.yPrecision,
317 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
318 motionEntry.downTime, motionEntry.pointerCount,
319 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
320 0 /* yOffset */);
321
322 if (motionEntry.injectionState) {
323 combinedMotionEntry->injectionState = motionEntry.injectionState;
324 combinedMotionEntry->injectionState->refCount += 1;
325 }
326
327 std::unique_ptr<DispatchEntry> dispatchEntry =
328 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700329 inputTargetFlags, firstPointerTransform,
330 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331 combinedMotionEntry->release();
332 return dispatchEntry;
333}
334
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700335static void addGestureMonitors(const std::vector<Monitor>& monitors,
336 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
337 float yOffset = 0) {
338 if (monitors.empty()) {
339 return;
340 }
341 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
342 for (const Monitor& monitor : monitors) {
343 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
344 }
345}
346
Gang Wang342c9272020-01-13 13:15:04 -0500347static std::array<uint8_t, 128> getRandomKey() {
348 std::array<uint8_t, 128> key;
349 if (RAND_bytes(key.data(), key.size()) != 1) {
350 LOG_ALWAYS_FATAL("Can't generate HMAC key");
351 }
352 return key;
353}
354
355// --- HmacKeyManager ---
356
357HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
358
359std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
360 size_t size;
361 switch (event.type) {
362 case VerifiedInputEvent::Type::KEY: {
363 size = sizeof(VerifiedKeyEvent);
364 break;
365 }
366 case VerifiedInputEvent::Type::MOTION: {
367 size = sizeof(VerifiedMotionEvent);
368 break;
369 }
370 }
Gang Wang342c9272020-01-13 13:15:04 -0500371 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700372 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500373}
374
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700375std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500376 // SHA256 always generates 32-bytes result
377 std::array<uint8_t, 32> hash;
378 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700379 uint8_t* result =
380 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500381 if (result == nullptr) {
382 ALOGE("Could not sign the data using HMAC");
383 return INVALID_HMAC;
384 }
385
386 if (hashLen != hash.size()) {
387 ALOGE("HMAC-SHA256 has unexpected length");
388 return INVALID_HMAC;
389 }
390
391 return hash;
392}
393
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394// --- InputDispatcher ---
395
Garfield Tan00f511d2019-06-12 16:55:40 -0700396InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
397 : mPolicy(policy),
398 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700399 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800400 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700401 mAppSwitchSawKeyDown(false),
402 mAppSwitchDueTime(LONG_LONG_MAX),
403 mNextUnblockedEvent(nullptr),
404 mDispatchEnabled(false),
405 mDispatchFrozen(false),
406 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800407 // mInTouchMode will be initialized by the WindowManager to the default device config.
408 // To avoid leaking stack in case that call never comes, and for tests,
409 // initialize it here anyways.
410 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700411 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800413 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414
Yi Kong9b14ac62018-07-17 13:48:38 -0700415 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416
417 policy->getDispatcherConfiguration(&mConfig);
418}
419
420InputDispatcher::~InputDispatcher() {
421 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800422 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800423
424 resetKeyRepeatLocked();
425 releasePendingEventLocked();
426 drainInboundQueueLocked();
427 }
428
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700429 while (!mConnectionsByFd.empty()) {
430 sp<Connection> connection = mConnectionsByFd.begin()->second;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500431 unregisterInputChannel(*connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 }
433}
434
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700435status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437 return ALREADY_EXISTS;
438 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700439 mThread = std::make_unique<InputThread>(
440 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
441 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442}
443
444status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700445 if (mThread && mThread->isCallingThread()) {
446 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700447 return INVALID_OPERATION;
448 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700449 mThread.reset();
450 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700451}
452
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453void InputDispatcher::dispatchOnce() {
454 nsecs_t nextWakeupTime = LONG_LONG_MAX;
455 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800456 std::scoped_lock _l(mLock);
457 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458
459 // Run a dispatch loop if there are no pending commands.
460 // The dispatch loop might enqueue commands to run afterwards.
461 if (!haveCommandsLocked()) {
462 dispatchOnceInnerLocked(&nextWakeupTime);
463 }
464
465 // Run all pending commands if there are any.
466 // If any commands were run then force the next poll to wake up immediately.
467 if (runCommandsLockedInterruptible()) {
468 nextWakeupTime = LONG_LONG_MIN;
469 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800470
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700471 // If we are still waiting for ack on some events,
472 // we might have to wake up earlier to check if an app is anr'ing.
473 const nsecs_t nextAnrCheck = processAnrsLocked();
474 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
475
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800476 // We are about to enter an infinitely long sleep, because we have no commands or
477 // pending or queued events
478 if (nextWakeupTime == LONG_LONG_MAX) {
479 mDispatcherEnteredIdle.notify_all();
480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 } // release lock
482
483 // Wait for callback or timeout or wake. (make sure we round up, not down)
484 nsecs_t currentTime = now();
485 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
486 mLooper->pollOnce(timeoutMillis);
487}
488
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700489/**
490 * Check if any of the connections' wait queues have events that are too old.
491 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
492 * Return the time at which we should wake up next.
493 */
494nsecs_t InputDispatcher::processAnrsLocked() {
495 const nsecs_t currentTime = now();
496 nsecs_t nextAnrCheck = LONG_LONG_MAX;
497 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
498 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
499 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
500 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700501 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700502 return LONG_LONG_MIN;
503 } else {
504 // Keep waiting
505 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
506 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
507 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
508 }
509 }
510
511 // Check if any connection ANRs are due
512 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
513 if (currentTime < nextAnrCheck) { // most likely scenario
514 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
515 }
516
517 // If we reached here, we have an unresponsive connection.
518 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
519 if (connection == nullptr) {
520 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
521 return nextAnrCheck;
522 }
523 connection->responsive = false;
524 // Stop waking up for this unresponsive connection
525 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
526 onAnrLocked(connection);
527 return LONG_LONG_MIN;
528}
529
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500530std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700531 sp<InputWindowHandle> window = getWindowHandleLocked(token);
532 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500533 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700534 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500535 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700536}
537
Michael Wrightd02c5b62014-02-10 15:10:22 -0800538void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
539 nsecs_t currentTime = now();
540
Jeff Browndc5992e2014-04-11 01:27:26 -0700541 // Reset the key repeat timer whenever normal dispatch is suspended while the
542 // device is in a non-interactive state. This is to ensure that we abort a key
543 // repeat if the device is just coming out of sleep.
544 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 resetKeyRepeatLocked();
546 }
547
548 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
549 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100550 if (DEBUG_FOCUS) {
551 ALOGD("Dispatch frozen. Waiting some more.");
552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 return;
554 }
555
556 // Optimize latency of app switches.
557 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
558 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
559 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
560 if (mAppSwitchDueTime < *nextWakeupTime) {
561 *nextWakeupTime = mAppSwitchDueTime;
562 }
563
564 // Ready to start a new event.
565 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700566 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700567 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 if (isAppSwitchDue) {
569 // The inbound queue is empty so the app switch key we were waiting
570 // for will never arrive. Stop waiting for it.
571 resetPendingAppSwitchLocked(false);
572 isAppSwitchDue = false;
573 }
574
575 // Synthesize a key repeat if appropriate.
576 if (mKeyRepeatState.lastKeyEntry) {
577 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
578 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
579 } else {
580 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
581 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
582 }
583 }
584 }
585
586 // Nothing to do if there is no pending event.
587 if (!mPendingEvent) {
588 return;
589 }
590 } else {
591 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700592 mPendingEvent = mInboundQueue.front();
593 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594 traceInboundQueueLengthLocked();
595 }
596
597 // Poke user activity for this event.
598 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700599 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 }
602
603 // Now we have an event to dispatch.
604 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700605 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700607 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700609 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700611 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
613
614 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700615 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 }
617
618 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700619 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 ConfigurationChangedEntry* typedEntry =
621 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
622 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700623 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700624 break;
625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700627 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700628 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
629 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 break;
632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100634 case EventEntry::Type::FOCUS: {
635 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
636 dispatchFocusLocked(currentTime, typedEntry);
637 done = true;
638 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
639 break;
640 }
641
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700642 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700643 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
644 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700645 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700646 resetPendingAppSwitchLocked(true);
647 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 } else if (dropReason == DropReason::NOT_DROPPED) {
649 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 }
651 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700652 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700653 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700655 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
656 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700657 }
658 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
659 break;
660 }
661
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700662 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700663 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700664 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
665 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700667 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700668 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700670 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
671 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700672 }
673 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
674 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677
678 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700679 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700680 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
Michael Wright3a981722015-06-10 15:26:13 +0100682 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683
684 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700685 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 }
687}
688
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700689/**
690 * Return true if the events preceding this incoming motion event should be dropped
691 * Return false otherwise (the default behaviour)
692 */
693bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700695 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700696
697 // Optimize case where the current application is unresponsive and the user
698 // decides to touch a window in a different application.
699 // If the application takes too long to catch up then we drop all events preceding
700 // the touch into the other window.
701 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700702 int32_t displayId = motionEntry.displayId;
703 int32_t x = static_cast<int32_t>(
704 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
705 int32_t y = static_cast<int32_t>(
706 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
707 sp<InputWindowHandle> touchedWindowHandle =
708 findTouchedWindowAtLocked(displayId, x, y, nullptr);
709 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700710 touchedWindowHandle->getApplicationToken() !=
711 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700712 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713 ALOGI("Pruning input queue because user touched a different application while waiting "
714 "for %s",
715 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700716 return true;
717 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700718
719 // Alternatively, maybe there's a gesture monitor that could handle this event
720 std::vector<TouchedMonitor> gestureMonitors =
721 findTouchedGestureMonitorsLocked(displayId, {});
722 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
723 sp<Connection> connection =
724 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000725 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700726 // This monitor could take more input. Drop all events preceding this
727 // event, so that gesture monitor could get a chance to receive the stream
728 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
729 "responsive gesture monitor that may handle the event",
730 mAwaitedFocusedApplication->getName().c_str());
731 return true;
732 }
733 }
734 }
735
736 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
737 // yet been processed by some connections, the dispatcher will wait for these motion
738 // events to be processed before dispatching the key event. This is because these motion events
739 // may cause a new window to be launched, which the user might expect to receive focus.
740 // To prevent waiting forever for such events, just send the key to the currently focused window
741 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
742 ALOGD("Received a new pointer down event, stop waiting for events to process and "
743 "just send the pending key event to the focused window.");
744 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700745 }
746 return false;
747}
748
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700750 bool needWake = mInboundQueue.empty();
751 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 traceInboundQueueLengthLocked();
753
754 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700755 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 // Optimize app switch latency.
757 // If the application takes too long to catch up then we drop all events preceding
758 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700759 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700760 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700761 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700762 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700763 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700768 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 mAppSwitchSawKeyDown = false;
770 needWake = true;
771 }
772 }
773 }
774 break;
775 }
776
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700777 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700778 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
779 mNextUnblockedEvent = entry;
780 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100784 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700785 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
786 break;
787 }
788 case EventEntry::Type::CONFIGURATION_CHANGED:
789 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700790 // nothing to do
791 break;
792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 }
794
795 return needWake;
796}
797
798void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
799 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700800 mRecentQueue.push_back(entry);
801 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
802 mRecentQueue.front()->release();
803 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
805}
806
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700808 int32_t y, TouchState* touchState,
809 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700810 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700811 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
812 LOG_ALWAYS_FATAL(
813 "Must provide a valid touch state if adding portal windows or outside targets");
814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700816 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800817 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 const InputWindowInfo* windowInfo = windowHandle->getInfo();
819 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100820 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821
822 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100823 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
824 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
825 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800827 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 if (portalToDisplayId != ADISPLAY_ID_NONE &&
829 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800830 if (addPortalWindows) {
831 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700832 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800833 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700834 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 // Found window.
838 return windowHandle;
839 }
840 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800841
Michael Wright44753b12020-07-08 13:48:11 +0100842 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700843 touchState->addOrUpdateWindow(windowHandle,
844 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
845 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 }
849 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700850 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
Garfield Tane84e6f92019-08-29 17:28:41 -0700853std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700854 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000855 std::vector<TouchedMonitor> touchedMonitors;
856
857 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
858 addGestureMonitors(monitors, touchedMonitors);
859 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
860 const InputWindowInfo* windowInfo = portalWindow->getInfo();
861 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
863 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000864 }
865 return touchedMonitors;
866}
867
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700868void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 const char* reason;
870 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 reason = "inbound event was dropped because the policy consumed it";
876 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 case DropReason::DISABLED:
878 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 ALOGI("Dropped event because input dispatch is disabled.");
880 }
881 reason = "inbound event was dropped because input dispatch is disabled";
882 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because of pending overdue app switch.");
885 reason = "inbound event was dropped because of pending overdue app switch";
886 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 ALOGI("Dropped event because the current application is not responding and the user "
889 "has started interacting with a different application.");
890 reason = "inbound event was dropped because the current application is not responding "
891 "and the user has started interacting with a different application";
892 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 ALOGI("Dropped event because it is stale.");
895 reason = "inbound event was dropped because it is stale";
896 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 case DropReason::NOT_DROPPED: {
898 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700904 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
906 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700909 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700910 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
911 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
913 synthesizeCancelationEventsForAllConnectionsLocked(options);
914 } else {
915 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
916 synthesizeCancelationEventsForAllConnectionsLocked(options);
917 }
918 break;
919 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100920 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700921 case EventEntry::Type::CONFIGURATION_CHANGED:
922 case EventEntry::Type::DEVICE_RESET: {
923 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927}
928
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800929static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
931 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932}
933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700934bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
935 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
936 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
937 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938}
939
940bool InputDispatcher::isAppSwitchPendingLocked() {
941 return mAppSwitchDueTime != LONG_LONG_MAX;
942}
943
944void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
945 mAppSwitchDueTime = LONG_LONG_MAX;
946
947#if DEBUG_APP_SWITCH
948 if (handled) {
949 ALOGD("App switch has arrived.");
950 } else {
951 ALOGD("App switch was abandoned.");
952 }
953#endif
954}
955
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700957 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
960bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700961 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 return false;
963 }
964
965 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700966 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700969 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970
971 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700972 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 return true;
974}
975
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700976void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
977 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978}
979
980void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700981 while (!mInboundQueue.empty()) {
982 EventEntry* entry = mInboundQueue.front();
983 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 releaseInboundEventLocked(entry);
985 }
986 traceInboundQueueLengthLocked();
987}
988
989void InputDispatcher::releasePendingEventLocked() {
990 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700992 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
994}
995
996void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
997 InjectionState* injectionState = entry->injectionState;
998 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
999#if DEBUG_DISPATCH_CYCLE
1000 ALOGD("Injected inbound event was dropped.");
1001#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001002 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
1004 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
1007 addRecentEventLocked(entry);
1008 entry->release();
1009}
1010
1011void InputDispatcher::resetKeyRepeatLocked() {
1012 if (mKeyRepeatState.lastKeyEntry) {
1013 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001014 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016}
1017
Garfield Tane84e6f92019-08-29 17:28:41 -07001018KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1020
1021 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001022 uint32_t policyFlags = entry->policyFlags &
1023 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 if (entry->refCount == 1) {
1025 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001026 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 entry->eventTime = currentTime;
1028 entry->policyFlags = policyFlags;
1029 entry->repeatCount += 1;
1030 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001032 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001033 entry->displayId, policyFlags, entry->action, entry->flags,
1034 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
1037 mKeyRepeatState.lastKeyEntry = newEntry;
1038 entry->release();
1039
1040 entry = newEntry;
1041 }
1042 entry->syntheticRepeat = true;
1043
1044 // Increment reference count since we keep a reference to the event in
1045 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1046 entry->refCount += 1;
1047
1048 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1049 return entry;
1050}
1051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1053 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001055 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056#endif
1057
1058 // Reset key repeating in case a keyboard device was added or removed or something.
1059 resetKeyRepeatLocked();
1060
1061 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001062 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1063 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001065 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 return true;
1067}
1068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001071 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073#endif
1074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 options.deviceId = entry->deviceId;
1077 synthesizeCancelationEventsForAllConnectionsLocked(options);
1078 return true;
1079}
1080
Vishnu Nairad321cd2020-08-20 16:40:21 -07001081void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001082 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001083 if (mPendingEvent != nullptr) {
1084 // Move the pending event to the front of the queue. This will give the chance
1085 // for the pending event to get dispatched to the newly focused window
1086 mInboundQueue.push_front(mPendingEvent);
1087 mPendingEvent = nullptr;
1088 }
1089
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001090 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001091 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001092
1093 // This event should go to the front of the queue, but behind all other focus events
1094 // Find the last focus event, and insert right after it
1095 std::deque<EventEntry*>::reverse_iterator it =
1096 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1097 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1098
1099 // Maintain the order of focus events. Insert the entry after all other focus events.
1100 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001101}
1102
1103void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001104 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001105 if (channel == nullptr) {
1106 return; // Window has gone away
1107 }
1108 InputTarget target;
1109 target.inputChannel = channel;
1110 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1111 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001112 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1113 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001114 std::string reason = std::string("reason=").append(entry->reason);
1115 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001116 dispatchEventLocked(currentTime, entry, {target});
1117}
1118
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 if (!entry->dispatchInProgress) {
1123 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1124 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1125 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1126 if (mKeyRepeatState.lastKeyEntry &&
1127 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 // We have seen two identical key downs in a row which indicates that the device
1129 // driver is automatically generating key repeats itself. We take note of the
1130 // repeat here, but we disable our own next key repeat timer since it is clear that
1131 // we will not need to synthesize key repeats ourselves.
1132 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1133 resetKeyRepeatLocked();
1134 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1135 } else {
1136 // Not a repeat. Save key down state in case we do see a repeat later.
1137 resetKeyRepeatLocked();
1138 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1139 }
1140 mKeyRepeatState.lastKeyEntry = entry;
1141 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 resetKeyRepeatLocked();
1144 }
1145
1146 if (entry->repeatCount == 1) {
1147 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1148 } else {
1149 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1150 }
1151
1152 entry->dispatchInProgress = true;
1153
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001154 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156
1157 // Handle case where the policy asked us to try again later last time.
1158 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1159 if (currentTime < entry->interceptKeyWakeupTime) {
1160 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1161 *nextWakeupTime = entry->interceptKeyWakeupTime;
1162 }
1163 return false; // wait until next wakeup
1164 }
1165 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1166 entry->interceptKeyWakeupTime = 0;
1167 }
1168
1169 // Give the policy a chance to intercept the key.
1170 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1171 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001172 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001173 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001174 sp<IBinder> focusedWindowToken =
1175 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1176 if (focusedWindowToken != nullptr) {
1177 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 }
1179 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001180 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 entry->refCount += 1;
1182 return false; // wait for the command to run
1183 } else {
1184 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1185 }
1186 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 if (*dropReason == DropReason::NOT_DROPPED) {
1188 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
1190 }
1191
1192 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001193 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001195 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001197 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 return true;
1199 }
1200
1201 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001202 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001204 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1206 return false;
1207 }
1208
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001209 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1211 return true;
1212 }
1213
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001214 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001215 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216
1217 // Dispatch the key.
1218 dispatchEventLocked(currentTime, entry, inputTargets);
1219 return true;
1220}
1221
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001222void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001224 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1226 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001227 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1228 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1229 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230#endif
1231}
1232
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1234 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001235 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 entry->dispatchInProgress = true;
1239
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001240 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 }
1242
1243 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001244 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001246 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 return true;
1249 }
1250
1251 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1252
1253 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001254 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255
1256 bool conflictingPointerActions = false;
1257 int32_t injectionResult;
1258 if (isPointerEvent) {
1259 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001261 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 } else {
1264 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001266 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1269 return false;
1270 }
1271
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001272 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001273 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1274 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1275 return true;
1276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001278 CancelationOptions::Mode mode(isPointerEvent
1279 ? CancelationOptions::CANCEL_POINTER_EVENTS
1280 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1281 CancelationOptions options(mode, "input event injection failed");
1282 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 return true;
1284 }
1285
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001286 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001287 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001289 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001290 std::unordered_map<int32_t, TouchState>::iterator it =
1291 mTouchStatesByDisplay.find(entry->displayId);
1292 if (it != mTouchStatesByDisplay.end()) {
1293 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001294 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001295 // The event has gone through these portal windows, so we add monitoring targets of
1296 // the corresponding displays as well.
1297 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001298 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001299 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001301 }
1302 }
1303 }
1304 }
1305
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 // Dispatch the motion.
1307 if (conflictingPointerActions) {
1308 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 synthesizeCancelationEventsForAllConnectionsLocked(options);
1311 }
1312 dispatchEventLocked(currentTime, entry, inputTargets);
1313 return true;
1314}
1315
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001316void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001318 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001319 ", policyFlags=0x%x, "
1320 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1321 "metaState=0x%x, buttonState=0x%x,"
1322 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001323 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1324 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1325 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001327 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329 "x=%f, y=%f, pressure=%f, size=%f, "
1330 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1331 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001332 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1338 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1339 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1340 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1341 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 }
1343#endif
1344}
1345
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001346void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1347 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001348 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349#if DEBUG_DISPATCH_CYCLE
1350 ALOGD("dispatchEventToCurrentInputTargets");
1351#endif
1352
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001353 updateInteractionTokensLocked(*eventEntry, inputTargets);
1354
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1356
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001359 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001360 sp<Connection> connection =
1361 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001362 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001363 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001365 if (DEBUG_FOCUS) {
1366 ALOGD("Dropping event delivery to target with channel '%s' because it "
1367 "is no longer registered with the input dispatcher.",
1368 inputTarget.inputChannel->getName().c_str());
1369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 }
1371 }
1372}
1373
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001374void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1375 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1376 // If the policy decides to close the app, we will get a channel removal event via
1377 // unregisterInputChannel, and will clean up the connection that way. We are already not
1378 // sending new pointers to the connection when it blocked, but focused events will continue to
1379 // pile up.
1380 ALOGW("Canceling events for %s because it is unresponsive",
1381 connection->inputChannel->getName().c_str());
1382 if (connection->status == Connection::STATUS_NORMAL) {
1383 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1384 "application not responding");
1385 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 }
1387}
1388
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001389void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001390 if (DEBUG_FOCUS) {
1391 ALOGD("Resetting ANR timeouts.");
1392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
1394 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001395 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001396 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397}
1398
Tiger Huang721e26f2018-07-24 22:26:19 +08001399/**
1400 * Get the display id that the given event should go to. If this event specifies a valid display id,
1401 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1402 * Focused display is the display that the user most recently interacted with.
1403 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001405 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001406 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001407 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001408 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1409 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001410 break;
1411 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001413 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1414 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 break;
1416 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001417 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001418 case EventEntry::Type::CONFIGURATION_CHANGED:
1419 case EventEntry::Type::DEVICE_RESET: {
1420 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001421 return ADISPLAY_ID_NONE;
1422 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001423 }
1424 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1425}
1426
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001427bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1428 const char* focusedWindowName) {
1429 if (mAnrTracker.empty()) {
1430 // already processed all events that we waited for
1431 mKeyIsWaitingForEventsTimeout = std::nullopt;
1432 return false;
1433 }
1434
1435 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1436 // Start the timer
1437 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1438 "focus to change",
1439 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001440 mKeyIsWaitingForEventsTimeout = currentTime +
1441 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1442 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001443 return true;
1444 }
1445
1446 // We still have pending events, and already started the timer
1447 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1448 return true; // Still waiting
1449 }
1450
1451 // Waited too long, and some connection still hasn't processed all motions
1452 // Just send the key to the focused window
1453 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1454 focusedWindowName);
1455 mKeyIsWaitingForEventsTimeout = std::nullopt;
1456 return false;
1457}
1458
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001460 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001461 std::vector<InputTarget>& inputTargets,
1462 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001463 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464
Tiger Huang721e26f2018-07-24 22:26:19 +08001465 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001466 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001467 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001468 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1469
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 // If there is no currently focused window and no focused application
1471 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001472 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1473 ALOGI("Dropping %s event because there is no focused window or focused application in "
1474 "display %" PRId32 ".",
1475 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001476 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 }
1478
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001479 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1480 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1481 // start interacting with another application via touch (app switch). This code can be removed
1482 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1483 // an app is expected to have a focused window.
1484 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1485 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1486 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001487 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1488 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1489 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001490 mAwaitedFocusedApplication = focusedApplicationHandle;
1491 ALOGW("Waiting because no window has focus but %s may eventually add a "
1492 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001493 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001494 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1495 return INPUT_EVENT_INJECTION_PENDING;
1496 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1497 // Already raised ANR. Drop the event
1498 ALOGE("Dropping %s event because there is no focused window",
1499 EventEntry::typeToString(entry.type));
1500 return INPUT_EVENT_INJECTION_FAILED;
1501 } else {
1502 // Still waiting for the focused window
1503 return INPUT_EVENT_INJECTION_PENDING;
1504 }
1505 }
1506
1507 // we have a valid, non-null focused window
1508 resetNoFocusedWindowTimeoutLocked();
1509
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001511 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001512 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 }
1514
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001515 if (focusedWindowHandle->getInfo()->paused) {
1516 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1517 return INPUT_EVENT_INJECTION_PENDING;
1518 }
1519
1520 // If the event is a key event, then we must wait for all previous events to
1521 // complete before delivering it because previous events may have the
1522 // side-effect of transferring focus to a different window and we want to
1523 // ensure that the following keys are sent to the new window.
1524 //
1525 // Suppose the user touches a button in a window then immediately presses "A".
1526 // If the button causes a pop-up window to appear then we want to ensure that
1527 // the "A" key is delivered to the new pop-up window. This is because users
1528 // often anticipate pending UI changes when typing on a keyboard.
1529 // To obtain this behavior, we must serialize key events with respect to all
1530 // prior input events.
1531 if (entry.type == EventEntry::Type::KEY) {
1532 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1533 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1534 return INPUT_EVENT_INJECTION_PENDING;
1535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 }
1537
1538 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001539 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001540 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1541 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542
1543 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001544 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545}
1546
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001547/**
1548 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1549 * that are currently unresponsive.
1550 */
1551std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1552 const std::vector<TouchedMonitor>& monitors) const {
1553 std::vector<TouchedMonitor> responsiveMonitors;
1554 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1555 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1556 sp<Connection> connection = getConnectionLocked(
1557 monitor.monitor.inputChannel->getConnectionToken());
1558 if (connection == nullptr) {
1559 ALOGE("Could not find connection for monitor %s",
1560 monitor.monitor.inputChannel->getName().c_str());
1561 return false;
1562 }
1563 if (!connection->responsive) {
1564 ALOGW("Unresponsive monitor %s will not get the new gesture",
1565 connection->inputChannel->getName().c_str());
1566 return false;
1567 }
1568 return true;
1569 });
1570 return responsiveMonitors;
1571}
1572
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001574 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001575 std::vector<InputTarget>& inputTargets,
1576 nsecs_t* nextWakeupTime,
1577 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001578 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 enum InjectionPermission {
1580 INJECTION_PERMISSION_UNKNOWN,
1581 INJECTION_PERMISSION_GRANTED,
1582 INJECTION_PERMISSION_DENIED
1583 };
1584
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 // For security reasons, we defer updating the touch state until we are sure that
1586 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001587 int32_t displayId = entry.displayId;
1588 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1590
1591 // Update the touch state as needed based on the properties of the touch event.
1592 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1593 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001594 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1595 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001597 // Copy current touch state into tempTouchState.
1598 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1599 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001600 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001601 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001602 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1603 mTouchStatesByDisplay.find(displayId);
1604 if (oldStateIt != mTouchStatesByDisplay.end()) {
1605 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001606 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001607 }
1608
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001609 bool isSplit = tempTouchState.split;
1610 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1611 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1612 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001613 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1614 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1615 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1616 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1617 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001618 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 bool wrongDevice = false;
1620 if (newGesture) {
1621 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001622 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001623 ALOGI("Dropping event because a pointer for a different device is already down "
1624 "in display %" PRId32,
1625 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001626 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1628 switchedDevice = false;
1629 wrongDevice = true;
1630 goto Failed;
1631 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001632 tempTouchState.reset();
1633 tempTouchState.down = down;
1634 tempTouchState.deviceId = entry.deviceId;
1635 tempTouchState.source = entry.source;
1636 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001638 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001639 ALOGI("Dropping move event because a pointer for a different device is already active "
1640 "in display %" PRId32,
1641 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001642 // TODO: test multiple simultaneous input streams.
1643 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1644 switchedDevice = false;
1645 wrongDevice = true;
1646 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 }
1648
1649 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1650 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1651
Garfield Tan00f511d2019-06-12 16:55:40 -07001652 int32_t x;
1653 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001655 // Always dispatch mouse events to cursor position.
1656 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 x = int32_t(entry.xCursorPosition);
1658 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001659 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001660 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1661 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001662 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001664 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001665 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1666 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001667
1668 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001669 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001670 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 if (newTouchedWindowHandle != nullptr &&
1674 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001675 // New window supports splitting, but we should never split mouse events.
1676 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 } else if (isSplit) {
1678 // New window does not support splitting but we have already split events.
1679 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001680 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 }
1682
1683 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001684 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001686 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001687 }
1688
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001689 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1690 ALOGI("Not sending touch event to %s because it is paused",
1691 newTouchedWindowHandle->getName().c_str());
1692 newTouchedWindowHandle = nullptr;
1693 }
1694
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001695 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001696 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001697 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1698 if (!isResponsive) {
1699 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001700 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1701 newTouchedWindowHandle = nullptr;
1702 }
1703 }
1704
1705 // Also don't send the new touch event to unresponsive gesture monitors
1706 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1707
Michael Wright3dd60e22019-03-27 22:06:44 +00001708 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1709 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 "(%d, %d) in display %" PRId32 ".",
1711 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001712 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1713 goto Failed;
1714 }
1715
1716 if (newTouchedWindowHandle != nullptr) {
1717 // Set target flags.
1718 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1719 if (isSplit) {
1720 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001722 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1723 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1724 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1725 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1726 }
1727
1728 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001729 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1730 newHoverWindowHandle = nullptr;
1731 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001732 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001733 }
1734
1735 // Update the temporary touch state.
1736 BitSet32 pointerIds;
1737 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001738 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001739 pointerIds.markBit(pointerId);
1740 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001741 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
1743
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001744 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 } else {
1746 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1747
1748 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001749 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001750 if (DEBUG_FOCUS) {
1751 ALOGD("Dropping event because the pointer is not down or we previously "
1752 "dropped the pointer down event in display %" PRId32,
1753 displayId);
1754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1756 goto Failed;
1757 }
1758
1759 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001760 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001761 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001762 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1763 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764
1765 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001766 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001767 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001768 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1769 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001770 if (DEBUG_FOCUS) {
1771 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1772 oldTouchedWindowHandle->getName().c_str(),
1773 newTouchedWindowHandle->getName().c_str(), displayId);
1774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001776 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1777 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1778 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779
1780 // Make a slippery entrance into the new window.
1781 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1782 isSplit = true;
1783 }
1784
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001785 int32_t targetFlags =
1786 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 if (isSplit) {
1788 targetFlags |= InputTarget::FLAG_SPLIT;
1789 }
1790 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1791 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1792 }
1793
1794 BitSet32 pointerIds;
1795 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001798 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800 }
1801 }
1802
1803 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001804 // Let the previous window know that the hover sequence is over, unless we already did it
1805 // when dispatching it as is to newTouchedWindowHandle.
1806 if (mLastHoverWindowHandle != nullptr &&
1807 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1808 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809#if DEBUG_HOVER
1810 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001811 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001813 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1814 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 }
1816
Garfield Tandf26e862020-07-01 20:18:19 -07001817 // Let the new window know that the hover sequence is starting, unless we already did it
1818 // when dispatching it as is to newTouchedWindowHandle.
1819 if (newHoverWindowHandle != nullptr &&
1820 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1821 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822#if DEBUG_HOVER
1823 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001824 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001826 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1827 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1828 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 }
1830 }
1831
1832 // Check permission to inject into all touched foreground windows and ensure there
1833 // is at least one touched foreground window.
1834 {
1835 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001836 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1838 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001839 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1841 injectionPermission = INJECTION_PERMISSION_DENIED;
1842 goto Failed;
1843 }
1844 }
1845 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001846 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001847 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001848 ALOGI("Dropping event because there is no touched foreground window in display "
1849 "%" PRId32 " or gesture monitor to receive it.",
1850 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1852 goto Failed;
1853 }
1854
1855 // Permission granted to injection into all touched foreground windows.
1856 injectionPermission = INJECTION_PERMISSION_GRANTED;
1857 }
1858
1859 // Check whether windows listening for outside touches are owned by the same UID. If it is
1860 // set the policy flag that we will not reveal coordinate information to this window.
1861 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1862 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001863 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001864 if (foregroundWindowHandle) {
1865 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001866 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001867 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1868 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1869 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001870 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1871 InputTarget::FLAG_ZERO_COORDS,
1872 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 }
1875 }
1876 }
1877 }
1878
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 // If this is the first pointer going down and the touched window has a wallpaper
1880 // then also add the touched wallpaper windows so they are locked in for the duration
1881 // of the touch gesture.
1882 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1883 // engine only supports touch events. We would need to add a mechanism similar
1884 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1885 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1886 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001887 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001888 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001889 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001890 getWindowHandlesLocked(displayId);
1891 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001894 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001895 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001896 .addOrUpdateWindow(windowHandle,
1897 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1898 InputTarget::
1899 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1900 InputTarget::FLAG_DISPATCH_AS_IS,
1901 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 }
1903 }
1904 }
1905 }
1906
1907 // Success! Output targets.
1908 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1909
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001910 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001912 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 }
1914
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001915 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001917 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001918 }
1919
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 // Drop the outside or hover touch windows since we will not care about them
1921 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001922 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923
1924Failed:
1925 // Check injection permission once and for all.
1926 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001927 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 injectionPermission = INJECTION_PERMISSION_GRANTED;
1929 } else {
1930 injectionPermission = INJECTION_PERMISSION_DENIED;
1931 }
1932 }
1933
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001934 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1935 return injectionResult;
1936 }
1937
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001939 if (!wrongDevice) {
1940 if (switchedDevice) {
1941 if (DEBUG_FOCUS) {
1942 ALOGD("Conflicting pointer actions: Switched to a different device.");
1943 }
1944 *outConflictingPointerActions = true;
1945 }
1946
1947 if (isHoverAction) {
1948 // Started hovering, therefore no longer down.
1949 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001950 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001951 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1952 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 *outConflictingPointerActions = true;
1955 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001956 tempTouchState.reset();
1957 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1958 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1959 tempTouchState.deviceId = entry.deviceId;
1960 tempTouchState.source = entry.source;
1961 tempTouchState.displayId = displayId;
1962 }
1963 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1964 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1965 // All pointers up or canceled.
1966 tempTouchState.reset();
1967 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1968 // First pointer went down.
1969 if (oldState && oldState->down) {
1970 if (DEBUG_FOCUS) {
1971 ALOGD("Conflicting pointer actions: Down received while already down.");
1972 }
1973 *outConflictingPointerActions = true;
1974 }
1975 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1976 // One pointer went up.
1977 if (isSplit) {
1978 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1979 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001981 for (size_t i = 0; i < tempTouchState.windows.size();) {
1982 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1983 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1984 touchedWindow.pointerIds.clearBit(pointerId);
1985 if (touchedWindow.pointerIds.isEmpty()) {
1986 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1987 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001992 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001993 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001994
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001995 // Save changes unless the action was scroll in which case the temporary touch
1996 // state was only valid for this one action.
1997 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1998 if (tempTouchState.displayId >= 0) {
1999 mTouchStatesByDisplay[displayId] = tempTouchState;
2000 } else {
2001 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002005 // Update hover state.
2006 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
2008
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 return injectionResult;
2010}
2011
2012void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002013 int32_t targetFlags, BitSet32 pointerIds,
2014 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002015 std::vector<InputTarget>::iterator it =
2016 std::find_if(inputTargets.begin(), inputTargets.end(),
2017 [&windowHandle](const InputTarget& inputTarget) {
2018 return inputTarget.inputChannel->getConnectionToken() ==
2019 windowHandle->getToken();
2020 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002021
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002022 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002023
2024 if (it == inputTargets.end()) {
2025 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002026 std::shared_ptr<InputChannel> inputChannel =
2027 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002028 if (inputChannel == nullptr) {
2029 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2030 return;
2031 }
2032 inputTarget.inputChannel = inputChannel;
2033 inputTarget.flags = targetFlags;
2034 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2035 inputTargets.push_back(inputTarget);
2036 it = inputTargets.end() - 1;
2037 }
2038
2039 ALOG_ASSERT(it->flags == targetFlags);
2040 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2041
chaviw1ff3d1e2020-07-01 15:53:47 -07002042 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043}
2044
Michael Wright3dd60e22019-03-27 22:06:44 +00002045void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046 int32_t displayId, float xOffset,
2047 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002048 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2049 mGlobalMonitorsByDisplay.find(displayId);
2050
2051 if (it != mGlobalMonitorsByDisplay.end()) {
2052 const std::vector<Monitor>& monitors = it->second;
2053 for (const Monitor& monitor : monitors) {
2054 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 }
2057}
2058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002059void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2060 float yOffset,
2061 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 InputTarget target;
2063 target.inputChannel = monitor.inputChannel;
2064 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002065 ui::Transform t;
2066 t.set(xOffset, yOffset);
2067 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002068 inputTargets.push_back(target);
2069}
2070
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002072 const InjectionState* injectionState) {
2073 if (injectionState &&
2074 (windowHandle == nullptr ||
2075 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2076 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002077 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002079 "owned by uid %d",
2080 injectionState->injectorPid, injectionState->injectorUid,
2081 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 } else {
2083 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002084 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 }
2086 return false;
2087 }
2088 return true;
2089}
2090
Robert Carrc9bf1d32020-04-13 17:21:08 -07002091/**
2092 * Indicate whether one window handle should be considered as obscuring
2093 * another window handle. We only check a few preconditions. Actually
2094 * checking the bounds is left to the caller.
2095 */
2096static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2097 const sp<InputWindowHandle>& otherHandle) {
2098 // Compare by token so cloned layers aren't counted
2099 if (haveSameToken(windowHandle, otherHandle)) {
2100 return false;
2101 }
2102 auto info = windowHandle->getInfo();
2103 auto otherInfo = otherHandle->getInfo();
2104 if (!otherInfo->visible) {
2105 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002106 } else if (info->ownerPid == otherInfo->ownerPid) {
2107 // If ownerPid is the same we don't generate occlusion events as there
2108 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002109 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002110 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002111 return false;
2112 } else if (otherInfo->displayId != info->displayId) {
2113 return false;
2114 }
2115 return true;
2116}
2117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002118bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2119 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002121 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002122 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002123 if (windowHandle == otherHandle) {
2124 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002127 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002128 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 return true;
2130 }
2131 }
2132 return false;
2133}
2134
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002135bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2136 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002137 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002138 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002139 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002140 if (windowHandle == otherHandle) {
2141 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002142 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002143 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002144 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002145 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002146 return true;
2147 }
2148 }
2149 return false;
2150}
2151
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002152std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002153 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002155 if (applicationHandle != nullptr) {
2156 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002157 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 } else {
2159 return applicationHandle->getName();
2160 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002161 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002162 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002164 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166}
2167
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002168void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002169 if (eventEntry.type == EventEntry::Type::FOCUS) {
2170 // Focus events are passed to apps, but do not represent user activity.
2171 return;
2172 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002173 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002174 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002175 if (focusedWindowHandle != nullptr) {
2176 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002177 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002179 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180#endif
2181 return;
2182 }
2183 }
2184
2185 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002186 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002187 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002188 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2189 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002190 return;
2191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002193 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002194 eventType = USER_ACTIVITY_EVENT_TOUCH;
2195 }
2196 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002198 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002199 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2200 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002201 return;
2202 }
2203 eventType = USER_ACTIVITY_EVENT_BUTTON;
2204 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002206 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002207 case EventEntry::Type::CONFIGURATION_CHANGED:
2208 case EventEntry::Type::DEVICE_RESET: {
2209 LOG_ALWAYS_FATAL("%s events are not user activity",
2210 EventEntry::typeToString(eventEntry.type));
2211 break;
2212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
2214
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002215 std::unique_ptr<CommandEntry> commandEntry =
2216 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002217 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002219 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220}
2221
2222void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 const sp<Connection>& connection,
2224 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002225 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002226 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002227 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002228 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002229 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 ATRACE_NAME(message.c_str());
2231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232#if DEBUG_DISPATCH_CYCLE
2233 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002234 "globalScaleFactor=%f, pointerIds=0x%x %s",
2235 connection->getInputChannelName().c_str(), inputTarget.flags,
2236 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2237 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238#endif
2239
2240 // Skip this event if the connection status is not normal.
2241 // We don't want to enqueue additional outbound events if the connection is broken.
2242 if (connection->status != Connection::STATUS_NORMAL) {
2243#if DEBUG_DISPATCH_CYCLE
2244 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002245 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246#endif
2247 return;
2248 }
2249
2250 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002251 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2252 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2253 "Entry type %s should not have FLAG_SPLIT",
2254 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002256 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002257 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002259 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 if (!splitMotionEntry) {
2261 return; // split event was dropped
2262 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002263 if (DEBUG_FOCUS) {
2264 ALOGD("channel '%s' ~ Split motion event.",
2265 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002266 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002267 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002268 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 splitMotionEntry->release();
2270 return;
2271 }
2272 }
2273
2274 // Not splitting. Enqueue dispatch entries for the event as is.
2275 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2276}
2277
2278void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 const sp<Connection>& connection,
2280 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002281 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002284 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002285 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002286 ATRACE_NAME(message.c_str());
2287 }
2288
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002289 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290
2291 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002300 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002302 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002303 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304
2305 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002306 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 startDispatchCycleLocked(currentTime, connection);
2308 }
2309}
2310
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2312 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002313 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002314 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002315 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002316 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2317 connection->getInputChannelName().c_str(),
2318 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002319 ATRACE_NAME(message.c_str());
2320 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002321 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 if (!(inputTargetFlags & dispatchMode)) {
2323 return;
2324 }
2325 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2326
2327 // This is a new event.
2328 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002329 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002330 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2333 // different EventEntry than what was passed in.
2334 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002336 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002337 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002338 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002339 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002340 dispatchEntry->resolvedAction = keyEntry.action;
2341 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002343 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2344 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2347 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 return; // skip the inconsistent event
2350 }
2351 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002354 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002355 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002356 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2357 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2358 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2359 static_cast<int32_t>(IdGenerator::Source::OTHER);
2360 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002361 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2367 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2368 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2369 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2370 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2371 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002373 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374 }
2375 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002376 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2377 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2380 "event",
2381 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002386 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2388 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2389 }
2390 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2391 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002394 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2395 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2398 "event",
2399 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002401 return; // skip the inconsistent event
2402 }
2403
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002404 dispatchEntry->resolvedEventId =
2405 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2406 ? mIdGenerator.nextId()
2407 : motionEntry.id;
2408 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2409 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2410 ") to MotionEvent(id=0x%" PRIx32 ").",
2411 motionEntry.id, dispatchEntry->resolvedEventId);
2412 ATRACE_NAME(message.c_str());
2413 }
2414
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002415 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002416 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417
2418 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002420 case EventEntry::Type::FOCUS: {
2421 break;
2422 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002423 case EventEntry::Type::CONFIGURATION_CHANGED:
2424 case EventEntry::Type::DEVICE_RESET: {
2425 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002426 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002427 break;
2428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 }
2430
2431 // Remember that we are waiting for this dispatch to complete.
2432 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002433 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
2435
2436 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002437 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002438 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002439}
2440
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002441/**
2442 * This function is purely for debugging. It helps us understand where the user interaction
2443 * was taking place. For example, if user is touching launcher, we will see a log that user
2444 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2445 * We will see both launcher and wallpaper in that list.
2446 * Once the interaction with a particular set of connections starts, no new logs will be printed
2447 * until the set of interacted connections changes.
2448 *
2449 * The following items are skipped, to reduce the logspam:
2450 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2451 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2452 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2453 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2454 * Both of those ACTION_UP events would not be logged
2455 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2456 * will not be logged. This is omitted to reduce the amount of data printed.
2457 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2458 * gesture monitor is the only connection receiving the remainder of the gesture.
2459 */
2460void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2461 const std::vector<InputTarget>& targets) {
2462 // Skip ACTION_UP events, and all events other than keys and motions
2463 if (entry.type == EventEntry::Type::KEY) {
2464 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2465 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2466 return;
2467 }
2468 } else if (entry.type == EventEntry::Type::MOTION) {
2469 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2470 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2471 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2472 return;
2473 }
2474 } else {
2475 return; // Not a key or a motion
2476 }
2477
2478 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2479 std::vector<sp<Connection>> newConnections;
2480 for (const InputTarget& target : targets) {
2481 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2482 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2483 continue; // Skip windows that receive ACTION_OUTSIDE
2484 }
2485
2486 sp<IBinder> token = target.inputChannel->getConnectionToken();
2487 sp<Connection> connection = getConnectionLocked(token);
2488 if (connection == nullptr || connection->monitor) {
2489 continue; // We only need to keep track of the non-monitor connections.
2490 }
2491 newConnectionTokens.insert(std::move(token));
2492 newConnections.emplace_back(connection);
2493 }
2494 if (newConnectionTokens == mInteractionConnectionTokens) {
2495 return; // no change
2496 }
2497 mInteractionConnectionTokens = newConnectionTokens;
2498
2499 std::string windowList;
2500 for (const sp<Connection>& connection : newConnections) {
2501 windowList += connection->getWindowName() + ", ";
2502 }
2503 std::string message = "Interaction with windows: " + windowList;
2504 if (windowList.empty()) {
2505 message += "<none>";
2506 }
2507 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2508}
2509
chaviwfd6d3512019-03-25 13:23:49 -07002510void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002511 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002512 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002513 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2514 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002515 return;
2516 }
2517
Vishnu Nairad321cd2020-08-20 16:40:21 -07002518 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2519 if (focusedToken == token) {
2520 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002521 return;
2522 }
2523
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002524 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2525 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002526 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002527 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528}
2529
2530void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002532 if (ATRACE_ENABLED()) {
2533 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002535 ATRACE_NAME(message.c_str());
2536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002538 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539#endif
2540
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002541 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2542 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002544 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002545 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002546 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547
2548 // Publish the event.
2549 status_t status;
2550 EventEntry* eventEntry = dispatchEntry->eventEntry;
2551 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002552 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002553 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2554 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002557 status =
2558 connection->inputPublisher
2559 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2560 keyEntry->deviceId, keyEntry->source,
2561 keyEntry->displayId, std::move(hmac),
2562 dispatchEntry->resolvedAction,
2563 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2564 keyEntry->scanCode, keyEntry->metaState,
2565 keyEntry->repeatCount, keyEntry->downTime,
2566 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
2569
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002570 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 PointerCoords scaledCoords[MAX_POINTERS];
2574 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2575
chaviw82357092020-01-28 13:13:06 -08002576 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2578 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2579 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002580 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2582 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002583 // Don't apply window scale here since we don't want scale to affect raw
2584 // coordinates. The scale will be sent back to the client and applied
2585 // later when requesting relative coordinates.
2586 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2587 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 }
2589 usingCoords = scaledCoords;
2590 }
2591 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 // We don't want the dispatch target to know.
2593 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2594 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2595 scaledCoords[i].clear();
2596 }
2597 usingCoords = scaledCoords;
2598 }
2599 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002600
2601 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002602
2603 // Publish the motion event.
2604 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002605 .publishMotionEvent(dispatchEntry->seq,
2606 dispatchEntry->resolvedEventId,
2607 motionEntry->deviceId, motionEntry->source,
2608 motionEntry->displayId, std::move(hmac),
2609 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002610 motionEntry->actionButton,
2611 dispatchEntry->resolvedFlags,
2612 motionEntry->edgeFlags, motionEntry->metaState,
2613 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002614 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002615 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002616 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002617 motionEntry->yPrecision,
2618 motionEntry->xCursorPosition,
2619 motionEntry->yCursorPosition,
2620 motionEntry->downTime, motionEntry->eventTime,
2621 motionEntry->pointerCount,
2622 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002623 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002624 break;
2625 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002626 case EventEntry::Type::FOCUS: {
2627 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2628 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002629 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002630 focusEntry->hasFocus,
2631 mInTouchMode);
2632 break;
2633 }
2634
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002635 case EventEntry::Type::CONFIGURATION_CHANGED:
2636 case EventEntry::Type::DEVICE_RESET: {
2637 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2638 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002639 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 }
2642
2643 // Check the result.
2644 if (status) {
2645 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002646 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002648 "This is unexpected because the wait queue is empty, so the pipe "
2649 "should be empty and we shouldn't have any problems writing an "
2650 "event to it, status=%d",
2651 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2653 } else {
2654 // Pipe is full and we are waiting for the app to finish process some events
2655 // before sending more events to it.
2656#if DEBUG_DISPATCH_CYCLE
2657 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 "waiting for the application to catch up",
2659 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661 }
2662 } else {
2663 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002664 "status=%d",
2665 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2667 }
2668 return;
2669 }
2670
2671 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002672 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2673 connection->outboundQueue.end(),
2674 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002675 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002676 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002677 if (connection->responsive) {
2678 mAnrTracker.insert(dispatchEntry->timeoutTime,
2679 connection->inputChannel->getConnectionToken());
2680 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002681 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
2683}
2684
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002685const std::array<uint8_t, 32> InputDispatcher::getSignature(
2686 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2687 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2688 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2689 // Only sign events up and down events as the purely move events
2690 // are tied to their up/down counterparts so signing would be redundant.
2691 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2692 verifiedEvent.actionMasked = actionMasked;
2693 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2694 return mHmacKeyManager.sign(verifiedEvent);
2695 }
2696 return INVALID_HMAC;
2697}
2698
2699const std::array<uint8_t, 32> InputDispatcher::getSignature(
2700 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2701 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2702 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2703 verifiedEvent.action = dispatchEntry.resolvedAction;
2704 return mHmacKeyManager.sign(verifiedEvent);
2705}
2706
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002708 const sp<Connection>& connection, uint32_t seq,
2709 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710#if DEBUG_DISPATCH_CYCLE
2711 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002712 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713#endif
2714
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002715 if (connection->status == Connection::STATUS_BROKEN ||
2716 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 return;
2718 }
2719
2720 // Notify other system components and prepare to start the next dispatch cycle.
2721 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2722}
2723
2724void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 const sp<Connection>& connection,
2726 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#if DEBUG_DISPATCH_CYCLE
2728 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730#endif
2731
2732 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002733 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002734 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002735 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002736 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737
2738 // The connection appears to be unrecoverably broken.
2739 // Ignore already broken or zombie connections.
2740 if (connection->status == Connection::STATUS_NORMAL) {
2741 connection->status = Connection::STATUS_BROKEN;
2742
2743 if (notify) {
2744 // Notify other system components.
2745 onDispatchCycleBrokenLocked(currentTime, connection);
2746 }
2747 }
2748}
2749
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002750void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2751 while (!queue.empty()) {
2752 DispatchEntry* dispatchEntry = queue.front();
2753 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002754 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
2756}
2757
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002758void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002760 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 }
2762 delete dispatchEntry;
2763}
2764
2765int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2766 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2767
2768 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002769 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002771 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 "fd=%d, events=0x%x",
2774 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 return 0; // remove the callback
2776 }
2777
2778 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002779 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2781 if (!(events & ALOOPER_EVENT_INPUT)) {
2782 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 "events=0x%x",
2784 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 return 1;
2786 }
2787
2788 nsecs_t currentTime = now();
2789 bool gotOne = false;
2790 status_t status;
2791 for (;;) {
2792 uint32_t seq;
2793 bool handled;
2794 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2795 if (status) {
2796 break;
2797 }
2798 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2799 gotOne = true;
2800 }
2801 if (gotOne) {
2802 d->runCommandsLockedInterruptible();
2803 if (status == WOULD_BLOCK) {
2804 return 1;
2805 }
2806 }
2807
2808 notify = status != DEAD_OBJECT || !connection->monitor;
2809 if (notify) {
2810 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002811 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
2813 } else {
2814 // Monitor channels are never explicitly unregistered.
2815 // We do it automatically when the remote endpoint is closed so don't warn
2816 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002817 const bool stillHaveWindowHandle =
2818 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2819 nullptr;
2820 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 if (notify) {
2822 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 "events=0x%x",
2824 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 }
2826 }
2827
2828 // Unregister the channel.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002829 d->unregisterInputChannelLocked(*connection->inputChannel, notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002831 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832}
2833
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002836 for (const auto& pair : mConnectionsByFd) {
2837 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 }
2839}
2840
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002842 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002843 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2844 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2845}
2846
2847void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2848 const CancelationOptions& options,
2849 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2850 for (const auto& it : monitorsByDisplay) {
2851 const std::vector<Monitor>& monitors = it.second;
2852 for (const Monitor& monitor : monitors) {
2853 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002854 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002855 }
2856}
2857
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002859 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002860 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002861 if (connection == nullptr) {
2862 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002864
2865 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866}
2867
2868void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2869 const sp<Connection>& connection, const CancelationOptions& options) {
2870 if (connection->status == Connection::STATUS_BROKEN) {
2871 return;
2872 }
2873
2874 nsecs_t currentTime = now();
2875
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002876 std::vector<EventEntry*> cancelationEvents =
2877 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002879 if (cancelationEvents.empty()) {
2880 return;
2881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002883 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2884 "with reality: %s, mode=%d.",
2885 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2886 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002888
2889 InputTarget target;
2890 sp<InputWindowHandle> windowHandle =
2891 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2892 if (windowHandle != nullptr) {
2893 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002894 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002895 target.globalScaleFactor = windowInfo->globalScaleFactor;
2896 }
2897 target.inputChannel = connection->inputChannel;
2898 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2899
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002900 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2901 EventEntry* cancelationEventEntry = cancelationEvents[i];
2902 switch (cancelationEventEntry->type) {
2903 case EventEntry::Type::KEY: {
2904 logOutboundKeyDetails("cancel - ",
2905 static_cast<const KeyEntry&>(*cancelationEventEntry));
2906 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002908 case EventEntry::Type::MOTION: {
2909 logOutboundMotionDetails("cancel - ",
2910 static_cast<const MotionEntry&>(*cancelationEventEntry));
2911 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002913 case EventEntry::Type::FOCUS: {
2914 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2915 break;
2916 }
2917 case EventEntry::Type::CONFIGURATION_CHANGED:
2918 case EventEntry::Type::DEVICE_RESET: {
2919 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2920 EventEntry::typeToString(cancelationEventEntry->type));
2921 break;
2922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 }
2924
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002925 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2926 target, InputTarget::FLAG_DISPATCH_AS_IS);
2927
2928 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002930
2931 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932}
2933
Svet Ganov5d3bc372020-01-26 23:11:07 -08002934void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2935 const sp<Connection>& connection) {
2936 if (connection->status == Connection::STATUS_BROKEN) {
2937 return;
2938 }
2939
2940 nsecs_t currentTime = now();
2941
2942 std::vector<EventEntry*> downEvents =
2943 connection->inputState.synthesizePointerDownEvents(currentTime);
2944
2945 if (downEvents.empty()) {
2946 return;
2947 }
2948
2949#if DEBUG_OUTBOUND_EVENT_DETAILS
2950 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2951 connection->getInputChannelName().c_str(), downEvents.size());
2952#endif
2953
2954 InputTarget target;
2955 sp<InputWindowHandle> windowHandle =
2956 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2957 if (windowHandle != nullptr) {
2958 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002959 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002960 target.globalScaleFactor = windowInfo->globalScaleFactor;
2961 }
2962 target.inputChannel = connection->inputChannel;
2963 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2964
2965 for (EventEntry* downEventEntry : downEvents) {
2966 switch (downEventEntry->type) {
2967 case EventEntry::Type::MOTION: {
2968 logOutboundMotionDetails("down - ",
2969 static_cast<const MotionEntry&>(*downEventEntry));
2970 break;
2971 }
2972
2973 case EventEntry::Type::KEY:
2974 case EventEntry::Type::FOCUS:
2975 case EventEntry::Type::CONFIGURATION_CHANGED:
2976 case EventEntry::Type::DEVICE_RESET: {
2977 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2978 EventEntry::typeToString(downEventEntry->type));
2979 break;
2980 }
2981 }
2982
2983 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2984 target, InputTarget::FLAG_DISPATCH_AS_IS);
2985
2986 downEventEntry->release();
2987 }
2988
2989 startDispatchCycleLocked(currentTime, connection);
2990}
2991
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002992MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002993 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 ALOG_ASSERT(pointerIds.value != 0);
2995
2996 uint32_t splitPointerIndexMap[MAX_POINTERS];
2997 PointerProperties splitPointerProperties[MAX_POINTERS];
2998 PointerCoords splitPointerCoords[MAX_POINTERS];
2999
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003000 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 uint32_t splitPointerCount = 0;
3002
3003 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 uint32_t pointerId = uint32_t(pointerProperties.id);
3008 if (pointerIds.hasBit(pointerId)) {
3009 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3010 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3011 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 splitPointerCount += 1;
3014 }
3015 }
3016
3017 if (splitPointerCount != pointerIds.count()) {
3018 // This is bad. We are missing some of the pointers that we expected to deliver.
3019 // Most likely this indicates that we received an ACTION_MOVE events that has
3020 // different pointer ids than we expected based on the previous ACTION_DOWN
3021 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3022 // in this way.
3023 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 "we expected there to be %d pointers. This probably means we received "
3025 "a broken sequence of pointer ids from the input device.",
3026 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003027 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 }
3029
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003030 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3033 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3035 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003036 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 uint32_t pointerId = uint32_t(pointerProperties.id);
3038 if (pointerIds.hasBit(pointerId)) {
3039 if (pointerIds.count() == 1) {
3040 // The first/last pointer went down/up.
3041 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 ? AMOTION_EVENT_ACTION_DOWN
3043 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 } else {
3045 // A secondary pointer went down/up.
3046 uint32_t splitPointerIndex = 0;
3047 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3048 splitPointerIndex += 1;
3049 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 action = maskedAction |
3051 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
3053 } else {
3054 // An unrelated pointer changed.
3055 action = AMOTION_EVENT_ACTION_MOVE;
3056 }
3057 }
3058
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003059 int32_t newId = mIdGenerator.nextId();
3060 if (ATRACE_ENABLED()) {
3061 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3062 ") to MotionEvent(id=0x%" PRIx32 ").",
3063 originalMotionEntry.id, newId);
3064 ATRACE_NAME(message.c_str());
3065 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003066 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003067 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3068 originalMotionEntry.source, originalMotionEntry.displayId,
3069 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003070 originalMotionEntry.actionButton, originalMotionEntry.flags,
3071 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3072 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3073 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3074 originalMotionEntry.xCursorPosition,
3075 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003076 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003078 if (originalMotionEntry.injectionState) {
3079 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 splitMotionEntry->injectionState->refCount += 1;
3081 }
3082
3083 return splitMotionEntry;
3084}
3085
3086void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3087#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003088 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#endif
3090
3091 bool needWake;
3092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003093 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094
Prabir Pradhan42611e02018-11-27 14:04:02 -08003095 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003096 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 needWake = enqueueInboundEventLocked(newEntry);
3098 } // release lock
3099
3100 if (needWake) {
3101 mLooper->wake();
3102 }
3103}
3104
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003105/**
3106 * If one of the meta shortcuts is detected, process them here:
3107 * Meta + Backspace -> generate BACK
3108 * Meta + Enter -> generate HOME
3109 * This will potentially overwrite keyCode and metaState.
3110 */
3111void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003113 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3114 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3115 if (keyCode == AKEYCODE_DEL) {
3116 newKeyCode = AKEYCODE_BACK;
3117 } else if (keyCode == AKEYCODE_ENTER) {
3118 newKeyCode = AKEYCODE_HOME;
3119 }
3120 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003121 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003122 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003123 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003124 keyCode = newKeyCode;
3125 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3126 }
3127 } else if (action == AKEY_EVENT_ACTION_UP) {
3128 // In order to maintain a consistent stream of up and down events, check to see if the key
3129 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3130 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003131 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003132 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003133 auto replacementIt = mReplacedKeys.find(replacement);
3134 if (replacementIt != mReplacedKeys.end()) {
3135 keyCode = replacementIt->second;
3136 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003137 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3138 }
3139 }
3140}
3141
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3143#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3145 "policyFlags=0x%x, action=0x%x, "
3146 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3147 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3148 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3149 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150#endif
3151 if (!validateKeyEvent(args->action)) {
3152 return;
3153 }
3154
3155 uint32_t policyFlags = args->policyFlags;
3156 int32_t flags = args->flags;
3157 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003158 // InputDispatcher tracks and generates key repeats on behalf of
3159 // whatever notifies it, so repeatCount should always be set to 0
3160 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3162 policyFlags |= POLICY_FLAG_VIRTUAL;
3163 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 if (policyFlags & POLICY_FLAG_FUNCTION) {
3166 metaState |= AMETA_FUNCTION_ON;
3167 }
3168
3169 policyFlags |= POLICY_FLAG_TRUSTED;
3170
Michael Wright78f24442014-08-06 15:55:28 -07003171 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003172 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003173
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003175 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003176 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3177 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178
Michael Wright2b3c3302018-03-02 17:19:13 +00003179 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003181 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3182 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 bool needWake;
3187 { // acquire lock
3188 mLock.lock();
3189
3190 if (shouldSendKeyToInputFilterLocked(args)) {
3191 mLock.unlock();
3192
3193 policyFlags |= POLICY_FLAG_FILTERED;
3194 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3195 return; // event was consumed by the filter
3196 }
3197
3198 mLock.lock();
3199 }
3200
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003202 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 args->displayId, policyFlags, args->action, flags, keyCode,
3204 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205
3206 needWake = enqueueInboundEventLocked(newEntry);
3207 mLock.unlock();
3208 } // release lock
3209
3210 if (needWake) {
3211 mLooper->wake();
3212 }
3213}
3214
3215bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3216 return mInputFilterEnabled;
3217}
3218
3219void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3220#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003221 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3222 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003223 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3224 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003225 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003226 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3227 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3228 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3229 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 for (uint32_t i = 0; i < args->pointerCount; i++) {
3231 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 "x=%f, y=%f, pressure=%f, size=%f, "
3233 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3234 "orientation=%f",
3235 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3236 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3237 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3238 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3239 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3240 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3241 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3242 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3243 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3244 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 }
3246#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3248 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 return;
3250 }
3251
3252 uint32_t policyFlags = args->policyFlags;
3253 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003254
3255 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003256 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003257 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3258 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261
3262 bool needWake;
3263 { // acquire lock
3264 mLock.lock();
3265
3266 if (shouldSendMotionToInputFilterLocked(args)) {
3267 mLock.unlock();
3268
3269 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003270 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003271 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3272 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003273 args->metaState, args->buttonState, args->classification, transform,
3274 args->xPrecision, args->yPrecision, args->xCursorPosition,
3275 args->yCursorPosition, args->downTime, args->eventTime,
3276 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277
3278 policyFlags |= POLICY_FLAG_FILTERED;
3279 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3280 return; // event was consumed by the filter
3281 }
3282
3283 mLock.lock();
3284 }
3285
3286 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003287 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003288 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003289 args->displayId, policyFlags, args->action, args->actionButton,
3290 args->flags, args->metaState, args->buttonState,
3291 args->classification, args->edgeFlags, args->xPrecision,
3292 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3293 args->downTime, args->pointerCount, args->pointerProperties,
3294 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295
3296 needWake = enqueueInboundEventLocked(newEntry);
3297 mLock.unlock();
3298 } // release lock
3299
3300 if (needWake) {
3301 mLooper->wake();
3302 }
3303}
3304
3305bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003306 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307}
3308
3309void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3310#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003311 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 "switchMask=0x%08x",
3313 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314#endif
3315
3316 uint32_t policyFlags = args->policyFlags;
3317 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319}
3320
3321void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3322#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3324 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325#endif
3326
3327 bool needWake;
3328 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003329 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
Prabir Pradhan42611e02018-11-27 14:04:02 -08003331 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003332 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 needWake = enqueueInboundEventLocked(newEntry);
3334 } // release lock
3335
3336 if (needWake) {
3337 mLooper->wake();
3338 }
3339}
3340
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3342 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003343 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344#if DEBUG_INBOUND_EVENT_DETAILS
3345 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003346 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3347 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348#endif
3349
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003350 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351
3352 policyFlags |= POLICY_FLAG_INJECTED;
3353 if (hasInjectionPermission(injectorPid, injectorUid)) {
3354 policyFlags |= POLICY_FLAG_TRUSTED;
3355 }
3356
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003357 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003360 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3361 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 if (!validateKeyEvent(action)) {
3363 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003366 int32_t flags = incomingKey.getFlags();
3367 int32_t keyCode = incomingKey.getKeyCode();
3368 int32_t metaState = incomingKey.getMetaState();
3369 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003371 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003372 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003373 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3374 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3375 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3378 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003379 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003380
3381 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3382 android::base::Timer t;
3383 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3384 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3385 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3386 std::to_string(t.duration().count()).c_str());
3387 }
3388 }
3389
3390 mLock.lock();
3391 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003392 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3393 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003394 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3395 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003396 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003397 injectedEntries.push(injectedEntry);
3398 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003401 case AINPUT_EVENT_TYPE_MOTION: {
3402 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3403 int32_t action = motionEvent->getAction();
3404 size_t pointerCount = motionEvent->getPointerCount();
3405 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3406 int32_t actionButton = motionEvent->getActionButton();
3407 int32_t displayId = motionEvent->getDisplayId();
3408 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3409 return INPUT_EVENT_INJECTION_FAILED;
3410 }
3411
3412 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3413 nsecs_t eventTime = motionEvent->getEventTime();
3414 android::base::Timer t;
3415 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3416 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3417 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3418 std::to_string(t.duration().count()).c_str());
3419 }
3420 }
3421
3422 mLock.lock();
3423 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3424 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3425 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003426 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3427 motionEvent->getSource(), motionEvent->getDisplayId(),
3428 policyFlags, action, actionButton, motionEvent->getFlags(),
3429 motionEvent->getMetaState(), motionEvent->getButtonState(),
3430 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3431 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003432 motionEvent->getRawXCursorPosition(),
3433 motionEvent->getRawYCursorPosition(),
3434 motionEvent->getDownTime(), uint32_t(pointerCount),
3435 pointerProperties, samplePointerCoords,
3436 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003437 injectedEntries.push(injectedEntry);
3438 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3439 sampleEventTimes += 1;
3440 samplePointerCoords += pointerCount;
3441 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003442 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003443 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003444 motionEvent->getDisplayId(), policyFlags, action,
3445 actionButton, motionEvent->getFlags(),
3446 motionEvent->getMetaState(), motionEvent->getButtonState(),
3447 motionEvent->getClassification(),
3448 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3449 motionEvent->getYPrecision(),
3450 motionEvent->getRawXCursorPosition(),
3451 motionEvent->getRawYCursorPosition(),
3452 motionEvent->getDownTime(), uint32_t(pointerCount),
3453 pointerProperties, samplePointerCoords,
3454 motionEvent->getXOffset(), motionEvent->getYOffset());
3455 injectedEntries.push(nextInjectedEntry);
3456 }
3457 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003460 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003461 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003462 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
3464
3465 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3466 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3467 injectionState->injectionIsAsync = true;
3468 }
3469
3470 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003471 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472
3473 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003474 while (!injectedEntries.empty()) {
3475 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3476 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 }
3478
3479 mLock.unlock();
3480
3481 if (needWake) {
3482 mLooper->wake();
3483 }
3484
3485 int32_t injectionResult;
3486 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003487 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488
3489 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3490 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3491 } else {
3492 for (;;) {
3493 injectionResult = injectionState->injectionResult;
3494 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3495 break;
3496 }
3497
3498 nsecs_t remainingTimeout = endTime - now();
3499 if (remainingTimeout <= 0) {
3500#if DEBUG_INJECTION
3501 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003502 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503#endif
3504 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3505 break;
3506 }
3507
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003508 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 }
3510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3512 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 while (injectionState->pendingForegroundDispatches != 0) {
3514#if DEBUG_INJECTION
3515 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003516 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517#endif
3518 nsecs_t remainingTimeout = endTime - now();
3519 if (remainingTimeout <= 0) {
3520#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003521 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3522 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523#endif
3524 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3525 break;
3526 }
3527
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003528 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
3530 }
3531 }
3532
3533 injectionState->release();
3534 } // release lock
3535
3536#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003537 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003538 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539#endif
3540
3541 return injectionResult;
3542}
3543
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003544std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003545 std::array<uint8_t, 32> calculatedHmac;
3546 std::unique_ptr<VerifiedInputEvent> result;
3547 switch (event.getType()) {
3548 case AINPUT_EVENT_TYPE_KEY: {
3549 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3550 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3551 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3552 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3553 break;
3554 }
3555 case AINPUT_EVENT_TYPE_MOTION: {
3556 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3557 VerifiedMotionEvent verifiedMotionEvent =
3558 verifiedMotionEventFromMotionEvent(motionEvent);
3559 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3560 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3561 break;
3562 }
3563 default: {
3564 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3565 return nullptr;
3566 }
3567 }
3568 if (calculatedHmac == INVALID_HMAC) {
3569 return nullptr;
3570 }
3571 if (calculatedHmac != event.getHmac()) {
3572 return nullptr;
3573 }
3574 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003575}
3576
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003578 return injectorUid == 0 ||
3579 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580}
3581
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003582void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 InjectionState* injectionState = entry->injectionState;
3584 if (injectionState) {
3585#if DEBUG_INJECTION
3586 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003587 "injectorPid=%d, injectorUid=%d",
3588 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589#endif
3590
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 // Log the outcome since the injector did not wait for the injection result.
3593 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003594 case INPUT_EVENT_INJECTION_SUCCEEDED:
3595 ALOGV("Asynchronous input event injection succeeded.");
3596 break;
3597 case INPUT_EVENT_INJECTION_FAILED:
3598 ALOGW("Asynchronous input event injection failed.");
3599 break;
3600 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3601 ALOGW("Asynchronous input event injection permission denied.");
3602 break;
3603 case INPUT_EVENT_INJECTION_TIMED_OUT:
3604 ALOGW("Asynchronous input event injection timed out.");
3605 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
3607 }
3608
3609 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003610 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 }
3612}
3613
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003614void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 InjectionState* injectionState = entry->injectionState;
3616 if (injectionState) {
3617 injectionState->pendingForegroundDispatches += 1;
3618 }
3619}
3620
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003621void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 InjectionState* injectionState = entry->injectionState;
3623 if (injectionState) {
3624 injectionState->pendingForegroundDispatches -= 1;
3625
3626 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003627 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 }
3629 }
3630}
3631
Vishnu Nairad321cd2020-08-20 16:40:21 -07003632const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003633 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003634 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3635 auto it = mWindowHandlesByDisplay.find(displayId);
3636 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003637}
3638
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003640 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003641 if (windowHandleToken == nullptr) {
3642 return nullptr;
3643 }
3644
Arthur Hungb92218b2018-08-14 12:00:21 +08003645 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003646 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003647 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003648 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003649 return windowHandle;
3650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 }
3652 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003653 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654}
3655
Vishnu Nairad321cd2020-08-20 16:40:21 -07003656sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3657 int displayId) const {
3658 if (windowHandleToken == nullptr) {
3659 return nullptr;
3660 }
3661
3662 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3663 if (windowHandle->getToken() == windowHandleToken) {
3664 return windowHandle;
3665 }
3666 }
3667 return nullptr;
3668}
3669
3670sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3671 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3672 return getWindowHandleLocked(focusedToken, displayId);
3673}
3674
Mady Mellor017bcd12020-06-23 19:12:00 +00003675bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3676 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003677 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003678 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003679 if (handle->getId() == windowHandle->getId() &&
3680 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003681 if (windowHandle->getInfo()->displayId != it.first) {
3682 ALOGE("Found window %s in display %" PRId32
3683 ", but it should belong to display %" PRId32,
3684 windowHandle->getName().c_str(), it.first,
3685 windowHandle->getInfo()->displayId);
3686 }
3687 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
3690 }
3691 return false;
3692}
3693
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003694bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3695 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3696 const bool noInputChannel =
3697 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3698 if (connection != nullptr && noInputChannel) {
3699 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3700 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3701 return false;
3702 }
3703
3704 if (connection == nullptr) {
3705 if (!noInputChannel) {
3706 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3707 }
3708 return false;
3709 }
3710 if (!connection->responsive) {
3711 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3712 return false;
3713 }
3714 return true;
3715}
3716
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003717std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3718 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003719 size_t count = mInputChannelsByToken.count(token);
3720 if (count == 0) {
3721 return nullptr;
3722 }
3723 return mInputChannelsByToken.at(token);
3724}
3725
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003726void InputDispatcher::updateWindowHandlesForDisplayLocked(
3727 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3728 if (inputWindowHandles.empty()) {
3729 // Remove all handles on a display if there are no windows left.
3730 mWindowHandlesByDisplay.erase(displayId);
3731 return;
3732 }
3733
3734 // Since we compare the pointer of input window handles across window updates, we need
3735 // to make sure the handle object for the same window stays unchanged across updates.
3736 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003737 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003738 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003739 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003740 }
3741
3742 std::vector<sp<InputWindowHandle>> newHandles;
3743 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3744 if (!handle->updateInfo()) {
3745 // handle no longer valid
3746 continue;
3747 }
3748
3749 const InputWindowInfo* info = handle->getInfo();
3750 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3751 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3752 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003753 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3754 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3755 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003756 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003757 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003758 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003759 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003760 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003761 }
3762
3763 if (info->displayId != displayId) {
3764 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3765 handle->getName().c_str(), displayId, info->displayId);
3766 continue;
3767 }
3768
Robert Carredd13602020-04-13 17:24:34 -07003769 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3770 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003771 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003772 oldHandle->updateFrom(handle);
3773 newHandles.push_back(oldHandle);
3774 } else {
3775 newHandles.push_back(handle);
3776 }
3777 }
3778
3779 // Insert or replace
3780 mWindowHandlesByDisplay[displayId] = newHandles;
3781}
3782
Arthur Hung72d8dc32020-03-28 00:48:39 +00003783void InputDispatcher::setInputWindows(
3784 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3785 { // acquire lock
3786 std::scoped_lock _l(mLock);
3787 for (auto const& i : handlesPerDisplay) {
3788 setInputWindowsLocked(i.second, i.first);
3789 }
3790 }
3791 // Wake up poll loop since it may need to make new input dispatching choices.
3792 mLooper->wake();
3793}
3794
Arthur Hungb92218b2018-08-14 12:00:21 +08003795/**
3796 * Called from InputManagerService, update window handle list by displayId that can receive input.
3797 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3798 * If set an empty list, remove all handles from the specific display.
3799 * For focused handle, check if need to change and send a cancel event to previous one.
3800 * For removed handle, check if need to send a cancel event if already in touch.
3801 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003802void InputDispatcher::setInputWindowsLocked(
3803 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003804 if (DEBUG_FOCUS) {
3805 std::string windowList;
3806 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3807 windowList += iwh->getName() + " ";
3808 }
3809 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003812 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3813 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3814 const bool noInputWindow =
3815 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3816 if (noInputWindow && window->getToken() != nullptr) {
3817 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3818 window->getName().c_str());
3819 window->releaseChannel();
3820 }
3821 }
3822
Arthur Hung72d8dc32020-03-28 00:48:39 +00003823 // Copy old handles for release if they are no longer present.
3824 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825
Arthur Hung72d8dc32020-03-28 00:48:39 +00003826 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003827
Vishnu Nairad321cd2020-08-20 16:40:21 -07003828 sp<IBinder> newFocusedToken = nullptr;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003829 bool foundHoveredWindow = false;
3830 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003831 // Set newFocusedToken to the top most focused window instead of the last one
3832 if (!newFocusedToken && windowHandle->getInfo()->focusable &&
Arthur Hung72d8dc32020-03-28 00:48:39 +00003833 windowHandle->getInfo()->visible) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003834 newFocusedToken = windowHandle->getToken();
Arthur Hung72d8dc32020-03-28 00:48:39 +00003835 }
3836 if (windowHandle == mLastHoverWindowHandle) {
3837 foundHoveredWindow = true;
3838 }
3839 }
3840
3841 if (!foundHoveredWindow) {
3842 mLastHoverWindowHandle = nullptr;
3843 }
3844
Vishnu Nairad321cd2020-08-20 16:40:21 -07003845 sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3846 if (oldFocusedToken != newFocusedToken) {
3847 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, "setInputWindowsLocked");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003850 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3851 mTouchStatesByDisplay.find(displayId);
3852 if (stateIt != mTouchStatesByDisplay.end()) {
3853 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003854 for (size_t i = 0; i < state.windows.size();) {
3855 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003856 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003857 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003858 ALOGD("Touched window was removed: %s in display %" PRId32,
3859 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003860 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003861 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003862 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3863 if (touchedInputChannel != nullptr) {
3864 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3865 "touched window was removed");
3866 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003868 state.windows.erase(state.windows.begin() + i);
3869 } else {
3870 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
3872 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003873 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003874
Arthur Hung72d8dc32020-03-28 00:48:39 +00003875 // Release information for windows that are no longer present.
3876 // This ensures that unused input channels are released promptly.
3877 // Otherwise, they might stick around until the window handle is destroyed
3878 // which might not happen until the next GC.
3879 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003880 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003881 if (DEBUG_FOCUS) {
3882 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003883 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003884 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003885 }
chaviw291d88a2019-02-14 10:33:58 -08003886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887}
3888
3889void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003890 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003891 if (DEBUG_FOCUS) {
3892 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3893 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3894 }
Chris Yea209fde2020-07-22 13:54:51 -07003895 if (inputApplicationHandle != nullptr &&
3896 inputApplicationHandle->getApplicationToken() != nullptr) {
3897 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003898 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899
Chris Yea209fde2020-07-22 13:54:51 -07003900 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003901 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003902
Chris Yea209fde2020-07-22 13:54:51 -07003903 // If oldFocusedApplicationHandle already exists
3904 if (oldFocusedApplicationHandle != nullptr) {
3905 // If a new focused application handle is different from the old one and
3906 // old focus application info is awaited focused application info.
3907 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3908 mAwaitedFocusedApplication != nullptr &&
3909 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3910 resetNoFocusedWindowTimeoutLocked();
3911 }
3912 // Erase the old application from container first
3913 mFocusedApplicationHandlesByDisplay.erase(displayId);
3914 // Should already get freed after removed from container but just double check.
3915 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003916 }
3917
Chris Yea209fde2020-07-22 13:54:51 -07003918 // Set the new application handle.
3919 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 } // release lock
3921
3922 // Wake up poll loop since it may need to make new input dispatching choices.
3923 mLooper->wake();
3924}
3925
Tiger Huang721e26f2018-07-24 22:26:19 +08003926/**
3927 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3928 * the display not specified.
3929 *
3930 * We track any unreleased events for each window. If a window loses the ability to receive the
3931 * released event, we will send a cancel event to it. So when the focused display is changed, we
3932 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3933 * display. The display-specified events won't be affected.
3934 */
3935void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003936 if (DEBUG_FOCUS) {
3937 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3938 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003939 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003940 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003941
3942 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003943 sp<IBinder> oldFocusedWindowToken =
3944 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3945 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003946 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003947 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003948 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949 CancelationOptions
3950 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3951 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003952 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003953 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3954 }
3955 }
3956 mFocusedDisplayId = displayId;
3957
Chris Ye3c2d6f52020-08-09 10:39:48 -07003958 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003959 sp<IBinder> newFocusedWindowToken =
3960 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3961 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003962
Vishnu Nairad321cd2020-08-20 16:40:21 -07003963 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003964 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003965 if (!mFocusedWindowTokenByDisplay.empty()) {
3966 ALOGE("But another display has a focused window\n%s",
3967 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003968 }
3969 }
3970 }
3971
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003972 if (DEBUG_FOCUS) {
3973 logDispatchStateLocked();
3974 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003975 } // release lock
3976
3977 // Wake up poll loop since it may need to make new input dispatching choices.
3978 mLooper->wake();
3979}
3980
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003982 if (DEBUG_FOCUS) {
3983 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 bool changed;
3987 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003988 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989
3990 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3991 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003992 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
3994
3995 if (mDispatchEnabled && !enabled) {
3996 resetAndDropEverythingLocked("dispatcher is being disabled");
3997 }
3998
3999 mDispatchEnabled = enabled;
4000 mDispatchFrozen = frozen;
4001 changed = true;
4002 } else {
4003 changed = false;
4004 }
4005
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004006 if (DEBUG_FOCUS) {
4007 logDispatchStateLocked();
4008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 } // release lock
4010
4011 if (changed) {
4012 // Wake up poll loop since it may need to make new input dispatching choices.
4013 mLooper->wake();
4014 }
4015}
4016
4017void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004018 if (DEBUG_FOCUS) {
4019 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021
4022 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004023 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024
4025 if (mInputFilterEnabled == enabled) {
4026 return;
4027 }
4028
4029 mInputFilterEnabled = enabled;
4030 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4031 } // release lock
4032
4033 // Wake up poll loop since there might be work to do to drop everything.
4034 mLooper->wake();
4035}
4036
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004037void InputDispatcher::setInTouchMode(bool inTouchMode) {
4038 std::scoped_lock lock(mLock);
4039 mInTouchMode = inTouchMode;
4040}
4041
chaviwfbe5d9c2018-12-26 12:23:37 -08004042bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4043 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004044 if (DEBUG_FOCUS) {
4045 ALOGD("Trivial transfer to same window.");
4046 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004047 return true;
4048 }
4049
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004051 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052
chaviwfbe5d9c2018-12-26 12:23:37 -08004053 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4054 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004055 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004056 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 return false;
4058 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004059 if (DEBUG_FOCUS) {
4060 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4061 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004064 if (DEBUG_FOCUS) {
4065 ALOGD("Cannot transfer focus because windows are on different displays.");
4066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 return false;
4068 }
4069
4070 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004071 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4072 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004073 for (size_t i = 0; i < state.windows.size(); i++) {
4074 const TouchedWindow& touchedWindow = state.windows[i];
4075 if (touchedWindow.windowHandle == fromWindowHandle) {
4076 int32_t oldTargetFlags = touchedWindow.targetFlags;
4077 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004079 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 int32_t newTargetFlags = oldTargetFlags &
4082 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4083 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004084 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
Jeff Brownf086ddb2014-02-11 14:28:48 -08004086 found = true;
4087 goto Found;
4088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 }
4090 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004091 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004094 if (DEBUG_FOCUS) {
4095 ALOGD("Focus transfer failed because from window did not have focus.");
4096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 return false;
4098 }
4099
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004100 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4101 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004102 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004103 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004104 CancelationOptions
4105 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4106 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004108 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 }
4110
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004111 if (DEBUG_FOCUS) {
4112 logDispatchStateLocked();
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 } // release lock
4115
4116 // Wake up poll loop since it may need to make new input dispatching choices.
4117 mLooper->wake();
4118 return true;
4119}
4120
4121void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004122 if (DEBUG_FOCUS) {
4123 ALOGD("Resetting and dropping all events (%s).", reason);
4124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
4126 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4127 synthesizeCancelationEventsForAllConnectionsLocked(options);
4128
4129 resetKeyRepeatLocked();
4130 releasePendingEventLocked();
4131 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004132 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004134 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004135 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004137 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138}
4139
4140void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 dumpDispatchStateLocked(dump);
4143
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144 std::istringstream stream(dump);
4145 std::string line;
4146
4147 while (std::getline(stream, line, '\n')) {
4148 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 }
4150}
4151
Vishnu Nairad321cd2020-08-20 16:40:21 -07004152std::string InputDispatcher::dumpFocusedWindowsLocked() {
4153 if (mFocusedWindowTokenByDisplay.empty()) {
4154 return INDENT "FocusedWindows: <none>\n";
4155 }
4156
4157 std::string dump;
4158 dump += INDENT "FocusedWindows:\n";
4159 for (auto& it : mFocusedWindowTokenByDisplay) {
4160 const int32_t displayId = it.first;
4161 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4162 if (windowHandle) {
4163 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4164 windowHandle->getName().c_str());
4165 } else {
4166 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4167 " has focused token without a window'\n",
4168 displayId);
4169 }
4170 }
4171 return dump;
4172}
4173
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004175 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4176 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4177 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004178 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Tiger Huang721e26f2018-07-24 22:26:19 +08004180 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4181 dump += StringPrintf(INDENT "FocusedApplications:\n");
4182 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4183 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004184 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004185 const std::chrono::duration timeout =
4186 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004188 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004189 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004192 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004194
Vishnu Nairad321cd2020-08-20 16:40:21 -07004195 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004197 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004199 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4200 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 state.displayId, toString(state.down), toString(state.split),
4203 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004204 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004206 for (size_t i = 0; i < state.windows.size(); i++) {
4207 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004208 dump += StringPrintf(INDENT4
4209 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4210 i, touchedWindow.windowHandle->getName().c_str(),
4211 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004212 }
4213 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004214 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004215 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004216 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004217 dump += INDENT3 "Portal windows:\n";
4218 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004219 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4221 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004222 }
4223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 }
4225 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004226 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228
Arthur Hungb92218b2018-08-14 12:00:21 +08004229 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004231 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004232 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004233 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004234 dump += INDENT2 "Windows:\n";
4235 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004236 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004237 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238
Arthur Hungb92218b2018-08-14 12:00:21 +08004239 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004240 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4241 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004242 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004244 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 i, windowInfo->name.c_str(), windowInfo->displayId,
4246 windowInfo->portalToDisplayId,
4247 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004248 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 toString(windowInfo->hasWallpaper),
4250 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004251 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004252 static_cast<int32_t>(windowInfo->type),
4253 windowInfo->frameLeft, windowInfo->frameTop,
4254 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004255 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004256 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004257 dump += StringPrintf(", inputFeatures=%s",
4258 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004259 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4260 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004262 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004263 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004264 }
4265 } else {
4266 dump += INDENT2 "Windows: <none>\n";
4267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004270 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 }
4272
Michael Wright3dd60e22019-03-27 22:06:44 +00004273 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004274 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004275 const std::vector<Monitor>& monitors = it.second;
4276 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4277 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 }
4279 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004280 const std::vector<Monitor>& monitors = it.second;
4281 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4282 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004285 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 }
4287
4288 nsecs_t currentTime = now();
4289
4290 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004291 if (!mRecentQueue.empty()) {
4292 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4293 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004294 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004296 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 }
4298 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004299 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301
4302 // Dump event currently being dispatched.
4303 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004304 dump += INDENT "PendingEvent:\n";
4305 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004307 dump += StringPrintf(", age=%" PRId64 "ms\n",
4308 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004310 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312
4313 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004314 if (!mInboundQueue.empty()) {
4315 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4316 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004317 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004319 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 }
4321 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004322 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 }
4324
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004325 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004326 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004327 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4328 const KeyReplacement& replacement = pair.first;
4329 int32_t newKeyCode = pair.second;
4330 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004332 }
4333 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004334 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004335 }
4336
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004337 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004338 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004339 for (const auto& pair : mConnectionsByFd) {
4340 const sp<Connection>& connection = pair.second;
4341 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004342 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004343 pair.first, connection->getInputChannelName().c_str(),
4344 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004345 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004347 if (!connection->outboundQueue.empty()) {
4348 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4349 connection->outboundQueue.size());
4350 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 dump.append(INDENT4);
4352 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004353 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4354 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004355 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004356 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
4358 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004359 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
4361
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004362 if (!connection->waitQueue.empty()) {
4363 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4364 connection->waitQueue.size());
4365 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004366 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004368 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004369 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004371 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004372 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004375 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 }
4377 }
4378 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004379 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 }
4381
4382 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004383 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4384 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004386 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 }
4388
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004389 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004390 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4391 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4392 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393}
4394
Michael Wright3dd60e22019-03-27 22:06:44 +00004395void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4396 const size_t numMonitors = monitors.size();
4397 for (size_t i = 0; i < numMonitors; i++) {
4398 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004399 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004400 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4401 dump += "\n";
4402 }
4403}
4404
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004405status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004407 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408#endif
4409
4410 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004411 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004412 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004413 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 return BAD_VALUE;
4417 }
4418
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004419 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420
4421 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004422 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004423 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4426 } // release lock
4427
4428 // Wake the looper because some connections have changed.
4429 mLooper->wake();
4430 return OK;
4431}
4432
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004433status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004434 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004435 { // acquire lock
4436 std::scoped_lock _l(mLock);
4437
4438 if (displayId < 0) {
4439 ALOGW("Attempted to register input monitor without a specified display.");
4440 return BAD_VALUE;
4441 }
4442
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004443 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004444 ALOGW("Attempted to register input monitor without an identifying token.");
4445 return BAD_VALUE;
4446 }
4447
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004448 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004449
4450 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004451 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004452 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004453
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004454 auto& monitorsByDisplay =
4455 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004456 monitorsByDisplay[displayId].emplace_back(inputChannel);
4457
4458 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004459 }
4460 // Wake the looper because some connections have changed.
4461 mLooper->wake();
4462 return OK;
4463}
4464
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004465status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004467 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468#endif
4469
4470 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004471 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472
4473 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4474 if (status) {
4475 return status;
4476 }
4477 } // release lock
4478
4479 // Wake the poll loop because removing the connection may have changed the current
4480 // synchronization state.
4481 mLooper->wake();
4482 return OK;
4483}
4484
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004485status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004486 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004487 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004488 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004490 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 return BAD_VALUE;
4492 }
4493
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004494 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004495 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004496
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 if (connection->monitor) {
4498 removeMonitorChannelLocked(inputChannel);
4499 }
4500
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004501 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
4503 nsecs_t currentTime = now();
4504 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4505
4506 connection->status = Connection::STATUS_ZOMBIE;
4507 return OK;
4508}
4509
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004510void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004511 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4512 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4513}
4514
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004516 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004517 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004518 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004519 std::vector<Monitor>& monitors = it->second;
4520 const size_t numMonitors = monitors.size();
4521 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004522 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 monitors.erase(monitors.begin() + i);
4524 break;
4525 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004526 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004527 if (monitors.empty()) {
4528 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004529 } else {
4530 ++it;
4531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 }
4533}
4534
Michael Wright3dd60e22019-03-27 22:06:44 +00004535status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4536 { // acquire lock
4537 std::scoped_lock _l(mLock);
4538 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4539
4540 if (!foundDisplayId) {
4541 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4542 return BAD_VALUE;
4543 }
4544 int32_t displayId = foundDisplayId.value();
4545
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004546 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4547 mTouchStatesByDisplay.find(displayId);
4548 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004549 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4550 return BAD_VALUE;
4551 }
4552
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004553 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004554 std::optional<int32_t> foundDeviceId;
4555 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004556 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004557 foundDeviceId = state.deviceId;
4558 }
4559 }
4560 if (!foundDeviceId || !state.down) {
4561 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004563 return BAD_VALUE;
4564 }
4565 int32_t deviceId = foundDeviceId.value();
4566
4567 // Send cancel events to all the input channels we're stealing from.
4568 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004570 options.deviceId = deviceId;
4571 options.displayId = displayId;
4572 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004573 std::shared_ptr<InputChannel> channel =
4574 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004575 if (channel != nullptr) {
4576 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4577 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004578 }
4579 // Then clear the current touch state so we stop dispatching to them as well.
4580 state.filterNonMonitors();
4581 }
4582 return OK;
4583}
4584
Michael Wright3dd60e22019-03-27 22:06:44 +00004585std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4586 const sp<IBinder>& token) {
4587 for (const auto& it : mGestureMonitorsByDisplay) {
4588 const std::vector<Monitor>& monitors = it.second;
4589 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004590 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004591 return it.first;
4592 }
4593 }
4594 }
4595 return std::nullopt;
4596}
4597
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004598sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004599 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004600 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004601 }
4602
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004603 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004604 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004605 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004606 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 }
4608 }
Robert Carr4e670e52018-08-15 13:26:12 -07004609
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004610 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611}
4612
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004613void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004614 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004615 removeByValue(mConnectionsByFd, connection);
4616}
4617
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4619 const sp<Connection>& connection, uint32_t seq,
4620 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004621 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4622 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 commandEntry->connection = connection;
4624 commandEntry->eventTime = currentTime;
4625 commandEntry->seq = seq;
4626 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004627 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628}
4629
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004630void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4631 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004633 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004635 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4636 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004638 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639}
4640
Vishnu Nairad321cd2020-08-20 16:40:21 -07004641void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4642 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004643 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4644 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004645 commandEntry->oldToken = oldToken;
4646 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004647 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004648}
4649
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004650void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4651 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4652 // is already healthy again. Don't raise ANR in this situation
4653 if (connection->waitQueue.empty()) {
4654 ALOGI("Not raising ANR because the connection %s has recovered",
4655 connection->inputChannel->getName().c_str());
4656 return;
4657 }
4658 /**
4659 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4660 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4661 * has changed. This could cause newer entries to time out before the already dispatched
4662 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4663 * processes the events linearly. So providing information about the oldest entry seems to be
4664 * most useful.
4665 */
4666 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4667 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4668 std::string reason =
4669 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4670 connection->inputChannel->getName().c_str(),
4671 ns2ms(currentWait),
4672 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4675 reason);
4676
4677 std::unique_ptr<CommandEntry> commandEntry =
4678 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4679 commandEntry->inputApplicationHandle = nullptr;
4680 commandEntry->inputChannel = connection->inputChannel;
4681 commandEntry->reason = std::move(reason);
4682 postCommandLocked(std::move(commandEntry));
4683}
4684
Chris Yea209fde2020-07-22 13:54:51 -07004685void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004686 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4687 application->getName().c_str());
4688
4689 updateLastAnrStateLocked(application, reason);
4690
4691 std::unique_ptr<CommandEntry> commandEntry =
4692 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4693 commandEntry->inputApplicationHandle = application;
4694 commandEntry->inputChannel = nullptr;
4695 commandEntry->reason = std::move(reason);
4696 postCommandLocked(std::move(commandEntry));
4697}
4698
4699void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4700 const std::string& reason) {
4701 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4702 updateLastAnrStateLocked(windowLabel, reason);
4703}
4704
Chris Yea209fde2020-07-22 13:54:51 -07004705void InputDispatcher::updateLastAnrStateLocked(
4706 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004707 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4708 updateLastAnrStateLocked(windowLabel, reason);
4709}
4710
4711void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4712 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004714 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 struct tm tm;
4716 localtime_r(&t, &tm);
4717 char timestr[64];
4718 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004719 mLastAnrState.clear();
4720 mLastAnrState += INDENT "ANR:\n";
4721 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004722 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4723 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004724 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725}
4726
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004727void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 mLock.unlock();
4729
4730 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4731
4732 mLock.lock();
4733}
4734
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 sp<Connection> connection = commandEntry->connection;
4737
4738 if (connection->status != Connection::STATUS_ZOMBIE) {
4739 mLock.unlock();
4740
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004741 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742
4743 mLock.lock();
4744 }
4745}
4746
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004747void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004748 sp<IBinder> oldToken = commandEntry->oldToken;
4749 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004750 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004751 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004752 mLock.lock();
4753}
4754
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004755void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004756 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004757 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 mLock.unlock();
4759
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004760 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004761 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762
4763 mLock.lock();
4764
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004765 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004766 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4767 } else {
4768 // stop waking up for events in this connection, it is already not responding
4769 sp<Connection> connection = getConnectionLocked(token);
4770 if (connection == nullptr) {
4771 return;
4772 }
4773 cancelEventsForAnrLocked(connection);
4774 }
4775}
4776
Chris Yea209fde2020-07-22 13:54:51 -07004777void InputDispatcher::extendAnrTimeoutsLocked(
4778 const std::shared_ptr<InputApplicationHandle>& application,
4779 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004780 sp<Connection> connection = getConnectionLocked(connectionToken);
4781 if (connection == nullptr) {
4782 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4783 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004784 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004785 mAwaitedFocusedApplication = application;
4786 } else {
4787 // It's also possible that the connection already disappeared. No action necessary.
4788 }
4789 return;
4790 }
4791
4792 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004793 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794
4795 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004796 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797 for (DispatchEntry* entry : connection->waitQueue) {
4798 if (newTimeout >= entry->timeoutTime) {
4799 // Already removed old entries when connection was marked unresponsive
4800 entry->timeoutTime = newTimeout;
4801 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4802 }
4803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804}
4805
4806void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4807 CommandEntry* commandEntry) {
4808 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004809 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810
4811 mLock.unlock();
4812
Michael Wright2b3c3302018-03-02 17:19:13 +00004813 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004815 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004816 : nullptr;
4817 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004818 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4819 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004820 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822
4823 mLock.lock();
4824
4825 if (delay < 0) {
4826 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4827 } else if (!delay) {
4828 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4829 } else {
4830 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4831 entry->interceptKeyWakeupTime = now() + delay;
4832 }
4833 entry->release();
4834}
4835
chaviwfd6d3512019-03-25 13:23:49 -07004836void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4837 mLock.unlock();
4838 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4839 mLock.lock();
4840}
4841
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004842/**
4843 * Connection is responsive if it has no events in the waitQueue that are older than the
4844 * current time.
4845 */
4846static bool isConnectionResponsive(const Connection& connection) {
4847 const nsecs_t currentTime = now();
4848 for (const DispatchEntry* entry : connection.waitQueue) {
4849 if (entry->timeoutTime < currentTime) {
4850 return false;
4851 }
4852 }
4853 return true;
4854}
4855
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004856void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004858 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004860 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861
4862 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004863 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004864 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004865 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004867 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004868 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004869 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004870 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4871 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004872 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004873 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004874
4875 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004876 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004877 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4878 restartEvent =
4879 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004880 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004881 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4882 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4883 handled);
4884 } else {
4885 restartEvent = false;
4886 }
4887
4888 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004889 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004890 // contents of the wait queue to have been drained, so we need to double-check
4891 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004892 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4893 if (dispatchEntryIt != connection->waitQueue.end()) {
4894 dispatchEntry = *dispatchEntryIt;
4895 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 mAnrTracker.erase(dispatchEntry->timeoutTime,
4897 connection->inputChannel->getConnectionToken());
4898 if (!connection->responsive) {
4899 connection->responsive = isConnectionResponsive(*connection);
4900 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004901 traceWaitQueueLength(connection);
4902 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004903 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004904 traceOutboundQueueLength(connection);
4905 } else {
4906 releaseDispatchEntry(dispatchEntry);
4907 }
4908 }
4909
4910 // Start the next dispatch cycle for this connection.
4911 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912}
4913
4914bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004915 DispatchEntry* dispatchEntry,
4916 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004917 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004918 if (!handled) {
4919 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004920 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004921 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004922 return false;
4923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004925 // Get the fallback key state.
4926 // Clear it out after dispatching the UP.
4927 int32_t originalKeyCode = keyEntry->keyCode;
4928 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4929 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4930 connection->inputState.removeFallbackKey(originalKeyCode);
4931 }
4932
4933 if (handled || !dispatchEntry->hasForegroundTarget()) {
4934 // If the application handles the original key for which we previously
4935 // generated a fallback or if the window is not a foreground window,
4936 // then cancel the associated fallback key, if any.
4937 if (fallbackKeyCode != -1) {
4938 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004940 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004941 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4942 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4943 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004945 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004946 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947
4948 mLock.unlock();
4949
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004950 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952
4953 mLock.lock();
4954
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004955 // Cancel the fallback key.
4956 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004958 "application handled the original non-fallback key "
4959 "or is no longer a foreground target, "
4960 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961 options.keyCode = fallbackKeyCode;
4962 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004964 connection->inputState.removeFallbackKey(originalKeyCode);
4965 }
4966 } else {
4967 // If the application did not handle a non-fallback key, first check
4968 // that we are in a good state to perform unhandled key event processing
4969 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004970 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004971 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004973 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004974 "since this is not an initial down. "
4975 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4976 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004978 return false;
4979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004981 // Dispatch the unhandled key to the policy.
4982#if DEBUG_OUTBOUND_EVENT_DETAILS
4983 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4985 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004986#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004987 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004988
4989 mLock.unlock();
4990
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004991 bool fallback =
4992 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4993 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004994
4995 mLock.lock();
4996
4997 if (connection->status != Connection::STATUS_NORMAL) {
4998 connection->inputState.removeFallbackKey(originalKeyCode);
4999 return false;
5000 }
5001
5002 // Latch the fallback keycode for this key on an initial down.
5003 // The fallback keycode cannot change at any other point in the lifecycle.
5004 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005006 fallbackKeyCode = event.getKeyCode();
5007 } else {
5008 fallbackKeyCode = AKEYCODE_UNKNOWN;
5009 }
5010 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5011 }
5012
5013 ALOG_ASSERT(fallbackKeyCode != -1);
5014
5015 // Cancel the fallback key if the policy decides not to send it anymore.
5016 // We will continue to dispatch the key to the policy but we will no
5017 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005018 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5019 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005020#if DEBUG_OUTBOUND_EVENT_DETAILS
5021 if (fallback) {
5022 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005023 "as a fallback for %d, but on the DOWN it had requested "
5024 "to send %d instead. Fallback canceled.",
5025 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005026 } else {
5027 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005028 "but on the DOWN it had requested to send %d. "
5029 "Fallback canceled.",
5030 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005031 }
5032#endif
5033
5034 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5035 "canceling fallback, policy no longer desires it");
5036 options.keyCode = fallbackKeyCode;
5037 synthesizeCancelationEventsForConnectionLocked(connection, options);
5038
5039 fallback = false;
5040 fallbackKeyCode = AKEYCODE_UNKNOWN;
5041 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005042 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005043 }
5044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045
5046#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005047 {
5048 std::string msg;
5049 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5050 connection->inputState.getFallbackKeys();
5051 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005052 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005054 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005055 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005056 }
5057#endif
5058
5059 if (fallback) {
5060 // Restart the dispatch cycle using the fallback key.
5061 keyEntry->eventTime = event.getEventTime();
5062 keyEntry->deviceId = event.getDeviceId();
5063 keyEntry->source = event.getSource();
5064 keyEntry->displayId = event.getDisplayId();
5065 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5066 keyEntry->keyCode = fallbackKeyCode;
5067 keyEntry->scanCode = event.getScanCode();
5068 keyEntry->metaState = event.getMetaState();
5069 keyEntry->repeatCount = event.getRepeatCount();
5070 keyEntry->downTime = event.getDownTime();
5071 keyEntry->syntheticRepeat = false;
5072
5073#if DEBUG_OUTBOUND_EVENT_DETAILS
5074 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005075 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5076 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005077#endif
5078 return true; // restart the event
5079 } else {
5080#if DEBUG_OUTBOUND_EVENT_DETAILS
5081 ALOGD("Unhandled key event: No fallback key.");
5082#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005083
5084 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005085 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087 }
5088 return false;
5089}
5090
5091bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005092 DispatchEntry* dispatchEntry,
5093 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 return false;
5095}
5096
5097void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5098 mLock.unlock();
5099
5100 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5101
5102 mLock.lock();
5103}
5104
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005105KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5106 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005107 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005108 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5109 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005110 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111}
5112
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005113void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5114 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 // TODO Write some statistics about how long we spend waiting.
5116}
5117
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005118/**
5119 * Report the touch event latency to the statsd server.
5120 * Input events are reported for statistics if:
5121 * - This is a touchscreen event
5122 * - InputFilter is not enabled
5123 * - Event is not injected or synthesized
5124 *
5125 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5126 * from getting aggregated with the "old" data.
5127 */
5128void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5129 REQUIRES(mLock) {
5130 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5131 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5132 if (!reportForStatistics) {
5133 return;
5134 }
5135
5136 if (mTouchStatistics.shouldReport()) {
5137 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5138 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5139 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5140 mTouchStatistics.reset();
5141 }
5142 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5143 mTouchStatistics.addValue(latencyMicros);
5144}
5145
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146void InputDispatcher::traceInboundQueueLengthLocked() {
5147 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005148 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 }
5150}
5151
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005152void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 if (ATRACE_ENABLED()) {
5154 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005155 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005156 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 }
5158}
5159
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005160void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 if (ATRACE_ENABLED()) {
5162 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005163 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005164 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 }
5166}
5167
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005168void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005169 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005171 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 dumpDispatchStateLocked(dump);
5173
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005174 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005175 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005176 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 }
5178}
5179
5180void InputDispatcher::monitor() {
5181 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005182 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005184 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185}
5186
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005187/**
5188 * Wake up the dispatcher and wait until it processes all events and commands.
5189 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5190 * this method can be safely called from any thread, as long as you've ensured that
5191 * the work you are interested in completing has already been queued.
5192 */
5193bool InputDispatcher::waitForIdle() {
5194 /**
5195 * Timeout should represent the longest possible time that a device might spend processing
5196 * events and commands.
5197 */
5198 constexpr std::chrono::duration TIMEOUT = 100ms;
5199 std::unique_lock lock(mLock);
5200 mLooper->wake();
5201 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5202 return result == std::cv_status::no_timeout;
5203}
5204
Vishnu Naire798b472020-07-23 13:52:21 -07005205/**
5206 * Sets focus to the window identified by the token. This must be called
5207 * after updating any input window handles.
5208 *
5209 * Params:
5210 * request.token - input channel token used to identify the window that should gain focus.
5211 * request.focusedToken - the token that the caller expects currently to be focused. If the
5212 * specified token does not match the currently focused window, this request will be dropped.
5213 * If the specified focused token matches the currently focused window, the call will succeed.
5214 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5215 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5216 * when requesting the focus change. This determines which request gets
5217 * precedence if there is a focus change request from another source such as pointer down.
5218 */
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005219void InputDispatcher::setFocusedWindow(const FocusRequest& request) {}
5220
Vishnu Nairad321cd2020-08-20 16:40:21 -07005221void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5222 const sp<IBinder>& newFocusedToken, int32_t displayId,
5223 std::string_view reason) {
5224 if (oldFocusedToken) {
5225 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005226 if (focusedInputChannel) {
5227 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5228 "focus left window");
5229 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005230 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005231 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005232 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005233 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005234 if (newFocusedToken) {
5235 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5236 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005237 }
5238
5239 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005240 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005241 }
5242}
Garfield Tane84e6f92019-08-29 17:28:41 -07005243} // namespace android::inputdispatcher