blob: a44e8734b42c4a2aba15f68bc5f5c82bb75c9c9e [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.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800816 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
817 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
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001081void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001082 if (mPendingEvent != nullptr) {
1083 // Move the pending event to the front of the queue. This will give the chance
1084 // for the pending event to get dispatched to the newly focused window
1085 mInboundQueue.push_front(mPendingEvent);
1086 mPendingEvent = nullptr;
1087 }
1088
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001089 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001090 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001091
1092 // This event should go to the front of the queue, but behind all other focus events
1093 // Find the last focus event, and insert right after it
1094 std::deque<EventEntry*>::reverse_iterator it =
1095 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1096 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1097
1098 // Maintain the order of focus events. Insert the entry after all other focus events.
1099 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001100}
1101
1102void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001103 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001104 if (channel == nullptr) {
1105 return; // Window has gone away
1106 }
1107 InputTarget target;
1108 target.inputChannel = channel;
1109 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1110 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001111 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1112 channel->getName();
1113 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001114 dispatchEventLocked(currentTime, entry, {target});
1115}
1116
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 if (!entry->dispatchInProgress) {
1121 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1122 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1123 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1124 if (mKeyRepeatState.lastKeyEntry &&
1125 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 // We have seen two identical key downs in a row which indicates that the device
1127 // driver is automatically generating key repeats itself. We take note of the
1128 // repeat here, but we disable our own next key repeat timer since it is clear that
1129 // we will not need to synthesize key repeats ourselves.
1130 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1131 resetKeyRepeatLocked();
1132 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1133 } else {
1134 // Not a repeat. Save key down state in case we do see a repeat later.
1135 resetKeyRepeatLocked();
1136 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1137 }
1138 mKeyRepeatState.lastKeyEntry = entry;
1139 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 resetKeyRepeatLocked();
1142 }
1143
1144 if (entry->repeatCount == 1) {
1145 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1146 } else {
1147 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1148 }
1149
1150 entry->dispatchInProgress = true;
1151
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001152 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
1154
1155 // Handle case where the policy asked us to try again later last time.
1156 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1157 if (currentTime < entry->interceptKeyWakeupTime) {
1158 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1159 *nextWakeupTime = entry->interceptKeyWakeupTime;
1160 }
1161 return false; // wait until next wakeup
1162 }
1163 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1164 entry->interceptKeyWakeupTime = 0;
1165 }
1166
1167 // Give the policy a chance to intercept the key.
1168 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1169 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001170 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001171 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001172 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001173 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001174 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
1177 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001178 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 entry->refCount += 1;
1180 return false; // wait for the command to run
1181 } else {
1182 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1183 }
1184 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001185 if (*dropReason == DropReason::NOT_DROPPED) {
1186 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 }
1188 }
1189
1190 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001191 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001193 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001195 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 return true;
1197 }
1198
1199 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001200 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001202 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1204 return false;
1205 }
1206
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001207 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1209 return true;
1210 }
1211
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001212 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214
1215 // Dispatch the key.
1216 dispatchEventLocked(currentTime, entry, inputTargets);
1217 return true;
1218}
1219
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001220void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001222 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1224 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001225 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1226 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1227 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228#endif
1229}
1230
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1232 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001233 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 entry->dispatchInProgress = true;
1237
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001238 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240
1241 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001244 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 return true;
1247 }
1248
1249 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1250
1251 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001252 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253
1254 bool conflictingPointerActions = false;
1255 int32_t injectionResult;
1256 if (isPointerEvent) {
1257 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001259 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 } else {
1262 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001263 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001264 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1267 return false;
1268 }
1269
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001270 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001271 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1272 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1273 return true;
1274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001276 CancelationOptions::Mode mode(isPointerEvent
1277 ? CancelationOptions::CANCEL_POINTER_EVENTS
1278 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1279 CancelationOptions options(mode, "input event injection failed");
1280 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 return true;
1282 }
1283
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001284 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001285 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001287 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001288 std::unordered_map<int32_t, TouchState>::iterator it =
1289 mTouchStatesByDisplay.find(entry->displayId);
1290 if (it != mTouchStatesByDisplay.end()) {
1291 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001292 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001293 // The event has gone through these portal windows, so we add monitoring targets of
1294 // the corresponding displays as well.
1295 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001296 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001297 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001299 }
1300 }
1301 }
1302 }
1303
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 // Dispatch the motion.
1305 if (conflictingPointerActions) {
1306 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 synthesizeCancelationEventsForAllConnectionsLocked(options);
1309 }
1310 dispatchEventLocked(currentTime, entry, inputTargets);
1311 return true;
1312}
1313
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001314void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001316 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001317 ", policyFlags=0x%x, "
1318 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1319 "metaState=0x%x, buttonState=0x%x,"
1320 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001321 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1322 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1323 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001325 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 "x=%f, y=%f, pressure=%f, size=%f, "
1328 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1329 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001330 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1338 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1339 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341#endif
1342}
1343
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001344void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1345 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001346 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347#if DEBUG_DISPATCH_CYCLE
1348 ALOGD("dispatchEventToCurrentInputTargets");
1349#endif
1350
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001351 updateInteractionTokensLocked(*eventEntry, inputTargets);
1352
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1354
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001355 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001357 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001358 sp<Connection> connection =
1359 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001360 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001361 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001363 if (DEBUG_FOCUS) {
1364 ALOGD("Dropping event delivery to target with channel '%s' because it "
1365 "is no longer registered with the input dispatcher.",
1366 inputTarget.inputChannel->getName().c_str());
1367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 }
1369 }
1370}
1371
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001372void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1373 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1374 // If the policy decides to close the app, we will get a channel removal event via
1375 // unregisterInputChannel, and will clean up the connection that way. We are already not
1376 // sending new pointers to the connection when it blocked, but focused events will continue to
1377 // pile up.
1378 ALOGW("Canceling events for %s because it is unresponsive",
1379 connection->inputChannel->getName().c_str());
1380 if (connection->status == Connection::STATUS_NORMAL) {
1381 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1382 "application not responding");
1383 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 }
1385}
1386
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001387void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001388 if (DEBUG_FOCUS) {
1389 ALOGD("Resetting ANR timeouts.");
1390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391
1392 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001393 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001394 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395}
1396
Tiger Huang721e26f2018-07-24 22:26:19 +08001397/**
1398 * Get the display id that the given event should go to. If this event specifies a valid display id,
1399 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1400 * Focused display is the display that the user most recently interacted with.
1401 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001403 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001405 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001406 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1407 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001408 break;
1409 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001410 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001411 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1412 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001413 break;
1414 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001415 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001416 case EventEntry::Type::CONFIGURATION_CHANGED:
1417 case EventEntry::Type::DEVICE_RESET: {
1418 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 return ADISPLAY_ID_NONE;
1420 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001421 }
1422 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1423}
1424
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001425bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1426 const char* focusedWindowName) {
1427 if (mAnrTracker.empty()) {
1428 // already processed all events that we waited for
1429 mKeyIsWaitingForEventsTimeout = std::nullopt;
1430 return false;
1431 }
1432
1433 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1434 // Start the timer
1435 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1436 "focus to change",
1437 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001438 mKeyIsWaitingForEventsTimeout = currentTime +
1439 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1440 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001441 return true;
1442 }
1443
1444 // We still have pending events, and already started the timer
1445 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1446 return true; // Still waiting
1447 }
1448
1449 // Waited too long, and some connection still hasn't processed all motions
1450 // Just send the key to the focused window
1451 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1452 focusedWindowName);
1453 mKeyIsWaitingForEventsTimeout = std::nullopt;
1454 return false;
1455}
1456
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001458 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001459 std::vector<InputTarget>& inputTargets,
1460 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001461 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462
Tiger Huang721e26f2018-07-24 22:26:19 +08001463 int32_t displayId = getTargetDisplayId(entry);
1464 sp<InputWindowHandle> focusedWindowHandle =
1465 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001466 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001467 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1468
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 // If there is no currently focused window and no focused application
1470 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001471 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1472 ALOGI("Dropping %s event because there is no focused window or focused application in "
1473 "display %" PRId32 ".",
1474 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001475 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 }
1477
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001478 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1479 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1480 // start interacting with another application via touch (app switch). This code can be removed
1481 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1482 // an app is expected to have a focused window.
1483 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1484 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1485 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001486 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1487 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1488 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001489 mAwaitedFocusedApplication = focusedApplicationHandle;
1490 ALOGW("Waiting because no window has focus but %s may eventually add a "
1491 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001492 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001493 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1494 return INPUT_EVENT_INJECTION_PENDING;
1495 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1496 // Already raised ANR. Drop the event
1497 ALOGE("Dropping %s event because there is no focused window",
1498 EventEntry::typeToString(entry.type));
1499 return INPUT_EVENT_INJECTION_FAILED;
1500 } else {
1501 // Still waiting for the focused window
1502 return INPUT_EVENT_INJECTION_PENDING;
1503 }
1504 }
1505
1506 // we have a valid, non-null focused window
1507 resetNoFocusedWindowTimeoutLocked();
1508
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001510 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001511 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001514 if (focusedWindowHandle->getInfo()->paused) {
1515 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1516 return INPUT_EVENT_INJECTION_PENDING;
1517 }
1518
1519 // If the event is a key event, then we must wait for all previous events to
1520 // complete before delivering it because previous events may have the
1521 // side-effect of transferring focus to a different window and we want to
1522 // ensure that the following keys are sent to the new window.
1523 //
1524 // Suppose the user touches a button in a window then immediately presses "A".
1525 // If the button causes a pop-up window to appear then we want to ensure that
1526 // the "A" key is delivered to the new pop-up window. This is because users
1527 // often anticipate pending UI changes when typing on a keyboard.
1528 // To obtain this behavior, we must serialize key events with respect to all
1529 // prior input events.
1530 if (entry.type == EventEntry::Type::KEY) {
1531 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1532 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1533 return INPUT_EVENT_INJECTION_PENDING;
1534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 }
1536
1537 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001538 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001539 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1540 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541
1542 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001543 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544}
1545
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001546/**
1547 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1548 * that are currently unresponsive.
1549 */
1550std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1551 const std::vector<TouchedMonitor>& monitors) const {
1552 std::vector<TouchedMonitor> responsiveMonitors;
1553 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1554 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1555 sp<Connection> connection = getConnectionLocked(
1556 monitor.monitor.inputChannel->getConnectionToken());
1557 if (connection == nullptr) {
1558 ALOGE("Could not find connection for monitor %s",
1559 monitor.monitor.inputChannel->getName().c_str());
1560 return false;
1561 }
1562 if (!connection->responsive) {
1563 ALOGW("Unresponsive monitor %s will not get the new gesture",
1564 connection->inputChannel->getName().c_str());
1565 return false;
1566 }
1567 return true;
1568 });
1569 return responsiveMonitors;
1570}
1571
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001573 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001574 std::vector<InputTarget>& inputTargets,
1575 nsecs_t* nextWakeupTime,
1576 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001577 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 enum InjectionPermission {
1579 INJECTION_PERMISSION_UNKNOWN,
1580 INJECTION_PERMISSION_GRANTED,
1581 INJECTION_PERMISSION_DENIED
1582 };
1583
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 // For security reasons, we defer updating the touch state until we are sure that
1585 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001586 int32_t displayId = entry.displayId;
1587 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1589
1590 // Update the touch state as needed based on the properties of the touch event.
1591 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1592 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001593 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1594 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001596 // Copy current touch state into tempTouchState.
1597 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1598 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001599 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001600 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001601 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1602 mTouchStatesByDisplay.find(displayId);
1603 if (oldStateIt != mTouchStatesByDisplay.end()) {
1604 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001605 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001606 }
1607
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001608 bool isSplit = tempTouchState.split;
1609 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1610 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1611 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1613 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1614 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1615 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1616 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001617 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 bool wrongDevice = false;
1619 if (newGesture) {
1620 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001621 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001622 ALOGI("Dropping event because a pointer for a different device is already down "
1623 "in display %" PRId32,
1624 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001625 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1627 switchedDevice = false;
1628 wrongDevice = true;
1629 goto Failed;
1630 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001631 tempTouchState.reset();
1632 tempTouchState.down = down;
1633 tempTouchState.deviceId = entry.deviceId;
1634 tempTouchState.source = entry.source;
1635 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001637 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001638 ALOGI("Dropping move event because a pointer for a different device is already active "
1639 "in display %" PRId32,
1640 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001641 // TODO: test multiple simultaneous input streams.
1642 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1643 switchedDevice = false;
1644 wrongDevice = true;
1645 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 }
1647
1648 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1649 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1650
Garfield Tan00f511d2019-06-12 16:55:40 -07001651 int32_t x;
1652 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001654 // Always dispatch mouse events to cursor position.
1655 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001656 x = int32_t(entry.xCursorPosition);
1657 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001658 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001659 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1660 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001661 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001662 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001663 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001664 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1665 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001666
1667 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001668 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001669 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001672 if (newTouchedWindowHandle != nullptr &&
1673 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001674 // New window supports splitting, but we should never split mouse events.
1675 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 } else if (isSplit) {
1677 // New window does not support splitting but we have already split events.
1678 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001679 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 }
1681
1682 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001683 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001685 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001686 }
1687
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001688 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1689 ALOGI("Not sending touch event to %s because it is paused",
1690 newTouchedWindowHandle->getName().c_str());
1691 newTouchedWindowHandle = nullptr;
1692 }
1693
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001694 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001695 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001696 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1697 if (!isResponsive) {
1698 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001699 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1700 newTouchedWindowHandle = nullptr;
1701 }
1702 }
1703
1704 // Also don't send the new touch event to unresponsive gesture monitors
1705 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1706
Michael Wright3dd60e22019-03-27 22:06:44 +00001707 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1708 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001709 "(%d, %d) in display %" PRId32 ".",
1710 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001711 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1712 goto Failed;
1713 }
1714
1715 if (newTouchedWindowHandle != nullptr) {
1716 // Set target flags.
1717 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1718 if (isSplit) {
1719 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001721 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1722 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1723 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1724 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1725 }
1726
1727 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001728 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1729 newHoverWindowHandle = nullptr;
1730 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001731 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001732 }
1733
1734 // Update the temporary touch state.
1735 BitSet32 pointerIds;
1736 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001738 pointerIds.markBit(pointerId);
1739 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001740 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 }
1742
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001743 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 } else {
1745 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1746
1747 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001748 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001749 if (DEBUG_FOCUS) {
1750 ALOGD("Dropping event because the pointer is not down or we previously "
1751 "dropped the pointer down event in display %" PRId32,
1752 displayId);
1753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1755 goto Failed;
1756 }
1757
1758 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001759 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001760 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001761 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1762 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763
1764 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001765 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001766 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001767 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1768 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001769 if (DEBUG_FOCUS) {
1770 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1771 oldTouchedWindowHandle->getName().c_str(),
1772 newTouchedWindowHandle->getName().c_str(), displayId);
1773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001775 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1776 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1777 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778
1779 // Make a slippery entrance into the new window.
1780 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1781 isSplit = true;
1782 }
1783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001784 int32_t targetFlags =
1785 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 if (isSplit) {
1787 targetFlags |= InputTarget::FLAG_SPLIT;
1788 }
1789 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1790 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1791 }
1792
1793 BitSet32 pointerIds;
1794 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001797 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 }
1799 }
1800 }
1801
1802 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001803 // Let the previous window know that the hover sequence is over, unless we already did it
1804 // when dispatching it as is to newTouchedWindowHandle.
1805 if (mLastHoverWindowHandle != nullptr &&
1806 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1807 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808#if DEBUG_HOVER
1809 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001810 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001812 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1813 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 }
1815
Garfield Tandf26e862020-07-01 20:18:19 -07001816 // Let the new window know that the hover sequence is starting, unless we already did it
1817 // when dispatching it as is to newTouchedWindowHandle.
1818 if (newHoverWindowHandle != nullptr &&
1819 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1820 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821#if DEBUG_HOVER
1822 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001823 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001825 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1826 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1827 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 }
1829 }
1830
1831 // Check permission to inject into all touched foreground windows and ensure there
1832 // is at least one touched foreground window.
1833 {
1834 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1837 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1840 injectionPermission = INJECTION_PERMISSION_DENIED;
1841 goto Failed;
1842 }
1843 }
1844 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001845 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001846 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001847 ALOGI("Dropping event because there is no touched foreground window in display "
1848 "%" PRId32 " or gesture monitor to receive it.",
1849 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1851 goto Failed;
1852 }
1853
1854 // Permission granted to injection into all touched foreground windows.
1855 injectionPermission = INJECTION_PERMISSION_GRANTED;
1856 }
1857
1858 // Check whether windows listening for outside touches are owned by the same UID. If it is
1859 // set the policy flag that we will not reveal coordinate information to this window.
1860 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1861 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001862 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001863 if (foregroundWindowHandle) {
1864 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001865 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001866 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1867 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1868 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001869 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1870 InputTarget::FLAG_ZERO_COORDS,
1871 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 }
1874 }
1875 }
1876 }
1877
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 // If this is the first pointer going down and the touched window has a wallpaper
1879 // then also add the touched wallpaper windows so they are locked in for the duration
1880 // of the touch gesture.
1881 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1882 // engine only supports touch events. We would need to add a mechanism similar
1883 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1884 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1885 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001886 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001888 const std::vector<sp<InputWindowHandle>> windowHandles =
1889 getWindowHandlesLocked(displayId);
1890 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001893 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001894 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001895 .addOrUpdateWindow(windowHandle,
1896 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1897 InputTarget::
1898 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1899 InputTarget::FLAG_DISPATCH_AS_IS,
1900 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 }
1902 }
1903 }
1904 }
1905
1906 // Success! Output targets.
1907 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1908
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001909 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001911 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 }
1913
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001914 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001915 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001916 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001917 }
1918
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 // Drop the outside or hover touch windows since we will not care about them
1920 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001921 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922
1923Failed:
1924 // Check injection permission once and for all.
1925 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001926 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 injectionPermission = INJECTION_PERMISSION_GRANTED;
1928 } else {
1929 injectionPermission = INJECTION_PERMISSION_DENIED;
1930 }
1931 }
1932
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001933 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1934 return injectionResult;
1935 }
1936
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001938 if (!wrongDevice) {
1939 if (switchedDevice) {
1940 if (DEBUG_FOCUS) {
1941 ALOGD("Conflicting pointer actions: Switched to a different device.");
1942 }
1943 *outConflictingPointerActions = true;
1944 }
1945
1946 if (isHoverAction) {
1947 // Started hovering, therefore no longer down.
1948 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001949 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001950 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1951 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 *outConflictingPointerActions = true;
1954 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001955 tempTouchState.reset();
1956 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1957 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1958 tempTouchState.deviceId = entry.deviceId;
1959 tempTouchState.source = entry.source;
1960 tempTouchState.displayId = displayId;
1961 }
1962 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1963 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1964 // All pointers up or canceled.
1965 tempTouchState.reset();
1966 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1967 // First pointer went down.
1968 if (oldState && oldState->down) {
1969 if (DEBUG_FOCUS) {
1970 ALOGD("Conflicting pointer actions: Down received while already down.");
1971 }
1972 *outConflictingPointerActions = true;
1973 }
1974 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1975 // One pointer went up.
1976 if (isSplit) {
1977 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1978 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001980 for (size_t i = 0; i < tempTouchState.windows.size();) {
1981 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1982 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1983 touchedWindow.pointerIds.clearBit(pointerId);
1984 if (touchedWindow.pointerIds.isEmpty()) {
1985 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1986 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001989 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001991 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001992 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001993
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001994 // Save changes unless the action was scroll in which case the temporary touch
1995 // state was only valid for this one action.
1996 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1997 if (tempTouchState.displayId >= 0) {
1998 mTouchStatesByDisplay[displayId] = tempTouchState;
1999 } else {
2000 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002004 // Update hover state.
2005 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 }
2007
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 return injectionResult;
2009}
2010
2011void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002012 int32_t targetFlags, BitSet32 pointerIds,
2013 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002014 std::vector<InputTarget>::iterator it =
2015 std::find_if(inputTargets.begin(), inputTargets.end(),
2016 [&windowHandle](const InputTarget& inputTarget) {
2017 return inputTarget.inputChannel->getConnectionToken() ==
2018 windowHandle->getToken();
2019 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002020
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002021 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002022
2023 if (it == inputTargets.end()) {
2024 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002025 std::shared_ptr<InputChannel> inputChannel =
2026 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002027 if (inputChannel == nullptr) {
2028 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2029 return;
2030 }
2031 inputTarget.inputChannel = inputChannel;
2032 inputTarget.flags = targetFlags;
2033 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2034 inputTargets.push_back(inputTarget);
2035 it = inputTargets.end() - 1;
2036 }
2037
2038 ALOG_ASSERT(it->flags == targetFlags);
2039 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2040
chaviw1ff3d1e2020-07-01 15:53:47 -07002041 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042}
2043
Michael Wright3dd60e22019-03-27 22:06:44 +00002044void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002045 int32_t displayId, float xOffset,
2046 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002047 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2048 mGlobalMonitorsByDisplay.find(displayId);
2049
2050 if (it != mGlobalMonitorsByDisplay.end()) {
2051 const std::vector<Monitor>& monitors = it->second;
2052 for (const Monitor& monitor : monitors) {
2053 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
2056}
2057
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002058void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2059 float yOffset,
2060 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002061 InputTarget target;
2062 target.inputChannel = monitor.inputChannel;
2063 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002064 ui::Transform t;
2065 t.set(xOffset, yOffset);
2066 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002067 inputTargets.push_back(target);
2068}
2069
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002071 const InjectionState* injectionState) {
2072 if (injectionState &&
2073 (windowHandle == nullptr ||
2074 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2075 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002076 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002078 "owned by uid %d",
2079 injectionState->injectorPid, injectionState->injectorUid,
2080 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 } else {
2082 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002083 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 }
2085 return false;
2086 }
2087 return true;
2088}
2089
Robert Carrc9bf1d32020-04-13 17:21:08 -07002090/**
2091 * Indicate whether one window handle should be considered as obscuring
2092 * another window handle. We only check a few preconditions. Actually
2093 * checking the bounds is left to the caller.
2094 */
2095static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2096 const sp<InputWindowHandle>& otherHandle) {
2097 // Compare by token so cloned layers aren't counted
2098 if (haveSameToken(windowHandle, otherHandle)) {
2099 return false;
2100 }
2101 auto info = windowHandle->getInfo();
2102 auto otherInfo = otherHandle->getInfo();
2103 if (!otherInfo->visible) {
2104 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002105 } else if (info->ownerPid == otherInfo->ownerPid) {
2106 // If ownerPid is the same we don't generate occlusion events as there
2107 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002108 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002109 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002110 return false;
2111 } else if (otherInfo->displayId != info->displayId) {
2112 return false;
2113 }
2114 return true;
2115}
2116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002117bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2118 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002120 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2121 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002122 if (windowHandle == otherHandle) {
2123 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002126 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002127 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 return true;
2129 }
2130 }
2131 return false;
2132}
2133
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002134bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2135 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002136 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002137 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002138 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002139 if (windowHandle == otherHandle) {
2140 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002141 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002142 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002143 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002144 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002145 return true;
2146 }
2147 }
2148 return false;
2149}
2150
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002151std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002152 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002154 if (applicationHandle != nullptr) {
2155 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002156 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 } else {
2158 return applicationHandle->getName();
2159 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002160 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002161 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002163 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 }
2165}
2166
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002167void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002168 if (eventEntry.type == EventEntry::Type::FOCUS) {
2169 // Focus events are passed to apps, but do not represent user activity.
2170 return;
2171 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002172 int32_t displayId = getTargetDisplayId(eventEntry);
2173 sp<InputWindowHandle> focusedWindowHandle =
2174 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2175 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,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 const sp<IBinder>& newToken) {
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
2518 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2519 if (inputWindowHandle == nullptr) {
2520 return;
2521 }
2522
chaviw8c9cf542019-03-25 13:02:48 -07002523 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002524 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002525
2526 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2527
2528 if (!hasFocusChanged) {
2529 return;
2530 }
2531
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002532 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2533 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002534 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002535 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536}
2537
2538void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002540 if (ATRACE_ENABLED()) {
2541 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002543 ATRACE_NAME(message.c_str());
2544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002546 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547#endif
2548
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002549 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2550 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002552 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002553 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002554 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555
2556 // Publish the event.
2557 status_t status;
2558 EventEntry* eventEntry = dispatchEntry->eventEntry;
2559 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002560 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002561 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2562 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002565 status =
2566 connection->inputPublisher
2567 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2568 keyEntry->deviceId, keyEntry->source,
2569 keyEntry->displayId, std::move(hmac),
2570 dispatchEntry->resolvedAction,
2571 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2572 keyEntry->scanCode, keyEntry->metaState,
2573 keyEntry->repeatCount, keyEntry->downTime,
2574 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 }
2577
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002578 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 PointerCoords scaledCoords[MAX_POINTERS];
2582 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2583
chaviw82357092020-01-28 13:13:06 -08002584 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2586 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2587 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002588 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2590 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002591 // Don't apply window scale here since we don't want scale to affect raw
2592 // coordinates. The scale will be sent back to the client and applied
2593 // later when requesting relative coordinates.
2594 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2595 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002596 }
2597 usingCoords = scaledCoords;
2598 }
2599 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002600 // We don't want the dispatch target to know.
2601 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2602 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2603 scaledCoords[i].clear();
2604 }
2605 usingCoords = scaledCoords;
2606 }
2607 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002608
2609 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002610
2611 // Publish the motion event.
2612 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002613 .publishMotionEvent(dispatchEntry->seq,
2614 dispatchEntry->resolvedEventId,
2615 motionEntry->deviceId, motionEntry->source,
2616 motionEntry->displayId, std::move(hmac),
2617 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002618 motionEntry->actionButton,
2619 dispatchEntry->resolvedFlags,
2620 motionEntry->edgeFlags, motionEntry->metaState,
2621 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002622 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002623 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002624 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002625 motionEntry->yPrecision,
2626 motionEntry->xCursorPosition,
2627 motionEntry->yCursorPosition,
2628 motionEntry->downTime, motionEntry->eventTime,
2629 motionEntry->pointerCount,
2630 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002631 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002632 break;
2633 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002634 case EventEntry::Type::FOCUS: {
2635 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2636 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002637 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002638 focusEntry->hasFocus,
2639 mInTouchMode);
2640 break;
2641 }
2642
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002643 case EventEntry::Type::CONFIGURATION_CHANGED:
2644 case EventEntry::Type::DEVICE_RESET: {
2645 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2646 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002647 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
2650
2651 // Check the result.
2652 if (status) {
2653 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002654 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002656 "This is unexpected because the wait queue is empty, so the pipe "
2657 "should be empty and we shouldn't have any problems writing an "
2658 "event to it, status=%d",
2659 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2661 } else {
2662 // Pipe is full and we are waiting for the app to finish process some events
2663 // before sending more events to it.
2664#if DEBUG_DISPATCH_CYCLE
2665 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002666 "waiting for the application to catch up",
2667 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 }
2670 } else {
2671 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002672 "status=%d",
2673 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2675 }
2676 return;
2677 }
2678
2679 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002680 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2681 connection->outboundQueue.end(),
2682 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002683 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002684 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002685 if (connection->responsive) {
2686 mAnrTracker.insert(dispatchEntry->timeoutTime,
2687 connection->inputChannel->getConnectionToken());
2688 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002689 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 }
2691}
2692
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002693const std::array<uint8_t, 32> InputDispatcher::getSignature(
2694 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2695 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2696 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2697 // Only sign events up and down events as the purely move events
2698 // are tied to their up/down counterparts so signing would be redundant.
2699 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2700 verifiedEvent.actionMasked = actionMasked;
2701 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2702 return mHmacKeyManager.sign(verifiedEvent);
2703 }
2704 return INVALID_HMAC;
2705}
2706
2707const std::array<uint8_t, 32> InputDispatcher::getSignature(
2708 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2709 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2710 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2711 verifiedEvent.action = dispatchEntry.resolvedAction;
2712 return mHmacKeyManager.sign(verifiedEvent);
2713}
2714
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002716 const sp<Connection>& connection, uint32_t seq,
2717 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718#if DEBUG_DISPATCH_CYCLE
2719 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002720 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721#endif
2722
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 if (connection->status == Connection::STATUS_BROKEN ||
2724 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 return;
2726 }
2727
2728 // Notify other system components and prepare to start the next dispatch cycle.
2729 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2730}
2731
2732void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 const sp<Connection>& connection,
2734 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735#if DEBUG_DISPATCH_CYCLE
2736 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738#endif
2739
2740 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002741 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002742 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002743 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002744 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745
2746 // The connection appears to be unrecoverably broken.
2747 // Ignore already broken or zombie connections.
2748 if (connection->status == Connection::STATUS_NORMAL) {
2749 connection->status = Connection::STATUS_BROKEN;
2750
2751 if (notify) {
2752 // Notify other system components.
2753 onDispatchCycleBrokenLocked(currentTime, connection);
2754 }
2755 }
2756}
2757
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002758void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2759 while (!queue.empty()) {
2760 DispatchEntry* dispatchEntry = queue.front();
2761 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002762 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 }
2764}
2765
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002766void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002768 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 }
2770 delete dispatchEntry;
2771}
2772
2773int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2774 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2775
2776 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002777 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002779 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781 "fd=%d, events=0x%x",
2782 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 return 0; // remove the callback
2784 }
2785
2786 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002787 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2789 if (!(events & ALOOPER_EVENT_INPUT)) {
2790 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 "events=0x%x",
2792 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 return 1;
2794 }
2795
2796 nsecs_t currentTime = now();
2797 bool gotOne = false;
2798 status_t status;
2799 for (;;) {
2800 uint32_t seq;
2801 bool handled;
2802 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2803 if (status) {
2804 break;
2805 }
2806 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2807 gotOne = true;
2808 }
2809 if (gotOne) {
2810 d->runCommandsLockedInterruptible();
2811 if (status == WOULD_BLOCK) {
2812 return 1;
2813 }
2814 }
2815
2816 notify = status != DEAD_OBJECT || !connection->monitor;
2817 if (notify) {
2818 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002819 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821 } else {
2822 // Monitor channels are never explicitly unregistered.
2823 // We do it automatically when the remote endpoint is closed so don't warn
2824 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002825 const bool stillHaveWindowHandle =
2826 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2827 nullptr;
2828 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 if (notify) {
2830 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002831 "events=0x%x",
2832 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 }
2834 }
2835
2836 // Unregister the channel.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002837 d->unregisterInputChannelLocked(*connection->inputChannel, notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840}
2841
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002842void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002844 for (const auto& pair : mConnectionsByFd) {
2845 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 }
2847}
2848
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002850 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002851 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2852 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2853}
2854
2855void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2856 const CancelationOptions& options,
2857 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2858 for (const auto& it : monitorsByDisplay) {
2859 const std::vector<Monitor>& monitors = it.second;
2860 for (const Monitor& monitor : monitors) {
2861 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002862 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002863 }
2864}
2865
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002867 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002868 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002869 if (connection == nullptr) {
2870 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002872
2873 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874}
2875
2876void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2877 const sp<Connection>& connection, const CancelationOptions& options) {
2878 if (connection->status == Connection::STATUS_BROKEN) {
2879 return;
2880 }
2881
2882 nsecs_t currentTime = now();
2883
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002884 std::vector<EventEntry*> cancelationEvents =
2885 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002887 if (cancelationEvents.empty()) {
2888 return;
2889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002891 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2892 "with reality: %s, mode=%d.",
2893 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2894 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002896
2897 InputTarget target;
2898 sp<InputWindowHandle> windowHandle =
2899 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2900 if (windowHandle != nullptr) {
2901 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002902 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002903 target.globalScaleFactor = windowInfo->globalScaleFactor;
2904 }
2905 target.inputChannel = connection->inputChannel;
2906 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2907
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002908 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2909 EventEntry* cancelationEventEntry = cancelationEvents[i];
2910 switch (cancelationEventEntry->type) {
2911 case EventEntry::Type::KEY: {
2912 logOutboundKeyDetails("cancel - ",
2913 static_cast<const KeyEntry&>(*cancelationEventEntry));
2914 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002916 case EventEntry::Type::MOTION: {
2917 logOutboundMotionDetails("cancel - ",
2918 static_cast<const MotionEntry&>(*cancelationEventEntry));
2919 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002921 case EventEntry::Type::FOCUS: {
2922 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2923 break;
2924 }
2925 case EventEntry::Type::CONFIGURATION_CHANGED:
2926 case EventEntry::Type::DEVICE_RESET: {
2927 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2928 EventEntry::typeToString(cancelationEventEntry->type));
2929 break;
2930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
2932
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002933 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2934 target, InputTarget::FLAG_DISPATCH_AS_IS);
2935
2936 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002938
2939 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940}
2941
Svet Ganov5d3bc372020-01-26 23:11:07 -08002942void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2943 const sp<Connection>& connection) {
2944 if (connection->status == Connection::STATUS_BROKEN) {
2945 return;
2946 }
2947
2948 nsecs_t currentTime = now();
2949
2950 std::vector<EventEntry*> downEvents =
2951 connection->inputState.synthesizePointerDownEvents(currentTime);
2952
2953 if (downEvents.empty()) {
2954 return;
2955 }
2956
2957#if DEBUG_OUTBOUND_EVENT_DETAILS
2958 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2959 connection->getInputChannelName().c_str(), downEvents.size());
2960#endif
2961
2962 InputTarget target;
2963 sp<InputWindowHandle> windowHandle =
2964 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2965 if (windowHandle != nullptr) {
2966 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002967 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002968 target.globalScaleFactor = windowInfo->globalScaleFactor;
2969 }
2970 target.inputChannel = connection->inputChannel;
2971 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2972
2973 for (EventEntry* downEventEntry : downEvents) {
2974 switch (downEventEntry->type) {
2975 case EventEntry::Type::MOTION: {
2976 logOutboundMotionDetails("down - ",
2977 static_cast<const MotionEntry&>(*downEventEntry));
2978 break;
2979 }
2980
2981 case EventEntry::Type::KEY:
2982 case EventEntry::Type::FOCUS:
2983 case EventEntry::Type::CONFIGURATION_CHANGED:
2984 case EventEntry::Type::DEVICE_RESET: {
2985 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2986 EventEntry::typeToString(downEventEntry->type));
2987 break;
2988 }
2989 }
2990
2991 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2992 target, InputTarget::FLAG_DISPATCH_AS_IS);
2993
2994 downEventEntry->release();
2995 }
2996
2997 startDispatchCycleLocked(currentTime, connection);
2998}
2999
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003000MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003001 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 ALOG_ASSERT(pointerIds.value != 0);
3003
3004 uint32_t splitPointerIndexMap[MAX_POINTERS];
3005 PointerProperties splitPointerProperties[MAX_POINTERS];
3006 PointerCoords splitPointerCoords[MAX_POINTERS];
3007
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003008 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 uint32_t splitPointerCount = 0;
3010
3011 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003014 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 uint32_t pointerId = uint32_t(pointerProperties.id);
3016 if (pointerIds.hasBit(pointerId)) {
3017 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3018 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3019 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003020 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 splitPointerCount += 1;
3022 }
3023 }
3024
3025 if (splitPointerCount != pointerIds.count()) {
3026 // This is bad. We are missing some of the pointers that we expected to deliver.
3027 // Most likely this indicates that we received an ACTION_MOVE events that has
3028 // different pointer ids than we expected based on the previous ACTION_DOWN
3029 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3030 // in this way.
3031 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 "we expected there to be %d pointers. This probably means we received "
3033 "a broken sequence of pointer ids from the input device.",
3034 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003035 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
3037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003038 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3041 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3043 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003044 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 uint32_t pointerId = uint32_t(pointerProperties.id);
3046 if (pointerIds.hasBit(pointerId)) {
3047 if (pointerIds.count() == 1) {
3048 // The first/last pointer went down/up.
3049 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 ? AMOTION_EVENT_ACTION_DOWN
3051 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 } else {
3053 // A secondary pointer went down/up.
3054 uint32_t splitPointerIndex = 0;
3055 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3056 splitPointerIndex += 1;
3057 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 action = maskedAction |
3059 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060 }
3061 } else {
3062 // An unrelated pointer changed.
3063 action = AMOTION_EVENT_ACTION_MOVE;
3064 }
3065 }
3066
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003067 int32_t newId = mIdGenerator.nextId();
3068 if (ATRACE_ENABLED()) {
3069 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3070 ") to MotionEvent(id=0x%" PRIx32 ").",
3071 originalMotionEntry.id, newId);
3072 ATRACE_NAME(message.c_str());
3073 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003074 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003075 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3076 originalMotionEntry.source, originalMotionEntry.displayId,
3077 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003078 originalMotionEntry.actionButton, originalMotionEntry.flags,
3079 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3080 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3081 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3082 originalMotionEntry.xCursorPosition,
3083 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003084 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003086 if (originalMotionEntry.injectionState) {
3087 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 splitMotionEntry->injectionState->refCount += 1;
3089 }
3090
3091 return splitMotionEntry;
3092}
3093
3094void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3095#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003096 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097#endif
3098
3099 bool needWake;
3100 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003101 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
Prabir Pradhan42611e02018-11-27 14:04:02 -08003103 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003104 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 needWake = enqueueInboundEventLocked(newEntry);
3106 } // release lock
3107
3108 if (needWake) {
3109 mLooper->wake();
3110 }
3111}
3112
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003113/**
3114 * If one of the meta shortcuts is detected, process them here:
3115 * Meta + Backspace -> generate BACK
3116 * Meta + Enter -> generate HOME
3117 * This will potentially overwrite keyCode and metaState.
3118 */
3119void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003121 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3122 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3123 if (keyCode == AKEYCODE_DEL) {
3124 newKeyCode = AKEYCODE_BACK;
3125 } else if (keyCode == AKEYCODE_ENTER) {
3126 newKeyCode = AKEYCODE_HOME;
3127 }
3128 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003129 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003130 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003131 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003132 keyCode = newKeyCode;
3133 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3134 }
3135 } else if (action == AKEY_EVENT_ACTION_UP) {
3136 // In order to maintain a consistent stream of up and down events, check to see if the key
3137 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3138 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003139 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003140 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003141 auto replacementIt = mReplacedKeys.find(replacement);
3142 if (replacementIt != mReplacedKeys.end()) {
3143 keyCode = replacementIt->second;
3144 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003145 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3146 }
3147 }
3148}
3149
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3151#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3153 "policyFlags=0x%x, action=0x%x, "
3154 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3155 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3156 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3157 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158#endif
3159 if (!validateKeyEvent(args->action)) {
3160 return;
3161 }
3162
3163 uint32_t policyFlags = args->policyFlags;
3164 int32_t flags = args->flags;
3165 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003166 // InputDispatcher tracks and generates key repeats on behalf of
3167 // whatever notifies it, so repeatCount should always be set to 0
3168 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3170 policyFlags |= POLICY_FLAG_VIRTUAL;
3171 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 if (policyFlags & POLICY_FLAG_FUNCTION) {
3174 metaState |= AMETA_FUNCTION_ON;
3175 }
3176
3177 policyFlags |= POLICY_FLAG_TRUSTED;
3178
Michael Wright78f24442014-08-06 15:55:28 -07003179 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003180 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003181
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003183 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003184 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3185 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186
Michael Wright2b3c3302018-03-02 17:19:13 +00003187 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003189 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3190 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003191 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 bool needWake;
3195 { // acquire lock
3196 mLock.lock();
3197
3198 if (shouldSendKeyToInputFilterLocked(args)) {
3199 mLock.unlock();
3200
3201 policyFlags |= POLICY_FLAG_FILTERED;
3202 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3203 return; // event was consumed by the filter
3204 }
3205
3206 mLock.lock();
3207 }
3208
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003210 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211 args->displayId, policyFlags, args->action, flags, keyCode,
3212 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
3214 needWake = enqueueInboundEventLocked(newEntry);
3215 mLock.unlock();
3216 } // release lock
3217
3218 if (needWake) {
3219 mLooper->wake();
3220 }
3221}
3222
3223bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3224 return mInputFilterEnabled;
3225}
3226
3227void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3228#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003229 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3230 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003231 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3232 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003233 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003234 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3235 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3236 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3237 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 for (uint32_t i = 0; i < args->pointerCount; i++) {
3239 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 "x=%f, y=%f, pressure=%f, size=%f, "
3241 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3242 "orientation=%f",
3243 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3244 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3245 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3246 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3247 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3248 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3249 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3250 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3251 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3252 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 }
3254#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3256 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 return;
3258 }
3259
3260 uint32_t policyFlags = args->policyFlags;
3261 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003262
3263 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003264 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003265 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3266 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
3270 bool needWake;
3271 { // acquire lock
3272 mLock.lock();
3273
3274 if (shouldSendMotionToInputFilterLocked(args)) {
3275 mLock.unlock();
3276
3277 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003278 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003279 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3280 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003281 args->metaState, args->buttonState, args->classification, transform,
3282 args->xPrecision, args->yPrecision, args->xCursorPosition,
3283 args->yCursorPosition, args->downTime, args->eventTime,
3284 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 policyFlags |= POLICY_FLAG_FILTERED;
3287 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3288 return; // event was consumed by the filter
3289 }
3290
3291 mLock.lock();
3292 }
3293
3294 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003295 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003296 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003297 args->displayId, policyFlags, args->action, args->actionButton,
3298 args->flags, args->metaState, args->buttonState,
3299 args->classification, args->edgeFlags, args->xPrecision,
3300 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3301 args->downTime, args->pointerCount, args->pointerProperties,
3302 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
3304 needWake = enqueueInboundEventLocked(newEntry);
3305 mLock.unlock();
3306 } // release lock
3307
3308 if (needWake) {
3309 mLooper->wake();
3310 }
3311}
3312
3313bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003314 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315}
3316
3317void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3318#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003319 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 "switchMask=0x%08x",
3321 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322#endif
3323
3324 uint32_t policyFlags = args->policyFlags;
3325 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327}
3328
3329void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3330#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3332 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333#endif
3334
3335 bool needWake;
3336 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003337 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
Prabir Pradhan42611e02018-11-27 14:04:02 -08003339 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003340 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 needWake = enqueueInboundEventLocked(newEntry);
3342 } // release lock
3343
3344 if (needWake) {
3345 mLooper->wake();
3346 }
3347}
3348
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3350 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003351 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352#if DEBUG_INBOUND_EVENT_DETAILS
3353 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003354 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3355 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356#endif
3357
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003358 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359
3360 policyFlags |= POLICY_FLAG_INJECTED;
3361 if (hasInjectionPermission(injectorPid, injectorUid)) {
3362 policyFlags |= POLICY_FLAG_TRUSTED;
3363 }
3364
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003365 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003368 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3369 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 if (!validateKeyEvent(action)) {
3371 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003374 int32_t flags = incomingKey.getFlags();
3375 int32_t keyCode = incomingKey.getKeyCode();
3376 int32_t metaState = incomingKey.getMetaState();
3377 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003379 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003380 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003381 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3382 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3383 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3386 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003387 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003388
3389 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3390 android::base::Timer t;
3391 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3392 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3393 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3394 std::to_string(t.duration().count()).c_str());
3395 }
3396 }
3397
3398 mLock.lock();
3399 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003400 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3401 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003402 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3403 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003404 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 injectedEntries.push(injectedEntry);
3406 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 }
3408
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003409 case AINPUT_EVENT_TYPE_MOTION: {
3410 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3411 int32_t action = motionEvent->getAction();
3412 size_t pointerCount = motionEvent->getPointerCount();
3413 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3414 int32_t actionButton = motionEvent->getActionButton();
3415 int32_t displayId = motionEvent->getDisplayId();
3416 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3417 return INPUT_EVENT_INJECTION_FAILED;
3418 }
3419
3420 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3421 nsecs_t eventTime = motionEvent->getEventTime();
3422 android::base::Timer t;
3423 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3424 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3425 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3426 std::to_string(t.duration().count()).c_str());
3427 }
3428 }
3429
3430 mLock.lock();
3431 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3432 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3433 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003434 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3435 motionEvent->getSource(), motionEvent->getDisplayId(),
3436 policyFlags, action, actionButton, motionEvent->getFlags(),
3437 motionEvent->getMetaState(), motionEvent->getButtonState(),
3438 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3439 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003440 motionEvent->getRawXCursorPosition(),
3441 motionEvent->getRawYCursorPosition(),
3442 motionEvent->getDownTime(), uint32_t(pointerCount),
3443 pointerProperties, samplePointerCoords,
3444 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 injectedEntries.push(injectedEntry);
3446 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3447 sampleEventTimes += 1;
3448 samplePointerCoords += pointerCount;
3449 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003450 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003451 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003452 motionEvent->getDisplayId(), policyFlags, action,
3453 actionButton, motionEvent->getFlags(),
3454 motionEvent->getMetaState(), motionEvent->getButtonState(),
3455 motionEvent->getClassification(),
3456 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3457 motionEvent->getYPrecision(),
3458 motionEvent->getRawXCursorPosition(),
3459 motionEvent->getRawYCursorPosition(),
3460 motionEvent->getDownTime(), uint32_t(pointerCount),
3461 pointerProperties, samplePointerCoords,
3462 motionEvent->getXOffset(), motionEvent->getYOffset());
3463 injectedEntries.push(nextInjectedEntry);
3464 }
3465 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003469 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472
3473 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3474 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3475 injectionState->injectionIsAsync = true;
3476 }
3477
3478 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003479 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480
3481 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003482 while (!injectedEntries.empty()) {
3483 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3484 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 }
3486
3487 mLock.unlock();
3488
3489 if (needWake) {
3490 mLooper->wake();
3491 }
3492
3493 int32_t injectionResult;
3494 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003495 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496
3497 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3498 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3499 } else {
3500 for (;;) {
3501 injectionResult = injectionState->injectionResult;
3502 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3503 break;
3504 }
3505
3506 nsecs_t remainingTimeout = endTime - now();
3507 if (remainingTimeout <= 0) {
3508#if DEBUG_INJECTION
3509 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511#endif
3512 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3513 break;
3514 }
3515
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003516 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
3518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3520 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 while (injectionState->pendingForegroundDispatches != 0) {
3522#if DEBUG_INJECTION
3523 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003524 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525#endif
3526 nsecs_t remainingTimeout = endTime - now();
3527 if (remainingTimeout <= 0) {
3528#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3530 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531#endif
3532 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3533 break;
3534 }
3535
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003536 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 }
3538 }
3539 }
3540
3541 injectionState->release();
3542 } // release lock
3543
3544#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003545 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003546 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547#endif
3548
3549 return injectionResult;
3550}
3551
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003552std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003553 std::array<uint8_t, 32> calculatedHmac;
3554 std::unique_ptr<VerifiedInputEvent> result;
3555 switch (event.getType()) {
3556 case AINPUT_EVENT_TYPE_KEY: {
3557 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3558 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3559 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3560 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3561 break;
3562 }
3563 case AINPUT_EVENT_TYPE_MOTION: {
3564 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3565 VerifiedMotionEvent verifiedMotionEvent =
3566 verifiedMotionEventFromMotionEvent(motionEvent);
3567 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3568 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3569 break;
3570 }
3571 default: {
3572 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3573 return nullptr;
3574 }
3575 }
3576 if (calculatedHmac == INVALID_HMAC) {
3577 return nullptr;
3578 }
3579 if (calculatedHmac != event.getHmac()) {
3580 return nullptr;
3581 }
3582 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003583}
3584
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003586 return injectorUid == 0 ||
3587 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588}
3589
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003590void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 InjectionState* injectionState = entry->injectionState;
3592 if (injectionState) {
3593#if DEBUG_INJECTION
3594 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003595 "injectorPid=%d, injectorUid=%d",
3596 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597#endif
3598
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003599 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 // Log the outcome since the injector did not wait for the injection result.
3601 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003602 case INPUT_EVENT_INJECTION_SUCCEEDED:
3603 ALOGV("Asynchronous input event injection succeeded.");
3604 break;
3605 case INPUT_EVENT_INJECTION_FAILED:
3606 ALOGW("Asynchronous input event injection failed.");
3607 break;
3608 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3609 ALOGW("Asynchronous input event injection permission denied.");
3610 break;
3611 case INPUT_EVENT_INJECTION_TIMED_OUT:
3612 ALOGW("Asynchronous input event injection timed out.");
3613 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 }
3615 }
3616
3617 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003618 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 }
3620}
3621
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003622void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 InjectionState* injectionState = entry->injectionState;
3624 if (injectionState) {
3625 injectionState->pendingForegroundDispatches += 1;
3626 }
3627}
3628
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003629void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 InjectionState* injectionState = entry->injectionState;
3631 if (injectionState) {
3632 injectionState->pendingForegroundDispatches -= 1;
3633
3634 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003635 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 }
3637 }
3638}
3639
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003640std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3641 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003642 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003643}
3644
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003646 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003647 if (windowHandleToken == nullptr) {
3648 return nullptr;
3649 }
3650
Arthur Hungb92218b2018-08-14 12:00:21 +08003651 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003652 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3653 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003654 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003655 return windowHandle;
3656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003659 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660}
3661
Mady Mellor017bcd12020-06-23 19:12:00 +00003662bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3663 for (auto& it : mWindowHandlesByDisplay) {
3664 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3665 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003666 if (handle->getId() == windowHandle->getId() &&
3667 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003668 if (windowHandle->getInfo()->displayId != it.first) {
3669 ALOGE("Found window %s in display %" PRId32
3670 ", but it should belong to display %" PRId32,
3671 windowHandle->getName().c_str(), it.first,
3672 windowHandle->getInfo()->displayId);
3673 }
3674 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 }
3677 }
3678 return false;
3679}
3680
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003681bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3682 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3683 const bool noInputChannel =
3684 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3685 if (connection != nullptr && noInputChannel) {
3686 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3687 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3688 return false;
3689 }
3690
3691 if (connection == nullptr) {
3692 if (!noInputChannel) {
3693 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3694 }
3695 return false;
3696 }
3697 if (!connection->responsive) {
3698 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3699 return false;
3700 }
3701 return true;
3702}
3703
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003704std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3705 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003706 size_t count = mInputChannelsByToken.count(token);
3707 if (count == 0) {
3708 return nullptr;
3709 }
3710 return mInputChannelsByToken.at(token);
3711}
3712
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003713void InputDispatcher::updateWindowHandlesForDisplayLocked(
3714 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3715 if (inputWindowHandles.empty()) {
3716 // Remove all handles on a display if there are no windows left.
3717 mWindowHandlesByDisplay.erase(displayId);
3718 return;
3719 }
3720
3721 // Since we compare the pointer of input window handles across window updates, we need
3722 // to make sure the handle object for the same window stays unchanged across updates.
3723 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003724 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003725 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003726 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003727 }
3728
3729 std::vector<sp<InputWindowHandle>> newHandles;
3730 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3731 if (!handle->updateInfo()) {
3732 // handle no longer valid
3733 continue;
3734 }
3735
3736 const InputWindowInfo* info = handle->getInfo();
3737 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3738 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3739 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003740 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3741 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3742 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003743 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003744 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003745 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003746 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003747 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003748 }
3749
3750 if (info->displayId != displayId) {
3751 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3752 handle->getName().c_str(), displayId, info->displayId);
3753 continue;
3754 }
3755
Robert Carredd13602020-04-13 17:24:34 -07003756 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3757 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003758 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003759 oldHandle->updateFrom(handle);
3760 newHandles.push_back(oldHandle);
3761 } else {
3762 newHandles.push_back(handle);
3763 }
3764 }
3765
3766 // Insert or replace
3767 mWindowHandlesByDisplay[displayId] = newHandles;
3768}
3769
Arthur Hung72d8dc32020-03-28 00:48:39 +00003770void InputDispatcher::setInputWindows(
3771 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3772 { // acquire lock
3773 std::scoped_lock _l(mLock);
3774 for (auto const& i : handlesPerDisplay) {
3775 setInputWindowsLocked(i.second, i.first);
3776 }
3777 }
3778 // Wake up poll loop since it may need to make new input dispatching choices.
3779 mLooper->wake();
3780}
3781
Arthur Hungb92218b2018-08-14 12:00:21 +08003782/**
3783 * Called from InputManagerService, update window handle list by displayId that can receive input.
3784 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3785 * If set an empty list, remove all handles from the specific display.
3786 * For focused handle, check if need to change and send a cancel event to previous one.
3787 * For removed handle, check if need to send a cancel event if already in touch.
3788 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003789void InputDispatcher::setInputWindowsLocked(
3790 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003791 if (DEBUG_FOCUS) {
3792 std::string windowList;
3793 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3794 windowList += iwh->getName() + " ";
3795 }
3796 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003799 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3800 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3801 const bool noInputWindow =
3802 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3803 if (noInputWindow && window->getToken() != nullptr) {
3804 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3805 window->getName().c_str());
3806 window->releaseChannel();
3807 }
3808 }
3809
Arthur Hung72d8dc32020-03-28 00:48:39 +00003810 // Copy old handles for release if they are no longer present.
3811 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812
Arthur Hung72d8dc32020-03-28 00:48:39 +00003813 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003814
Arthur Hung72d8dc32020-03-28 00:48:39 +00003815 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3816 bool foundHoveredWindow = false;
3817 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3818 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3819 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3820 windowHandle->getInfo()->visible) {
3821 newFocusedWindowHandle = windowHandle;
3822 }
3823 if (windowHandle == mLastHoverWindowHandle) {
3824 foundHoveredWindow = true;
3825 }
3826 }
3827
3828 if (!foundHoveredWindow) {
3829 mLastHoverWindowHandle = nullptr;
3830 }
3831
3832 sp<InputWindowHandle> oldFocusedWindowHandle =
3833 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3834
3835 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3836 if (oldFocusedWindowHandle != nullptr) {
3837 if (DEBUG_FOCUS) {
3838 ALOGD("Focus left window: %s in display %" PRId32,
3839 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003840 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003841 std::shared_ptr<InputChannel> focusedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003842 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3843 if (focusedInputChannel != nullptr) {
3844 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3845 "focus left window");
3846 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3847 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003848 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003849 mFocusedWindowHandlesByDisplay.erase(displayId);
3850 }
3851 if (newFocusedWindowHandle != nullptr) {
3852 if (DEBUG_FOCUS) {
3853 ALOGD("Focus entered window: %s in display %" PRId32,
3854 newFocusedWindowHandle->getName().c_str(), displayId);
3855 }
3856 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3857 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
3859
Arthur Hung72d8dc32020-03-28 00:48:39 +00003860 if (mFocusedDisplayId == displayId) {
3861 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003865 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3866 mTouchStatesByDisplay.find(displayId);
3867 if (stateIt != mTouchStatesByDisplay.end()) {
3868 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003869 for (size_t i = 0; i < state.windows.size();) {
3870 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003871 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003872 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003873 ALOGD("Touched window was removed: %s in display %" PRId32,
3874 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003875 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003876 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003877 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3878 if (touchedInputChannel != nullptr) {
3879 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3880 "touched window was removed");
3881 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003883 state.windows.erase(state.windows.begin() + i);
3884 } else {
3885 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 }
3887 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003888 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003889
Arthur Hung72d8dc32020-03-28 00:48:39 +00003890 // Release information for windows that are no longer present.
3891 // This ensures that unused input channels are released promptly.
3892 // Otherwise, they might stick around until the window handle is destroyed
3893 // which might not happen until the next GC.
3894 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003895 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003896 if (DEBUG_FOCUS) {
3897 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003898 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003899 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003900 }
chaviw291d88a2019-02-14 10:33:58 -08003901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902}
3903
3904void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003905 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003906 if (DEBUG_FOCUS) {
3907 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3908 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3909 }
Chris Yea209fde2020-07-22 13:54:51 -07003910 if (inputApplicationHandle != nullptr &&
3911 inputApplicationHandle->getApplicationToken() != nullptr) {
3912 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003913 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914
Chris Yea209fde2020-07-22 13:54:51 -07003915 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003916 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003917
Chris Yea209fde2020-07-22 13:54:51 -07003918 // If oldFocusedApplicationHandle already exists
3919 if (oldFocusedApplicationHandle != nullptr) {
3920 // If a new focused application handle is different from the old one and
3921 // old focus application info is awaited focused application info.
3922 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3923 mAwaitedFocusedApplication != nullptr &&
3924 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3925 resetNoFocusedWindowTimeoutLocked();
3926 }
3927 // Erase the old application from container first
3928 mFocusedApplicationHandlesByDisplay.erase(displayId);
3929 // Should already get freed after removed from container but just double check.
3930 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003931 }
3932
Chris Yea209fde2020-07-22 13:54:51 -07003933 // Set the new application handle.
3934 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 } // release lock
3936
3937 // Wake up poll loop since it may need to make new input dispatching choices.
3938 mLooper->wake();
3939}
3940
Tiger Huang721e26f2018-07-24 22:26:19 +08003941/**
3942 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3943 * the display not specified.
3944 *
3945 * We track any unreleased events for each window. If a window loses the ability to receive the
3946 * released event, we will send a cancel event to it. So when the focused display is changed, we
3947 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3948 * display. The display-specified events won't be affected.
3949 */
3950void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003951 if (DEBUG_FOCUS) {
3952 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3953 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003954 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003955 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003956
3957 if (mFocusedDisplayId != displayId) {
3958 sp<InputWindowHandle> oldFocusedWindowHandle =
3959 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3960 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003961 std::shared_ptr<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003963 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003964 CancelationOptions
3965 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3966 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003967 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003968 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3969 }
3970 }
3971 mFocusedDisplayId = displayId;
3972
3973 // Sanity check
3974 sp<InputWindowHandle> newFocusedWindowHandle =
3975 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003976 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003977
Tiger Huang721e26f2018-07-24 22:26:19 +08003978 if (newFocusedWindowHandle == nullptr) {
3979 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3980 if (!mFocusedWindowHandlesByDisplay.empty()) {
3981 ALOGE("But another display has a focused window:");
3982 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003983 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003984 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003985 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003986 }
3987 }
3988 }
3989 }
3990
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003991 if (DEBUG_FOCUS) {
3992 logDispatchStateLocked();
3993 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003994 } // release lock
3995
3996 // Wake up poll loop since it may need to make new input dispatching choices.
3997 mLooper->wake();
3998}
3999
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004001 if (DEBUG_FOCUS) {
4002 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
4005 bool changed;
4006 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004007 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008
4009 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4010 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004011 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 }
4013
4014 if (mDispatchEnabled && !enabled) {
4015 resetAndDropEverythingLocked("dispatcher is being disabled");
4016 }
4017
4018 mDispatchEnabled = enabled;
4019 mDispatchFrozen = frozen;
4020 changed = true;
4021 } else {
4022 changed = false;
4023 }
4024
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004025 if (DEBUG_FOCUS) {
4026 logDispatchStateLocked();
4027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 } // release lock
4029
4030 if (changed) {
4031 // Wake up poll loop since it may need to make new input dispatching choices.
4032 mLooper->wake();
4033 }
4034}
4035
4036void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004037 if (DEBUG_FOCUS) {
4038 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
4041 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004042 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043
4044 if (mInputFilterEnabled == enabled) {
4045 return;
4046 }
4047
4048 mInputFilterEnabled = enabled;
4049 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4050 } // release lock
4051
4052 // Wake up poll loop since there might be work to do to drop everything.
4053 mLooper->wake();
4054}
4055
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004056void InputDispatcher::setInTouchMode(bool inTouchMode) {
4057 std::scoped_lock lock(mLock);
4058 mInTouchMode = inTouchMode;
4059}
4060
chaviwfbe5d9c2018-12-26 12:23:37 -08004061bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4062 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004063 if (DEBUG_FOCUS) {
4064 ALOGD("Trivial transfer to same window.");
4065 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004066 return true;
4067 }
4068
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004070 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
chaviwfbe5d9c2018-12-26 12:23:37 -08004072 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4073 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004074 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004075 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 return false;
4077 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004078 if (DEBUG_FOCUS) {
4079 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4080 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004083 if (DEBUG_FOCUS) {
4084 ALOGD("Cannot transfer focus because windows are on different displays.");
4085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 return false;
4087 }
4088
4089 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004090 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4091 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004092 for (size_t i = 0; i < state.windows.size(); i++) {
4093 const TouchedWindow& touchedWindow = state.windows[i];
4094 if (touchedWindow.windowHandle == fromWindowHandle) {
4095 int32_t oldTargetFlags = touchedWindow.targetFlags;
4096 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004098 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004100 int32_t newTargetFlags = oldTargetFlags &
4101 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4102 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004103 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104
Jeff Brownf086ddb2014-02-11 14:28:48 -08004105 found = true;
4106 goto Found;
4107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 }
4109 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004112 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004113 if (DEBUG_FOCUS) {
4114 ALOGD("Focus transfer failed because from window did not have focus.");
4115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 return false;
4117 }
4118
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004119 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4120 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004121 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004122 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 CancelationOptions
4124 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4125 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004127 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 }
4129
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004130 if (DEBUG_FOCUS) {
4131 logDispatchStateLocked();
4132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 } // release lock
4134
4135 // Wake up poll loop since it may need to make new input dispatching choices.
4136 mLooper->wake();
4137 return true;
4138}
4139
4140void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004141 if (DEBUG_FOCUS) {
4142 ALOGD("Resetting and dropping all events (%s).", reason);
4143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144
4145 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4146 synthesizeCancelationEventsForAllConnectionsLocked(options);
4147
4148 resetKeyRepeatLocked();
4149 releasePendingEventLocked();
4150 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004151 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004153 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004154 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004156 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157}
4158
4159void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 dumpDispatchStateLocked(dump);
4162
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 std::istringstream stream(dump);
4164 std::string line;
4165
4166 while (std::getline(stream, line, '\n')) {
4167 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169}
4170
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004172 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4173 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4174 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004175 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176
Tiger Huang721e26f2018-07-24 22:26:19 +08004177 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4178 dump += StringPrintf(INDENT "FocusedApplications:\n");
4179 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4180 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004181 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004182 const std::chrono::duration timeout =
4183 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004185 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004186 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004189 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004191
4192 if (!mFocusedWindowHandlesByDisplay.empty()) {
4193 dump += StringPrintf(INDENT "FocusedWindows:\n");
4194 for (auto& it : mFocusedWindowHandlesByDisplay) {
4195 const int32_t displayId = it.first;
4196 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4198 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004199 }
4200 } else {
4201 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004204 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004206 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4207 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 state.displayId, toString(state.down), toString(state.split),
4210 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004211 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004213 for (size_t i = 0; i < state.windows.size(); i++) {
4214 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004215 dump += StringPrintf(INDENT4
4216 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4217 i, touchedWindow.windowHandle->getName().c_str(),
4218 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004219 }
4220 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004222 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004223 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004224 dump += INDENT3 "Portal windows:\n";
4225 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004226 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4228 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004229 }
4230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004233 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 }
4235
Arthur Hungb92218b2018-08-14 12:00:21 +08004236 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004238 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004239 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004240 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004241 dump += INDENT2 "Windows:\n";
4242 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004243 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004244 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245
Arthur Hungb92218b2018-08-14 12:00:21 +08004246 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004248 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004249 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004251 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 i, windowInfo->name.c_str(), windowInfo->displayId,
4253 windowInfo->portalToDisplayId,
4254 toString(windowInfo->paused),
4255 toString(windowInfo->hasFocus),
4256 toString(windowInfo->hasWallpaper),
4257 toString(windowInfo->visible),
4258 toString(windowInfo->canReceiveKeys),
Michael Wright8759d672020-07-21 00:46:45 +01004259 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004260 static_cast<int32_t>(windowInfo->type),
4261 windowInfo->frameLeft, windowInfo->frameTop,
4262 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004263 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004264 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004265 dump += StringPrintf(", inputFeatures=%s",
4266 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004267 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4268 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004269 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004270 millis(windowInfo->dispatchingTimeout));
chaviw1ff3d1e2020-07-01 15:53:47 -07004271 windowInfo->transform.dump(dump, INDENT4 "transform=");
Arthur Hungb92218b2018-08-14 12:00:21 +08004272 }
4273 } else {
4274 dump += INDENT2 "Windows: <none>\n";
4275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 }
4277 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004278 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 }
4280
Michael Wright3dd60e22019-03-27 22:06:44 +00004281 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004283 const std::vector<Monitor>& monitors = it.second;
4284 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4285 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 }
4287 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004288 const std::vector<Monitor>& monitors = it.second;
4289 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4290 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004293 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295
4296 nsecs_t currentTime = now();
4297
4298 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004299 if (!mRecentQueue.empty()) {
4300 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4301 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004302 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004304 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004307 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 }
4309
4310 // Dump event currently being dispatched.
4311 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004312 dump += INDENT "PendingEvent:\n";
4313 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004315 dump += StringPrintf(", age=%" PRId64 "ms\n",
4316 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004318 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 }
4320
4321 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004322 if (!mInboundQueue.empty()) {
4323 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4324 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004325 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004327 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 }
4329 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004330 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004333 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004334 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004335 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4336 const KeyReplacement& replacement = pair.first;
4337 int32_t newKeyCode = pair.second;
4338 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004340 }
4341 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004342 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004343 }
4344
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004345 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004346 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004347 for (const auto& pair : mConnectionsByFd) {
4348 const sp<Connection>& connection = pair.second;
4349 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004350 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004351 pair.first, connection->getInputChannelName().c_str(),
4352 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004353 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004355 if (!connection->outboundQueue.empty()) {
4356 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4357 connection->outboundQueue.size());
4358 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 dump.append(INDENT4);
4360 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004361 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4362 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004363 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004364 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 }
4366 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004367 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004370 if (!connection->waitQueue.empty()) {
4371 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4372 connection->waitQueue.size());
4373 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004374 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004376 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004377 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004378 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004379 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004380 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 }
4382 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004383 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385 }
4386 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004387 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 }
4389
4390 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004391 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4392 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004394 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 }
4396
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004397 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004398 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4399 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4400 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401}
4402
Michael Wright3dd60e22019-03-27 22:06:44 +00004403void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4404 const size_t numMonitors = monitors.size();
4405 for (size_t i = 0; i < numMonitors; i++) {
4406 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004407 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004408 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4409 dump += "\n";
4410 }
4411}
4412
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004413status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004415 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416#endif
4417
4418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004419 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004420 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004421 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004423 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 return BAD_VALUE;
4425 }
4426
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004427 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
4429 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004430 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004431 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4434 } // release lock
4435
4436 // Wake the looper because some connections have changed.
4437 mLooper->wake();
4438 return OK;
4439}
4440
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004441status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004443 { // acquire lock
4444 std::scoped_lock _l(mLock);
4445
4446 if (displayId < 0) {
4447 ALOGW("Attempted to register input monitor without a specified display.");
4448 return BAD_VALUE;
4449 }
4450
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004451 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004452 ALOGW("Attempted to register input monitor without an identifying token.");
4453 return BAD_VALUE;
4454 }
4455
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004456 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004457
4458 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004459 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004460 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004461
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004462 auto& monitorsByDisplay =
4463 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004464 monitorsByDisplay[displayId].emplace_back(inputChannel);
4465
4466 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004467 }
4468 // Wake the looper because some connections have changed.
4469 mLooper->wake();
4470 return OK;
4471}
4472
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004473status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004475 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476#endif
4477
4478 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004479 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480
4481 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4482 if (status) {
4483 return status;
4484 }
4485 } // release lock
4486
4487 // Wake the poll loop because removing the connection may have changed the current
4488 // synchronization state.
4489 mLooper->wake();
4490 return OK;
4491}
4492
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004493status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004494 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004495 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004496 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004498 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 return BAD_VALUE;
4500 }
4501
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004502 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004503 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004504
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 if (connection->monitor) {
4506 removeMonitorChannelLocked(inputChannel);
4507 }
4508
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004509 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
4511 nsecs_t currentTime = now();
4512 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4513
4514 connection->status = Connection::STATUS_ZOMBIE;
4515 return OK;
4516}
4517
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004518void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004519 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4520 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4521}
4522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004524 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004525 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004527 std::vector<Monitor>& monitors = it->second;
4528 const size_t numMonitors = monitors.size();
4529 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004530 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531 monitors.erase(monitors.begin() + i);
4532 break;
4533 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004534 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004535 if (monitors.empty()) {
4536 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004537 } else {
4538 ++it;
4539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 }
4541}
4542
Michael Wright3dd60e22019-03-27 22:06:44 +00004543status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4544 { // acquire lock
4545 std::scoped_lock _l(mLock);
4546 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4547
4548 if (!foundDisplayId) {
4549 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4550 return BAD_VALUE;
4551 }
4552 int32_t displayId = foundDisplayId.value();
4553
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004554 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4555 mTouchStatesByDisplay.find(displayId);
4556 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004557 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4558 return BAD_VALUE;
4559 }
4560
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004561 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004562 std::optional<int32_t> foundDeviceId;
4563 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004564 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004565 foundDeviceId = state.deviceId;
4566 }
4567 }
4568 if (!foundDeviceId || !state.down) {
4569 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004570 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004571 return BAD_VALUE;
4572 }
4573 int32_t deviceId = foundDeviceId.value();
4574
4575 // Send cancel events to all the input channels we're stealing from.
4576 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004577 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004578 options.deviceId = deviceId;
4579 options.displayId = displayId;
4580 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004581 std::shared_ptr<InputChannel> channel =
4582 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004583 if (channel != nullptr) {
4584 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4585 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004586 }
4587 // Then clear the current touch state so we stop dispatching to them as well.
4588 state.filterNonMonitors();
4589 }
4590 return OK;
4591}
4592
Michael Wright3dd60e22019-03-27 22:06:44 +00004593std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4594 const sp<IBinder>& token) {
4595 for (const auto& it : mGestureMonitorsByDisplay) {
4596 const std::vector<Monitor>& monitors = it.second;
4597 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004598 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004599 return it.first;
4600 }
4601 }
4602 }
4603 return std::nullopt;
4604}
4605
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004606sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004607 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004608 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004609 }
4610
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004611 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004612 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004613 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004614 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 }
4616 }
Robert Carr4e670e52018-08-15 13:26:12 -07004617
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004618 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619}
4620
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004621void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004622 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004623 removeByValue(mConnectionsByFd, connection);
4624}
4625
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004626void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4627 const sp<Connection>& connection, uint32_t seq,
4628 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004629 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4630 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 commandEntry->connection = connection;
4632 commandEntry->eventTime = currentTime;
4633 commandEntry->seq = seq;
4634 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004635 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636}
4637
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4639 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004641 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004643 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4644 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004646 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647}
4648
chaviw0c06c6e2019-01-09 13:27:07 -08004649void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004651 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4652 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004653 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4654 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004655 commandEntry->oldToken = oldToken;
4656 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004657 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004658}
4659
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4661 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4662 // is already healthy again. Don't raise ANR in this situation
4663 if (connection->waitQueue.empty()) {
4664 ALOGI("Not raising ANR because the connection %s has recovered",
4665 connection->inputChannel->getName().c_str());
4666 return;
4667 }
4668 /**
4669 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4670 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4671 * has changed. This could cause newer entries to time out before the already dispatched
4672 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4673 * processes the events linearly. So providing information about the oldest entry seems to be
4674 * most useful.
4675 */
4676 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4677 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4678 std::string reason =
4679 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4680 connection->inputChannel->getName().c_str(),
4681 ns2ms(currentWait),
4682 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004684 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4685 reason);
4686
4687 std::unique_ptr<CommandEntry> commandEntry =
4688 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4689 commandEntry->inputApplicationHandle = nullptr;
4690 commandEntry->inputChannel = connection->inputChannel;
4691 commandEntry->reason = std::move(reason);
4692 postCommandLocked(std::move(commandEntry));
4693}
4694
Chris Yea209fde2020-07-22 13:54:51 -07004695void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004696 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4697 application->getName().c_str());
4698
4699 updateLastAnrStateLocked(application, reason);
4700
4701 std::unique_ptr<CommandEntry> commandEntry =
4702 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4703 commandEntry->inputApplicationHandle = application;
4704 commandEntry->inputChannel = nullptr;
4705 commandEntry->reason = std::move(reason);
4706 postCommandLocked(std::move(commandEntry));
4707}
4708
4709void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4710 const std::string& reason) {
4711 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4712 updateLastAnrStateLocked(windowLabel, reason);
4713}
4714
Chris Yea209fde2020-07-22 13:54:51 -07004715void InputDispatcher::updateLastAnrStateLocked(
4716 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004717 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4718 updateLastAnrStateLocked(windowLabel, reason);
4719}
4720
4721void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4722 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004724 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 struct tm tm;
4726 localtime_r(&t, &tm);
4727 char timestr[64];
4728 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004729 mLastAnrState.clear();
4730 mLastAnrState += INDENT "ANR:\n";
4731 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004732 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4733 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004734 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735}
4736
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004737void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 mLock.unlock();
4739
4740 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4741
4742 mLock.lock();
4743}
4744
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004745void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 sp<Connection> connection = commandEntry->connection;
4747
4748 if (connection->status != Connection::STATUS_ZOMBIE) {
4749 mLock.unlock();
4750
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004751 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
4753 mLock.lock();
4754 }
4755}
4756
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004757void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004758 sp<IBinder> oldToken = commandEntry->oldToken;
4759 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004760 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004761 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004762 mLock.lock();
4763}
4764
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004765void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004766 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004767 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 mLock.unlock();
4769
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004770 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004771 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772
4773 mLock.lock();
4774
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004775 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4777 } else {
4778 // stop waking up for events in this connection, it is already not responding
4779 sp<Connection> connection = getConnectionLocked(token);
4780 if (connection == nullptr) {
4781 return;
4782 }
4783 cancelEventsForAnrLocked(connection);
4784 }
4785}
4786
Chris Yea209fde2020-07-22 13:54:51 -07004787void InputDispatcher::extendAnrTimeoutsLocked(
4788 const std::shared_ptr<InputApplicationHandle>& application,
4789 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790 sp<Connection> connection = getConnectionLocked(connectionToken);
4791 if (connection == nullptr) {
4792 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4793 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004794 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795 mAwaitedFocusedApplication = application;
4796 } else {
4797 // It's also possible that the connection already disappeared. No action necessary.
4798 }
4799 return;
4800 }
4801
4802 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004803 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804
4805 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004806 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807 for (DispatchEntry* entry : connection->waitQueue) {
4808 if (newTimeout >= entry->timeoutTime) {
4809 // Already removed old entries when connection was marked unresponsive
4810 entry->timeoutTime = newTimeout;
4811 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4812 }
4813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814}
4815
4816void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4817 CommandEntry* commandEntry) {
4818 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004819 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820
4821 mLock.unlock();
4822
Michael Wright2b3c3302018-03-02 17:19:13 +00004823 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004824 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004825 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004826 : nullptr;
4827 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004828 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4829 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004830 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832
4833 mLock.lock();
4834
4835 if (delay < 0) {
4836 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4837 } else if (!delay) {
4838 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4839 } else {
4840 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4841 entry->interceptKeyWakeupTime = now() + delay;
4842 }
4843 entry->release();
4844}
4845
chaviwfd6d3512019-03-25 13:23:49 -07004846void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4847 mLock.unlock();
4848 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4849 mLock.lock();
4850}
4851
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852/**
4853 * Connection is responsive if it has no events in the waitQueue that are older than the
4854 * current time.
4855 */
4856static bool isConnectionResponsive(const Connection& connection) {
4857 const nsecs_t currentTime = now();
4858 for (const DispatchEntry* entry : connection.waitQueue) {
4859 if (entry->timeoutTime < currentTime) {
4860 return false;
4861 }
4862 }
4863 return true;
4864}
4865
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004866void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004868 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004870 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871
4872 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004873 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004874 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004875 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004877 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004878 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004879 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004880 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4881 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004882 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004883 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004884
4885 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004886 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004887 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4888 restartEvent =
4889 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004890 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004891 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4892 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4893 handled);
4894 } else {
4895 restartEvent = false;
4896 }
4897
4898 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004899 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004900 // contents of the wait queue to have been drained, so we need to double-check
4901 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004902 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4903 if (dispatchEntryIt != connection->waitQueue.end()) {
4904 dispatchEntry = *dispatchEntryIt;
4905 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004906 mAnrTracker.erase(dispatchEntry->timeoutTime,
4907 connection->inputChannel->getConnectionToken());
4908 if (!connection->responsive) {
4909 connection->responsive = isConnectionResponsive(*connection);
4910 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004911 traceWaitQueueLength(connection);
4912 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004913 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004914 traceOutboundQueueLength(connection);
4915 } else {
4916 releaseDispatchEntry(dispatchEntry);
4917 }
4918 }
4919
4920 // Start the next dispatch cycle for this connection.
4921 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922}
4923
4924bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004925 DispatchEntry* dispatchEntry,
4926 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004927 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004928 if (!handled) {
4929 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004930 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004931 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004932 return false;
4933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004935 // Get the fallback key state.
4936 // Clear it out after dispatching the UP.
4937 int32_t originalKeyCode = keyEntry->keyCode;
4938 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4939 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4940 connection->inputState.removeFallbackKey(originalKeyCode);
4941 }
4942
4943 if (handled || !dispatchEntry->hasForegroundTarget()) {
4944 // If the application handles the original key for which we previously
4945 // generated a fallback or if the window is not a foreground window,
4946 // then cancel the associated fallback key, if any.
4947 if (fallbackKeyCode != -1) {
4948 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004950 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4952 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4953 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004955 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004956 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957
4958 mLock.unlock();
4959
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004960 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004961 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962
4963 mLock.lock();
4964
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004965 // Cancel the fallback key.
4966 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004968 "application handled the original non-fallback key "
4969 "or is no longer a foreground target, "
4970 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 options.keyCode = fallbackKeyCode;
4972 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004974 connection->inputState.removeFallbackKey(originalKeyCode);
4975 }
4976 } else {
4977 // If the application did not handle a non-fallback key, first check
4978 // that we are in a good state to perform unhandled key event processing
4979 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004980 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004981 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004983 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 "since this is not an initial down. "
4985 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4986 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004988 return false;
4989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004991 // Dispatch the unhandled key to the policy.
4992#if DEBUG_OUTBOUND_EVENT_DETAILS
4993 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004994 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4995 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004996#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004997 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004998
4999 mLock.unlock();
5000
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005001 bool fallback =
5002 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5003 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005004
5005 mLock.lock();
5006
5007 if (connection->status != Connection::STATUS_NORMAL) {
5008 connection->inputState.removeFallbackKey(originalKeyCode);
5009 return false;
5010 }
5011
5012 // Latch the fallback keycode for this key on an initial down.
5013 // The fallback keycode cannot change at any other point in the lifecycle.
5014 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005016 fallbackKeyCode = event.getKeyCode();
5017 } else {
5018 fallbackKeyCode = AKEYCODE_UNKNOWN;
5019 }
5020 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5021 }
5022
5023 ALOG_ASSERT(fallbackKeyCode != -1);
5024
5025 // Cancel the fallback key if the policy decides not to send it anymore.
5026 // We will continue to dispatch the key to the policy but we will no
5027 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005028 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5029 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005030#if DEBUG_OUTBOUND_EVENT_DETAILS
5031 if (fallback) {
5032 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005033 "as a fallback for %d, but on the DOWN it had requested "
5034 "to send %d instead. Fallback canceled.",
5035 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005036 } else {
5037 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005038 "but on the DOWN it had requested to send %d. "
5039 "Fallback canceled.",
5040 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005041 }
5042#endif
5043
5044 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5045 "canceling fallback, policy no longer desires it");
5046 options.keyCode = fallbackKeyCode;
5047 synthesizeCancelationEventsForConnectionLocked(connection, options);
5048
5049 fallback = false;
5050 fallbackKeyCode = AKEYCODE_UNKNOWN;
5051 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005052 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005053 }
5054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055
5056#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005057 {
5058 std::string msg;
5059 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5060 connection->inputState.getFallbackKeys();
5061 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005062 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005064 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005065 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005066 }
5067#endif
5068
5069 if (fallback) {
5070 // Restart the dispatch cycle using the fallback key.
5071 keyEntry->eventTime = event.getEventTime();
5072 keyEntry->deviceId = event.getDeviceId();
5073 keyEntry->source = event.getSource();
5074 keyEntry->displayId = event.getDisplayId();
5075 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5076 keyEntry->keyCode = fallbackKeyCode;
5077 keyEntry->scanCode = event.getScanCode();
5078 keyEntry->metaState = event.getMetaState();
5079 keyEntry->repeatCount = event.getRepeatCount();
5080 keyEntry->downTime = event.getDownTime();
5081 keyEntry->syntheticRepeat = false;
5082
5083#if DEBUG_OUTBOUND_EVENT_DETAILS
5084 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005085 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5086 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005087#endif
5088 return true; // restart the event
5089 } else {
5090#if DEBUG_OUTBOUND_EVENT_DETAILS
5091 ALOGD("Unhandled key event: No fallback key.");
5092#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005093
5094 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005095 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 }
5097 }
5098 return false;
5099}
5100
5101bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005102 DispatchEntry* dispatchEntry,
5103 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104 return false;
5105}
5106
5107void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5108 mLock.unlock();
5109
5110 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5111
5112 mLock.lock();
5113}
5114
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005115KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5116 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005117 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005118 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5119 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005120 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121}
5122
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005123void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5124 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 // TODO Write some statistics about how long we spend waiting.
5126}
5127
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005128/**
5129 * Report the touch event latency to the statsd server.
5130 * Input events are reported for statistics if:
5131 * - This is a touchscreen event
5132 * - InputFilter is not enabled
5133 * - Event is not injected or synthesized
5134 *
5135 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5136 * from getting aggregated with the "old" data.
5137 */
5138void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5139 REQUIRES(mLock) {
5140 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5141 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5142 if (!reportForStatistics) {
5143 return;
5144 }
5145
5146 if (mTouchStatistics.shouldReport()) {
5147 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5148 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5149 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5150 mTouchStatistics.reset();
5151 }
5152 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5153 mTouchStatistics.addValue(latencyMicros);
5154}
5155
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156void InputDispatcher::traceInboundQueueLengthLocked() {
5157 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005158 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
5160}
5161
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005162void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 if (ATRACE_ENABLED()) {
5164 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005165 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005166 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 }
5168}
5169
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005170void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 if (ATRACE_ENABLED()) {
5172 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005173 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005174 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 }
5176}
5177
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005178void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005179 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005181 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 dumpDispatchStateLocked(dump);
5183
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005184 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005185 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005186 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 }
5188}
5189
5190void InputDispatcher::monitor() {
5191 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005192 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005194 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195}
5196
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005197/**
5198 * Wake up the dispatcher and wait until it processes all events and commands.
5199 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5200 * this method can be safely called from any thread, as long as you've ensured that
5201 * the work you are interested in completing has already been queued.
5202 */
5203bool InputDispatcher::waitForIdle() {
5204 /**
5205 * Timeout should represent the longest possible time that a device might spend processing
5206 * events and commands.
5207 */
5208 constexpr std::chrono::duration TIMEOUT = 100ms;
5209 std::unique_lock lock(mLock);
5210 mLooper->wake();
5211 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5212 return result == std::cv_status::no_timeout;
5213}
5214
Vishnu Naire798b472020-07-23 13:52:21 -07005215/**
5216 * Sets focus to the window identified by the token. This must be called
5217 * after updating any input window handles.
5218 *
5219 * Params:
5220 * request.token - input channel token used to identify the window that should gain focus.
5221 * request.focusedToken - the token that the caller expects currently to be focused. If the
5222 * specified token does not match the currently focused window, this request will be dropped.
5223 * If the specified focused token matches the currently focused window, the call will succeed.
5224 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5225 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5226 * when requesting the focus change. This determines which request gets
5227 * precedence if there is a focus change request from another source such as pointer down.
5228 */
5229void InputDispatcher::setFocusedWindow(const FocusRequest&) {}
Garfield Tane84e6f92019-08-29 17:28:41 -07005230} // namespace android::inputdispatcher