blob: 44f26b0de8c19c3fa3ad9799e29ebcb9789bdf97 [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
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001081void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus,
1082 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001083 if (mPendingEvent != nullptr) {
1084 // Move the pending event to the front of the queue. This will give the chance
1085 // for the pending event to get dispatched to the newly focused window
1086 mInboundQueue.push_front(mPendingEvent);
1087 mPendingEvent = nullptr;
1088 }
1089
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001090 FocusEntry* focusEntry =
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001091 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001092
1093 // This event should go to the front of the queue, but behind all other focus events
1094 // Find the last focus event, and insert right after it
1095 std::deque<EventEntry*>::reverse_iterator it =
1096 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1097 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1098
1099 // Maintain the order of focus events. Insert the entry after all other focus events.
1100 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001101}
1102
1103void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001104 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001105 if (channel == nullptr) {
1106 return; // Window has gone away
1107 }
1108 InputTarget target;
1109 target.inputChannel = channel;
1110 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1111 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001112 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1113 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001114 std::string reason = std::string("reason=").append(entry->reason);
1115 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001116 dispatchEventLocked(currentTime, entry, {target});
1117}
1118
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 if (!entry->dispatchInProgress) {
1123 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1124 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1125 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1126 if (mKeyRepeatState.lastKeyEntry &&
1127 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 // We have seen two identical key downs in a row which indicates that the device
1129 // driver is automatically generating key repeats itself. We take note of the
1130 // repeat here, but we disable our own next key repeat timer since it is clear that
1131 // we will not need to synthesize key repeats ourselves.
1132 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1133 resetKeyRepeatLocked();
1134 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1135 } else {
1136 // Not a repeat. Save key down state in case we do see a repeat later.
1137 resetKeyRepeatLocked();
1138 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1139 }
1140 mKeyRepeatState.lastKeyEntry = entry;
1141 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 resetKeyRepeatLocked();
1144 }
1145
1146 if (entry->repeatCount == 1) {
1147 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1148 } else {
1149 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1150 }
1151
1152 entry->dispatchInProgress = true;
1153
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001154 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156
1157 // Handle case where the policy asked us to try again later last time.
1158 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1159 if (currentTime < entry->interceptKeyWakeupTime) {
1160 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1161 *nextWakeupTime = entry->interceptKeyWakeupTime;
1162 }
1163 return false; // wait until next wakeup
1164 }
1165 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1166 entry->interceptKeyWakeupTime = 0;
1167 }
1168
1169 // Give the policy a chance to intercept the key.
1170 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1171 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001172 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001173 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001174 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001175 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001176 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 }
1179 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001180 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 entry->refCount += 1;
1182 return false; // wait for the command to run
1183 } else {
1184 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1185 }
1186 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 if (*dropReason == DropReason::NOT_DROPPED) {
1188 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
1190 }
1191
1192 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001193 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001195 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001197 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 return true;
1199 }
1200
1201 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001202 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001204 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1206 return false;
1207 }
1208
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001209 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1211 return true;
1212 }
1213
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001214 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001215 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216
1217 // Dispatch the key.
1218 dispatchEventLocked(currentTime, entry, inputTargets);
1219 return true;
1220}
1221
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001222void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001224 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1226 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001227 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1228 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1229 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230#endif
1231}
1232
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1234 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001235 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 entry->dispatchInProgress = true;
1239
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001240 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 }
1242
1243 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001244 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001246 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 return true;
1249 }
1250
1251 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1252
1253 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001254 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255
1256 bool conflictingPointerActions = false;
1257 int32_t injectionResult;
1258 if (isPointerEvent) {
1259 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001261 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 } else {
1264 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001266 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1269 return false;
1270 }
1271
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001272 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001273 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1274 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1275 return true;
1276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001278 CancelationOptions::Mode mode(isPointerEvent
1279 ? CancelationOptions::CANCEL_POINTER_EVENTS
1280 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1281 CancelationOptions options(mode, "input event injection failed");
1282 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 return true;
1284 }
1285
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001286 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001287 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001289 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001290 std::unordered_map<int32_t, TouchState>::iterator it =
1291 mTouchStatesByDisplay.find(entry->displayId);
1292 if (it != mTouchStatesByDisplay.end()) {
1293 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001294 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001295 // The event has gone through these portal windows, so we add monitoring targets of
1296 // the corresponding displays as well.
1297 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001298 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001299 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001301 }
1302 }
1303 }
1304 }
1305
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 // Dispatch the motion.
1307 if (conflictingPointerActions) {
1308 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 synthesizeCancelationEventsForAllConnectionsLocked(options);
1311 }
1312 dispatchEventLocked(currentTime, entry, inputTargets);
1313 return true;
1314}
1315
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001316void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001318 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001319 ", policyFlags=0x%x, "
1320 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1321 "metaState=0x%x, buttonState=0x%x,"
1322 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001323 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1324 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1325 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001327 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329 "x=%f, y=%f, pressure=%f, size=%f, "
1330 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1331 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001332 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1338 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1339 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1340 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1341 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 }
1343#endif
1344}
1345
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001346void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1347 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001348 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349#if DEBUG_DISPATCH_CYCLE
1350 ALOGD("dispatchEventToCurrentInputTargets");
1351#endif
1352
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001353 updateInteractionTokensLocked(*eventEntry, inputTargets);
1354
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1356
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001359 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001360 sp<Connection> connection =
1361 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001362 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001363 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001365 if (DEBUG_FOCUS) {
1366 ALOGD("Dropping event delivery to target with channel '%s' because it "
1367 "is no longer registered with the input dispatcher.",
1368 inputTarget.inputChannel->getName().c_str());
1369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 }
1371 }
1372}
1373
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001374void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1375 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1376 // If the policy decides to close the app, we will get a channel removal event via
1377 // unregisterInputChannel, and will clean up the connection that way. We are already not
1378 // sending new pointers to the connection when it blocked, but focused events will continue to
1379 // pile up.
1380 ALOGW("Canceling events for %s because it is unresponsive",
1381 connection->inputChannel->getName().c_str());
1382 if (connection->status == Connection::STATUS_NORMAL) {
1383 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1384 "application not responding");
1385 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 }
1387}
1388
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001389void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001390 if (DEBUG_FOCUS) {
1391 ALOGD("Resetting ANR timeouts.");
1392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
1394 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001395 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001396 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397}
1398
Tiger Huang721e26f2018-07-24 22:26:19 +08001399/**
1400 * Get the display id that the given event should go to. If this event specifies a valid display id,
1401 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1402 * Focused display is the display that the user most recently interacted with.
1403 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001405 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001406 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001407 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001408 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1409 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001410 break;
1411 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001413 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1414 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 break;
1416 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001417 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001418 case EventEntry::Type::CONFIGURATION_CHANGED:
1419 case EventEntry::Type::DEVICE_RESET: {
1420 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001421 return ADISPLAY_ID_NONE;
1422 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001423 }
1424 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1425}
1426
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001427bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1428 const char* focusedWindowName) {
1429 if (mAnrTracker.empty()) {
1430 // already processed all events that we waited for
1431 mKeyIsWaitingForEventsTimeout = std::nullopt;
1432 return false;
1433 }
1434
1435 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1436 // Start the timer
1437 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1438 "focus to change",
1439 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001440 mKeyIsWaitingForEventsTimeout = currentTime +
1441 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1442 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001443 return true;
1444 }
1445
1446 // We still have pending events, and already started the timer
1447 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1448 return true; // Still waiting
1449 }
1450
1451 // Waited too long, and some connection still hasn't processed all motions
1452 // Just send the key to the focused window
1453 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1454 focusedWindowName);
1455 mKeyIsWaitingForEventsTimeout = std::nullopt;
1456 return false;
1457}
1458
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001460 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001461 std::vector<InputTarget>& inputTargets,
1462 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001463 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464
Tiger Huang721e26f2018-07-24 22:26:19 +08001465 int32_t displayId = getTargetDisplayId(entry);
1466 sp<InputWindowHandle> focusedWindowHandle =
1467 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001468 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001469 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1470
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 // If there is no currently focused window and no focused application
1472 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001473 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1474 ALOGI("Dropping %s event because there is no focused window or focused application in "
1475 "display %" PRId32 ".",
1476 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001477 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001480 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1481 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1482 // start interacting with another application via touch (app switch). This code can be removed
1483 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1484 // an app is expected to have a focused window.
1485 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1486 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1487 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001488 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1489 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1490 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001491 mAwaitedFocusedApplication = focusedApplicationHandle;
1492 ALOGW("Waiting because no window has focus but %s may eventually add a "
1493 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001494 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001495 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1496 return INPUT_EVENT_INJECTION_PENDING;
1497 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1498 // Already raised ANR. Drop the event
1499 ALOGE("Dropping %s event because there is no focused window",
1500 EventEntry::typeToString(entry.type));
1501 return INPUT_EVENT_INJECTION_FAILED;
1502 } else {
1503 // Still waiting for the focused window
1504 return INPUT_EVENT_INJECTION_PENDING;
1505 }
1506 }
1507
1508 // we have a valid, non-null focused window
1509 resetNoFocusedWindowTimeoutLocked();
1510
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001512 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001513 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001516 if (focusedWindowHandle->getInfo()->paused) {
1517 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1518 return INPUT_EVENT_INJECTION_PENDING;
1519 }
1520
1521 // If the event is a key event, then we must wait for all previous events to
1522 // complete before delivering it because previous events may have the
1523 // side-effect of transferring focus to a different window and we want to
1524 // ensure that the following keys are sent to the new window.
1525 //
1526 // Suppose the user touches a button in a window then immediately presses "A".
1527 // If the button causes a pop-up window to appear then we want to ensure that
1528 // the "A" key is delivered to the new pop-up window. This is because users
1529 // often anticipate pending UI changes when typing on a keyboard.
1530 // To obtain this behavior, we must serialize key events with respect to all
1531 // prior input events.
1532 if (entry.type == EventEntry::Type::KEY) {
1533 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1534 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1535 return INPUT_EVENT_INJECTION_PENDING;
1536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538
1539 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001540 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001541 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1542 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
1544 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001545 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546}
1547
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001548/**
1549 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1550 * that are currently unresponsive.
1551 */
1552std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1553 const std::vector<TouchedMonitor>& monitors) const {
1554 std::vector<TouchedMonitor> responsiveMonitors;
1555 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1556 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1557 sp<Connection> connection = getConnectionLocked(
1558 monitor.monitor.inputChannel->getConnectionToken());
1559 if (connection == nullptr) {
1560 ALOGE("Could not find connection for monitor %s",
1561 monitor.monitor.inputChannel->getName().c_str());
1562 return false;
1563 }
1564 if (!connection->responsive) {
1565 ALOGW("Unresponsive monitor %s will not get the new gesture",
1566 connection->inputChannel->getName().c_str());
1567 return false;
1568 }
1569 return true;
1570 });
1571 return responsiveMonitors;
1572}
1573
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 std::vector<InputTarget>& inputTargets,
1577 nsecs_t* nextWakeupTime,
1578 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001579 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 enum InjectionPermission {
1581 INJECTION_PERMISSION_UNKNOWN,
1582 INJECTION_PERMISSION_GRANTED,
1583 INJECTION_PERMISSION_DENIED
1584 };
1585
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 // For security reasons, we defer updating the touch state until we are sure that
1587 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001588 int32_t displayId = entry.displayId;
1589 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1591
1592 // Update the touch state as needed based on the properties of the touch event.
1593 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1594 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001595 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1596 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001598 // Copy current touch state into tempTouchState.
1599 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1600 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001601 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001602 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001603 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1604 mTouchStatesByDisplay.find(displayId);
1605 if (oldStateIt != mTouchStatesByDisplay.end()) {
1606 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001607 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001608 }
1609
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001610 bool isSplit = tempTouchState.split;
1611 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1612 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1613 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1615 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1616 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1617 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1618 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001619 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 bool wrongDevice = false;
1621 if (newGesture) {
1622 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001623 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001624 ALOGI("Dropping event because a pointer for a different device is already down "
1625 "in display %" PRId32,
1626 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001627 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1629 switchedDevice = false;
1630 wrongDevice = true;
1631 goto Failed;
1632 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001633 tempTouchState.reset();
1634 tempTouchState.down = down;
1635 tempTouchState.deviceId = entry.deviceId;
1636 tempTouchState.source = entry.source;
1637 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001639 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001640 ALOGI("Dropping move event because a pointer for a different device is already active "
1641 "in display %" PRId32,
1642 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001643 // TODO: test multiple simultaneous input streams.
1644 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1645 switchedDevice = false;
1646 wrongDevice = true;
1647 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 }
1649
1650 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1651 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1652
Garfield Tan00f511d2019-06-12 16:55:40 -07001653 int32_t x;
1654 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001656 // Always dispatch mouse events to cursor position.
1657 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001658 x = int32_t(entry.xCursorPosition);
1659 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001660 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001661 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1662 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001663 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001664 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001665 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001666 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1667 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001668
1669 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001670 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001671 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 if (newTouchedWindowHandle != nullptr &&
1675 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001676 // New window supports splitting, but we should never split mouse events.
1677 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 } else if (isSplit) {
1679 // New window does not support splitting but we have already split events.
1680 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001681 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 }
1683
1684 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001685 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001687 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001688 }
1689
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001690 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1691 ALOGI("Not sending touch event to %s because it is paused",
1692 newTouchedWindowHandle->getName().c_str());
1693 newTouchedWindowHandle = nullptr;
1694 }
1695
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001696 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001697 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001698 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1699 if (!isResponsive) {
1700 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001701 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1702 newTouchedWindowHandle = nullptr;
1703 }
1704 }
1705
1706 // Also don't send the new touch event to unresponsive gesture monitors
1707 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1708
Michael Wright3dd60e22019-03-27 22:06:44 +00001709 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1710 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001711 "(%d, %d) in display %" PRId32 ".",
1712 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001713 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1714 goto Failed;
1715 }
1716
1717 if (newTouchedWindowHandle != nullptr) {
1718 // Set target flags.
1719 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1720 if (isSplit) {
1721 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001723 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1724 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1725 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1726 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1727 }
1728
1729 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001730 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1731 newHoverWindowHandle = nullptr;
1732 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001733 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001734 }
1735
1736 // Update the temporary touch state.
1737 BitSet32 pointerIds;
1738 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001739 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001740 pointerIds.markBit(pointerId);
1741 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001742 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 }
1744
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001745 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 } else {
1747 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1748
1749 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001750 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001751 if (DEBUG_FOCUS) {
1752 ALOGD("Dropping event because the pointer is not down or we previously "
1753 "dropped the pointer down event in display %" PRId32,
1754 displayId);
1755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1757 goto Failed;
1758 }
1759
1760 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001761 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001762 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001763 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1764 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765
1766 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001767 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001768 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001769 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1770 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001771 if (DEBUG_FOCUS) {
1772 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1773 oldTouchedWindowHandle->getName().c_str(),
1774 newTouchedWindowHandle->getName().c_str(), displayId);
1775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001777 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1778 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1779 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780
1781 // Make a slippery entrance into the new window.
1782 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1783 isSplit = true;
1784 }
1785
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786 int32_t targetFlags =
1787 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 if (isSplit) {
1789 targetFlags |= InputTarget::FLAG_SPLIT;
1790 }
1791 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1792 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1793 }
1794
1795 BitSet32 pointerIds;
1796 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001797 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001799 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 }
1801 }
1802 }
1803
1804 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001805 // Let the previous window know that the hover sequence is over, unless we already did it
1806 // when dispatching it as is to newTouchedWindowHandle.
1807 if (mLastHoverWindowHandle != nullptr &&
1808 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1809 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810#if DEBUG_HOVER
1811 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001812 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001814 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1815 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
1817
Garfield Tandf26e862020-07-01 20:18:19 -07001818 // Let the new window know that the hover sequence is starting, unless we already did it
1819 // when dispatching it as is to newTouchedWindowHandle.
1820 if (newHoverWindowHandle != nullptr &&
1821 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1822 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823#if DEBUG_HOVER
1824 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001825 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001827 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1828 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1829 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 }
1831 }
1832
1833 // Check permission to inject into all touched foreground windows and ensure there
1834 // is at least one touched foreground window.
1835 {
1836 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001837 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1839 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001840 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1842 injectionPermission = INJECTION_PERMISSION_DENIED;
1843 goto Failed;
1844 }
1845 }
1846 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001848 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001849 ALOGI("Dropping event because there is no touched foreground window in display "
1850 "%" PRId32 " or gesture monitor to receive it.",
1851 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1853 goto Failed;
1854 }
1855
1856 // Permission granted to injection into all touched foreground windows.
1857 injectionPermission = INJECTION_PERMISSION_GRANTED;
1858 }
1859
1860 // Check whether windows listening for outside touches are owned by the same UID. If it is
1861 // set the policy flag that we will not reveal coordinate information to this window.
1862 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1863 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001864 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001865 if (foregroundWindowHandle) {
1866 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001868 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1869 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1870 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001871 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1872 InputTarget::FLAG_ZERO_COORDS,
1873 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876 }
1877 }
1878 }
1879
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 // If this is the first pointer going down and the touched window has a wallpaper
1881 // then also add the touched wallpaper windows so they are locked in for the duration
1882 // of the touch gesture.
1883 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1884 // engine only supports touch events. We would need to add a mechanism similar
1885 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1886 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1887 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001888 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001889 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001890 const std::vector<sp<InputWindowHandle>> windowHandles =
1891 getWindowHandlesLocked(displayId);
1892 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001894 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001895 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001896 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001897 .addOrUpdateWindow(windowHandle,
1898 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1899 InputTarget::
1900 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1901 InputTarget::FLAG_DISPATCH_AS_IS,
1902 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904 }
1905 }
1906 }
1907
1908 // Success! Output targets.
1909 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1910
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001911 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001913 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 }
1915
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001916 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001917 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001918 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001919 }
1920
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 // Drop the outside or hover touch windows since we will not care about them
1922 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001923 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924
1925Failed:
1926 // Check injection permission once and for all.
1927 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001928 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 injectionPermission = INJECTION_PERMISSION_GRANTED;
1930 } else {
1931 injectionPermission = INJECTION_PERMISSION_DENIED;
1932 }
1933 }
1934
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001935 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1936 return injectionResult;
1937 }
1938
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001940 if (!wrongDevice) {
1941 if (switchedDevice) {
1942 if (DEBUG_FOCUS) {
1943 ALOGD("Conflicting pointer actions: Switched to a different device.");
1944 }
1945 *outConflictingPointerActions = true;
1946 }
1947
1948 if (isHoverAction) {
1949 // Started hovering, therefore no longer down.
1950 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001951 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001952 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1953 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 *outConflictingPointerActions = true;
1956 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001957 tempTouchState.reset();
1958 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1959 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1960 tempTouchState.deviceId = entry.deviceId;
1961 tempTouchState.source = entry.source;
1962 tempTouchState.displayId = displayId;
1963 }
1964 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1965 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1966 // All pointers up or canceled.
1967 tempTouchState.reset();
1968 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1969 // First pointer went down.
1970 if (oldState && oldState->down) {
1971 if (DEBUG_FOCUS) {
1972 ALOGD("Conflicting pointer actions: Down received while already down.");
1973 }
1974 *outConflictingPointerActions = true;
1975 }
1976 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1977 // One pointer went up.
1978 if (isSplit) {
1979 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1980 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001982 for (size_t i = 0; i < tempTouchState.windows.size();) {
1983 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1984 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1985 touchedWindow.pointerIds.clearBit(pointerId);
1986 if (touchedWindow.pointerIds.isEmpty()) {
1987 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1988 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001991 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001993 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001994 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001995
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001996 // Save changes unless the action was scroll in which case the temporary touch
1997 // state was only valid for this one action.
1998 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1999 if (tempTouchState.displayId >= 0) {
2000 mTouchStatesByDisplay[displayId] = tempTouchState;
2001 } else {
2002 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002006 // Update hover state.
2007 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 return injectionResult;
2011}
2012
2013void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002014 int32_t targetFlags, BitSet32 pointerIds,
2015 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002016 std::vector<InputTarget>::iterator it =
2017 std::find_if(inputTargets.begin(), inputTargets.end(),
2018 [&windowHandle](const InputTarget& inputTarget) {
2019 return inputTarget.inputChannel->getConnectionToken() ==
2020 windowHandle->getToken();
2021 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002022
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002023 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002024
2025 if (it == inputTargets.end()) {
2026 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002027 std::shared_ptr<InputChannel> inputChannel =
2028 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002029 if (inputChannel == nullptr) {
2030 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2031 return;
2032 }
2033 inputTarget.inputChannel = inputChannel;
2034 inputTarget.flags = targetFlags;
2035 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2036 inputTargets.push_back(inputTarget);
2037 it = inputTargets.end() - 1;
2038 }
2039
2040 ALOG_ASSERT(it->flags == targetFlags);
2041 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2042
chaviw1ff3d1e2020-07-01 15:53:47 -07002043 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044}
2045
Michael Wright3dd60e22019-03-27 22:06:44 +00002046void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002047 int32_t displayId, float xOffset,
2048 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002049 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2050 mGlobalMonitorsByDisplay.find(displayId);
2051
2052 if (it != mGlobalMonitorsByDisplay.end()) {
2053 const std::vector<Monitor>& monitors = it->second;
2054 for (const Monitor& monitor : monitors) {
2055 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058}
2059
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002060void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2061 float yOffset,
2062 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002063 InputTarget target;
2064 target.inputChannel = monitor.inputChannel;
2065 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002066 ui::Transform t;
2067 t.set(xOffset, yOffset);
2068 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002069 inputTargets.push_back(target);
2070}
2071
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002073 const InjectionState* injectionState) {
2074 if (injectionState &&
2075 (windowHandle == nullptr ||
2076 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2077 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002078 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002080 "owned by uid %d",
2081 injectionState->injectorPid, injectionState->injectorUid,
2082 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 } else {
2084 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086 }
2087 return false;
2088 }
2089 return true;
2090}
2091
Robert Carrc9bf1d32020-04-13 17:21:08 -07002092/**
2093 * Indicate whether one window handle should be considered as obscuring
2094 * another window handle. We only check a few preconditions. Actually
2095 * checking the bounds is left to the caller.
2096 */
2097static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2098 const sp<InputWindowHandle>& otherHandle) {
2099 // Compare by token so cloned layers aren't counted
2100 if (haveSameToken(windowHandle, otherHandle)) {
2101 return false;
2102 }
2103 auto info = windowHandle->getInfo();
2104 auto otherInfo = otherHandle->getInfo();
2105 if (!otherInfo->visible) {
2106 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002107 } else if (info->ownerPid == otherInfo->ownerPid) {
2108 // If ownerPid is the same we don't generate occlusion events as there
2109 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002110 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002111 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002112 return false;
2113 } else if (otherInfo->displayId != info->displayId) {
2114 return false;
2115 }
2116 return true;
2117}
2118
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002119bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2120 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002122 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2123 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002124 if (windowHandle == otherHandle) {
2125 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002128 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002129 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 return true;
2131 }
2132 }
2133 return false;
2134}
2135
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002136bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2137 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002138 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002139 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002140 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002141 if (windowHandle == otherHandle) {
2142 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002143 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002144 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002145 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002146 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002147 return true;
2148 }
2149 }
2150 return false;
2151}
2152
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002153std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002154 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002156 if (applicationHandle != nullptr) {
2157 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002158 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 } else {
2160 return applicationHandle->getName();
2161 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002162 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002163 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002165 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 }
2167}
2168
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002169void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002170 if (eventEntry.type == EventEntry::Type::FOCUS) {
2171 // Focus events are passed to apps, but do not represent user activity.
2172 return;
2173 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002174 int32_t displayId = getTargetDisplayId(eventEntry);
2175 sp<InputWindowHandle> focusedWindowHandle =
2176 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2177 if (focusedWindowHandle != nullptr) {
2178 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002179 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002181 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182#endif
2183 return;
2184 }
2185 }
2186
2187 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002188 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002189 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002190 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2191 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002192 return;
2193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002195 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002196 eventType = USER_ACTIVITY_EVENT_TOUCH;
2197 }
2198 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002200 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002201 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2202 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002203 return;
2204 }
2205 eventType = USER_ACTIVITY_EVENT_BUTTON;
2206 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002208 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002209 case EventEntry::Type::CONFIGURATION_CHANGED:
2210 case EventEntry::Type::DEVICE_RESET: {
2211 LOG_ALWAYS_FATAL("%s events are not user activity",
2212 EventEntry::typeToString(eventEntry.type));
2213 break;
2214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 }
2216
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002217 std::unique_ptr<CommandEntry> commandEntry =
2218 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002219 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002221 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222}
2223
2224void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002225 const sp<Connection>& connection,
2226 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002227 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002228 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002229 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002230 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002231 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002232 ATRACE_NAME(message.c_str());
2233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#if DEBUG_DISPATCH_CYCLE
2235 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002236 "globalScaleFactor=%f, pointerIds=0x%x %s",
2237 connection->getInputChannelName().c_str(), inputTarget.flags,
2238 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2239 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240#endif
2241
2242 // Skip this event if the connection status is not normal.
2243 // We don't want to enqueue additional outbound events if the connection is broken.
2244 if (connection->status != Connection::STATUS_NORMAL) {
2245#if DEBUG_DISPATCH_CYCLE
2246 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002247 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248#endif
2249 return;
2250 }
2251
2252 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002253 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2254 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2255 "Entry type %s should not have FLAG_SPLIT",
2256 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002258 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002259 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002260 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002261 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 if (!splitMotionEntry) {
2263 return; // split event was dropped
2264 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002265 if (DEBUG_FOCUS) {
2266 ALOGD("channel '%s' ~ Split motion event.",
2267 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002268 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002269 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 splitMotionEntry->release();
2272 return;
2273 }
2274 }
2275
2276 // Not splitting. Enqueue dispatch entries for the event as is.
2277 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2278}
2279
2280void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 const sp<Connection>& connection,
2282 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002283 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002286 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002287 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002288 ATRACE_NAME(message.c_str());
2289 }
2290
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002291 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292
2293 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002300 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002302 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002303 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002304 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002305 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306
2307 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002308 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 startDispatchCycleLocked(currentTime, connection);
2310 }
2311}
2312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002313void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2314 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002315 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002316 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002317 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2319 connection->getInputChannelName().c_str(),
2320 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002321 ATRACE_NAME(message.c_str());
2322 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002323 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 if (!(inputTargetFlags & dispatchMode)) {
2325 return;
2326 }
2327 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2328
2329 // This is a new event.
2330 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002331 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2335 // different EventEntry than what was passed in.
2336 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002338 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002339 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002340 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002341 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002342 dispatchEntry->resolvedAction = keyEntry.action;
2343 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2346 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2349 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002351 return; // skip the inconsistent event
2352 }
2353 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002356 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002357 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002358 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2359 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2360 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2361 static_cast<int32_t>(IdGenerator::Source::OTHER);
2362 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002363 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2367 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2368 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2369 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2370 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2371 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2372 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2373 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002374 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002375 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002376 }
2377 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002378 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2379 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2382 "event",
2383 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002385 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002388 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002389 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2390 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2391 }
2392 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2393 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002396 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2397 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002399 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2400 "event",
2401 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002403 return; // skip the inconsistent event
2404 }
2405
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002406 dispatchEntry->resolvedEventId =
2407 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2408 ? mIdGenerator.nextId()
2409 : motionEntry.id;
2410 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2411 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2412 ") to MotionEvent(id=0x%" PRIx32 ").",
2413 motionEntry.id, dispatchEntry->resolvedEventId);
2414 ATRACE_NAME(message.c_str());
2415 }
2416
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002417 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002418 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002419
2420 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002422 case EventEntry::Type::FOCUS: {
2423 break;
2424 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002425 case EventEntry::Type::CONFIGURATION_CHANGED:
2426 case EventEntry::Type::DEVICE_RESET: {
2427 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002428 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002429 break;
2430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
2432
2433 // Remember that we are waiting for this dispatch to complete.
2434 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002435 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
2437
2438 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002439 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002440 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002441}
2442
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002443/**
2444 * This function is purely for debugging. It helps us understand where the user interaction
2445 * was taking place. For example, if user is touching launcher, we will see a log that user
2446 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2447 * We will see both launcher and wallpaper in that list.
2448 * Once the interaction with a particular set of connections starts, no new logs will be printed
2449 * until the set of interacted connections changes.
2450 *
2451 * The following items are skipped, to reduce the logspam:
2452 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2453 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2454 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2455 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2456 * Both of those ACTION_UP events would not be logged
2457 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2458 * will not be logged. This is omitted to reduce the amount of data printed.
2459 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2460 * gesture monitor is the only connection receiving the remainder of the gesture.
2461 */
2462void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2463 const std::vector<InputTarget>& targets) {
2464 // Skip ACTION_UP events, and all events other than keys and motions
2465 if (entry.type == EventEntry::Type::KEY) {
2466 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2467 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2468 return;
2469 }
2470 } else if (entry.type == EventEntry::Type::MOTION) {
2471 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2472 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2473 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2474 return;
2475 }
2476 } else {
2477 return; // Not a key or a motion
2478 }
2479
2480 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2481 std::vector<sp<Connection>> newConnections;
2482 for (const InputTarget& target : targets) {
2483 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2484 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2485 continue; // Skip windows that receive ACTION_OUTSIDE
2486 }
2487
2488 sp<IBinder> token = target.inputChannel->getConnectionToken();
2489 sp<Connection> connection = getConnectionLocked(token);
2490 if (connection == nullptr || connection->monitor) {
2491 continue; // We only need to keep track of the non-monitor connections.
2492 }
2493 newConnectionTokens.insert(std::move(token));
2494 newConnections.emplace_back(connection);
2495 }
2496 if (newConnectionTokens == mInteractionConnectionTokens) {
2497 return; // no change
2498 }
2499 mInteractionConnectionTokens = newConnectionTokens;
2500
2501 std::string windowList;
2502 for (const sp<Connection>& connection : newConnections) {
2503 windowList += connection->getWindowName() + ", ";
2504 }
2505 std::string message = "Interaction with windows: " + windowList;
2506 if (windowList.empty()) {
2507 message += "<none>";
2508 }
2509 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2510}
2511
chaviwfd6d3512019-03-25 13:23:49 -07002512void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002513 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002514 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002515 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2516 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002517 return;
2518 }
2519
2520 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2521 if (inputWindowHandle == nullptr) {
2522 return;
2523 }
2524
chaviw8c9cf542019-03-25 13:02:48 -07002525 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002526 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002527
2528 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2529
2530 if (!hasFocusChanged) {
2531 return;
2532 }
2533
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002534 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2535 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002536 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002537 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538}
2539
2540void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002541 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002542 if (ATRACE_ENABLED()) {
2543 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002545 ATRACE_NAME(message.c_str());
2546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002548 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549#endif
2550
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002551 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2552 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002554 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002555 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002556 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557
2558 // Publish the event.
2559 status_t status;
2560 EventEntry* eventEntry = dispatchEntry->eventEntry;
2561 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002562 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002563 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2564 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002567 status =
2568 connection->inputPublisher
2569 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2570 keyEntry->deviceId, keyEntry->source,
2571 keyEntry->displayId, std::move(hmac),
2572 dispatchEntry->resolvedAction,
2573 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2574 keyEntry->scanCode, keyEntry->metaState,
2575 keyEntry->repeatCount, keyEntry->downTime,
2576 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 }
2579
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002580 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 PointerCoords scaledCoords[MAX_POINTERS];
2584 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2585
chaviw82357092020-01-28 13:13:06 -08002586 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2588 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2589 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002590 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2592 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002593 // Don't apply window scale here since we don't want scale to affect raw
2594 // coordinates. The scale will be sent back to the client and applied
2595 // later when requesting relative coordinates.
2596 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2597 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 }
2599 usingCoords = scaledCoords;
2600 }
2601 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002602 // We don't want the dispatch target to know.
2603 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2604 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2605 scaledCoords[i].clear();
2606 }
2607 usingCoords = scaledCoords;
2608 }
2609 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002610
2611 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002612
2613 // Publish the motion event.
2614 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002615 .publishMotionEvent(dispatchEntry->seq,
2616 dispatchEntry->resolvedEventId,
2617 motionEntry->deviceId, motionEntry->source,
2618 motionEntry->displayId, std::move(hmac),
2619 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002620 motionEntry->actionButton,
2621 dispatchEntry->resolvedFlags,
2622 motionEntry->edgeFlags, motionEntry->metaState,
2623 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002624 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002625 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002626 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002627 motionEntry->yPrecision,
2628 motionEntry->xCursorPosition,
2629 motionEntry->yCursorPosition,
2630 motionEntry->downTime, motionEntry->eventTime,
2631 motionEntry->pointerCount,
2632 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002633 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002634 break;
2635 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002636 case EventEntry::Type::FOCUS: {
2637 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2638 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002639 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002640 focusEntry->hasFocus,
2641 mInTouchMode);
2642 break;
2643 }
2644
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002645 case EventEntry::Type::CONFIGURATION_CHANGED:
2646 case EventEntry::Type::DEVICE_RESET: {
2647 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2648 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002649 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 }
2652
2653 // Check the result.
2654 if (status) {
2655 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002656 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 "This is unexpected because the wait queue is empty, so the pipe "
2659 "should be empty and we shouldn't have any problems writing an "
2660 "event to it, status=%d",
2661 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2663 } else {
2664 // Pipe is full and we are waiting for the app to finish process some events
2665 // before sending more events to it.
2666#if DEBUG_DISPATCH_CYCLE
2667 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002668 "waiting for the application to catch up",
2669 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 }
2672 } else {
2673 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002674 "status=%d",
2675 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2677 }
2678 return;
2679 }
2680
2681 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002682 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2683 connection->outboundQueue.end(),
2684 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002685 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002686 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002687 if (connection->responsive) {
2688 mAnrTracker.insert(dispatchEntry->timeoutTime,
2689 connection->inputChannel->getConnectionToken());
2690 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002691 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 }
2693}
2694
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002695const std::array<uint8_t, 32> InputDispatcher::getSignature(
2696 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2697 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2698 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2699 // Only sign events up and down events as the purely move events
2700 // are tied to their up/down counterparts so signing would be redundant.
2701 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2702 verifiedEvent.actionMasked = actionMasked;
2703 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2704 return mHmacKeyManager.sign(verifiedEvent);
2705 }
2706 return INVALID_HMAC;
2707}
2708
2709const std::array<uint8_t, 32> InputDispatcher::getSignature(
2710 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2711 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2712 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2713 verifiedEvent.action = dispatchEntry.resolvedAction;
2714 return mHmacKeyManager.sign(verifiedEvent);
2715}
2716
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 const sp<Connection>& connection, uint32_t seq,
2719 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720#if DEBUG_DISPATCH_CYCLE
2721 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723#endif
2724
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 if (connection->status == Connection::STATUS_BROKEN ||
2726 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 return;
2728 }
2729
2730 // Notify other system components and prepare to start the next dispatch cycle.
2731 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2732}
2733
2734void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 const sp<Connection>& connection,
2736 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737#if DEBUG_DISPATCH_CYCLE
2738 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002739 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740#endif
2741
2742 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002743 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002744 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002745 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002746 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747
2748 // The connection appears to be unrecoverably broken.
2749 // Ignore already broken or zombie connections.
2750 if (connection->status == Connection::STATUS_NORMAL) {
2751 connection->status = Connection::STATUS_BROKEN;
2752
2753 if (notify) {
2754 // Notify other system components.
2755 onDispatchCycleBrokenLocked(currentTime, connection);
2756 }
2757 }
2758}
2759
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002760void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2761 while (!queue.empty()) {
2762 DispatchEntry* dispatchEntry = queue.front();
2763 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002764 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 }
2766}
2767
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002768void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002770 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 }
2772 delete dispatchEntry;
2773}
2774
2775int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2776 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2777
2778 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002779 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002781 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 "fd=%d, events=0x%x",
2784 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 return 0; // remove the callback
2786 }
2787
2788 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002789 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2791 if (!(events & ALOOPER_EVENT_INPUT)) {
2792 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002793 "events=0x%x",
2794 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 return 1;
2796 }
2797
2798 nsecs_t currentTime = now();
2799 bool gotOne = false;
2800 status_t status;
2801 for (;;) {
2802 uint32_t seq;
2803 bool handled;
2804 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2805 if (status) {
2806 break;
2807 }
2808 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2809 gotOne = true;
2810 }
2811 if (gotOne) {
2812 d->runCommandsLockedInterruptible();
2813 if (status == WOULD_BLOCK) {
2814 return 1;
2815 }
2816 }
2817
2818 notify = status != DEAD_OBJECT || !connection->monitor;
2819 if (notify) {
2820 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
2823 } else {
2824 // Monitor channels are never explicitly unregistered.
2825 // We do it automatically when the remote endpoint is closed so don't warn
2826 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002827 const bool stillHaveWindowHandle =
2828 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2829 nullptr;
2830 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 if (notify) {
2832 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 "events=0x%x",
2834 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 }
2836 }
2837
2838 // Unregister the channel.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002839 d->unregisterInputChannelLocked(*connection->inputChannel, notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842}
2843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002846 for (const auto& pair : mConnectionsByFd) {
2847 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 }
2849}
2850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002851void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002852 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002853 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2854 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2855}
2856
2857void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2858 const CancelationOptions& options,
2859 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2860 for (const auto& it : monitorsByDisplay) {
2861 const std::vector<Monitor>& monitors = it.second;
2862 for (const Monitor& monitor : monitors) {
2863 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002864 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002865 }
2866}
2867
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002869 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002870 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002871 if (connection == nullptr) {
2872 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002874
2875 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876}
2877
2878void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2879 const sp<Connection>& connection, const CancelationOptions& options) {
2880 if (connection->status == Connection::STATUS_BROKEN) {
2881 return;
2882 }
2883
2884 nsecs_t currentTime = now();
2885
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002886 std::vector<EventEntry*> cancelationEvents =
2887 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002889 if (cancelationEvents.empty()) {
2890 return;
2891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002893 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2894 "with reality: %s, mode=%d.",
2895 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2896 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002898
2899 InputTarget target;
2900 sp<InputWindowHandle> windowHandle =
2901 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2902 if (windowHandle != nullptr) {
2903 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002904 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002905 target.globalScaleFactor = windowInfo->globalScaleFactor;
2906 }
2907 target.inputChannel = connection->inputChannel;
2908 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2909
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002910 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2911 EventEntry* cancelationEventEntry = cancelationEvents[i];
2912 switch (cancelationEventEntry->type) {
2913 case EventEntry::Type::KEY: {
2914 logOutboundKeyDetails("cancel - ",
2915 static_cast<const KeyEntry&>(*cancelationEventEntry));
2916 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002918 case EventEntry::Type::MOTION: {
2919 logOutboundMotionDetails("cancel - ",
2920 static_cast<const MotionEntry&>(*cancelationEventEntry));
2921 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002923 case EventEntry::Type::FOCUS: {
2924 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2925 break;
2926 }
2927 case EventEntry::Type::CONFIGURATION_CHANGED:
2928 case EventEntry::Type::DEVICE_RESET: {
2929 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2930 EventEntry::typeToString(cancelationEventEntry->type));
2931 break;
2932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
2934
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002935 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2936 target, InputTarget::FLAG_DISPATCH_AS_IS);
2937
2938 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002940
2941 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942}
2943
Svet Ganov5d3bc372020-01-26 23:11:07 -08002944void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2945 const sp<Connection>& connection) {
2946 if (connection->status == Connection::STATUS_BROKEN) {
2947 return;
2948 }
2949
2950 nsecs_t currentTime = now();
2951
2952 std::vector<EventEntry*> downEvents =
2953 connection->inputState.synthesizePointerDownEvents(currentTime);
2954
2955 if (downEvents.empty()) {
2956 return;
2957 }
2958
2959#if DEBUG_OUTBOUND_EVENT_DETAILS
2960 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2961 connection->getInputChannelName().c_str(), downEvents.size());
2962#endif
2963
2964 InputTarget target;
2965 sp<InputWindowHandle> windowHandle =
2966 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2967 if (windowHandle != nullptr) {
2968 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002969 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002970 target.globalScaleFactor = windowInfo->globalScaleFactor;
2971 }
2972 target.inputChannel = connection->inputChannel;
2973 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2974
2975 for (EventEntry* downEventEntry : downEvents) {
2976 switch (downEventEntry->type) {
2977 case EventEntry::Type::MOTION: {
2978 logOutboundMotionDetails("down - ",
2979 static_cast<const MotionEntry&>(*downEventEntry));
2980 break;
2981 }
2982
2983 case EventEntry::Type::KEY:
2984 case EventEntry::Type::FOCUS:
2985 case EventEntry::Type::CONFIGURATION_CHANGED:
2986 case EventEntry::Type::DEVICE_RESET: {
2987 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2988 EventEntry::typeToString(downEventEntry->type));
2989 break;
2990 }
2991 }
2992
2993 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2994 target, InputTarget::FLAG_DISPATCH_AS_IS);
2995
2996 downEventEntry->release();
2997 }
2998
2999 startDispatchCycleLocked(currentTime, connection);
3000}
3001
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003002MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003003 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 ALOG_ASSERT(pointerIds.value != 0);
3005
3006 uint32_t splitPointerIndexMap[MAX_POINTERS];
3007 PointerProperties splitPointerProperties[MAX_POINTERS];
3008 PointerCoords splitPointerCoords[MAX_POINTERS];
3009
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003010 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 uint32_t splitPointerCount = 0;
3012
3013 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003016 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 uint32_t pointerId = uint32_t(pointerProperties.id);
3018 if (pointerIds.hasBit(pointerId)) {
3019 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3020 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3021 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003022 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 splitPointerCount += 1;
3024 }
3025 }
3026
3027 if (splitPointerCount != pointerIds.count()) {
3028 // This is bad. We are missing some of the pointers that we expected to deliver.
3029 // Most likely this indicates that we received an ACTION_MOVE events that has
3030 // different pointer ids than we expected based on the previous ACTION_DOWN
3031 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3032 // in this way.
3033 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 "we expected there to be %d pointers. This probably means we received "
3035 "a broken sequence of pointer ids from the input device.",
3036 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003037 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 }
3039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3043 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3045 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003046 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 uint32_t pointerId = uint32_t(pointerProperties.id);
3048 if (pointerIds.hasBit(pointerId)) {
3049 if (pointerIds.count() == 1) {
3050 // The first/last pointer went down/up.
3051 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 ? AMOTION_EVENT_ACTION_DOWN
3053 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 } else {
3055 // A secondary pointer went down/up.
3056 uint32_t splitPointerIndex = 0;
3057 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3058 splitPointerIndex += 1;
3059 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003060 action = maskedAction |
3061 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062 }
3063 } else {
3064 // An unrelated pointer changed.
3065 action = AMOTION_EVENT_ACTION_MOVE;
3066 }
3067 }
3068
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003069 int32_t newId = mIdGenerator.nextId();
3070 if (ATRACE_ENABLED()) {
3071 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3072 ") to MotionEvent(id=0x%" PRIx32 ").",
3073 originalMotionEntry.id, newId);
3074 ATRACE_NAME(message.c_str());
3075 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003076 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003077 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3078 originalMotionEntry.source, originalMotionEntry.displayId,
3079 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003080 originalMotionEntry.actionButton, originalMotionEntry.flags,
3081 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3082 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3083 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3084 originalMotionEntry.xCursorPosition,
3085 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003086 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003088 if (originalMotionEntry.injectionState) {
3089 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 splitMotionEntry->injectionState->refCount += 1;
3091 }
3092
3093 return splitMotionEntry;
3094}
3095
3096void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3097#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003098 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099#endif
3100
3101 bool needWake;
3102 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003103 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104
Prabir Pradhan42611e02018-11-27 14:04:02 -08003105 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003106 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 needWake = enqueueInboundEventLocked(newEntry);
3108 } // release lock
3109
3110 if (needWake) {
3111 mLooper->wake();
3112 }
3113}
3114
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003115/**
3116 * If one of the meta shortcuts is detected, process them here:
3117 * Meta + Backspace -> generate BACK
3118 * Meta + Enter -> generate HOME
3119 * This will potentially overwrite keyCode and metaState.
3120 */
3121void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003123 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3124 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3125 if (keyCode == AKEYCODE_DEL) {
3126 newKeyCode = AKEYCODE_BACK;
3127 } else if (keyCode == AKEYCODE_ENTER) {
3128 newKeyCode = AKEYCODE_HOME;
3129 }
3130 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003131 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003132 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003133 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003134 keyCode = newKeyCode;
3135 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3136 }
3137 } else if (action == AKEY_EVENT_ACTION_UP) {
3138 // In order to maintain a consistent stream of up and down events, check to see if the key
3139 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3140 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003141 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003142 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003143 auto replacementIt = mReplacedKeys.find(replacement);
3144 if (replacementIt != mReplacedKeys.end()) {
3145 keyCode = replacementIt->second;
3146 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003147 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3148 }
3149 }
3150}
3151
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3153#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3155 "policyFlags=0x%x, action=0x%x, "
3156 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3157 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3158 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3159 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160#endif
3161 if (!validateKeyEvent(args->action)) {
3162 return;
3163 }
3164
3165 uint32_t policyFlags = args->policyFlags;
3166 int32_t flags = args->flags;
3167 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003168 // InputDispatcher tracks and generates key repeats on behalf of
3169 // whatever notifies it, so repeatCount should always be set to 0
3170 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3172 policyFlags |= POLICY_FLAG_VIRTUAL;
3173 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 if (policyFlags & POLICY_FLAG_FUNCTION) {
3176 metaState |= AMETA_FUNCTION_ON;
3177 }
3178
3179 policyFlags |= POLICY_FLAG_TRUSTED;
3180
Michael Wright78f24442014-08-06 15:55:28 -07003181 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003182 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003183
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003185 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003186 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3187 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188
Michael Wright2b3c3302018-03-02 17:19:13 +00003189 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003191 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3192 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 bool needWake;
3197 { // acquire lock
3198 mLock.lock();
3199
3200 if (shouldSendKeyToInputFilterLocked(args)) {
3201 mLock.unlock();
3202
3203 policyFlags |= POLICY_FLAG_FILTERED;
3204 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3205 return; // event was consumed by the filter
3206 }
3207
3208 mLock.lock();
3209 }
3210
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003212 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213 args->displayId, policyFlags, args->action, flags, keyCode,
3214 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215
3216 needWake = enqueueInboundEventLocked(newEntry);
3217 mLock.unlock();
3218 } // release lock
3219
3220 if (needWake) {
3221 mLooper->wake();
3222 }
3223}
3224
3225bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3226 return mInputFilterEnabled;
3227}
3228
3229void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3230#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003231 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3232 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003233 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3234 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003235 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003236 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3237 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3238 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3239 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 for (uint32_t i = 0; i < args->pointerCount; i++) {
3241 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 "x=%f, y=%f, pressure=%f, size=%f, "
3243 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3244 "orientation=%f",
3245 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3246 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3247 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3248 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3249 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3250 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3251 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3252 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3253 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3254 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
3256#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3258 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 return;
3260 }
3261
3262 uint32_t policyFlags = args->policyFlags;
3263 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003264
3265 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003266 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003267 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3268 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003269 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 bool needWake;
3273 { // acquire lock
3274 mLock.lock();
3275
3276 if (shouldSendMotionToInputFilterLocked(args)) {
3277 mLock.unlock();
3278
3279 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003280 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003281 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3282 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003283 args->metaState, args->buttonState, args->classification, transform,
3284 args->xPrecision, args->yPrecision, args->xCursorPosition,
3285 args->yCursorPosition, args->downTime, args->eventTime,
3286 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287
3288 policyFlags |= POLICY_FLAG_FILTERED;
3289 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3290 return; // event was consumed by the filter
3291 }
3292
3293 mLock.lock();
3294 }
3295
3296 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003297 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003298 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003299 args->displayId, policyFlags, args->action, args->actionButton,
3300 args->flags, args->metaState, args->buttonState,
3301 args->classification, args->edgeFlags, args->xPrecision,
3302 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3303 args->downTime, args->pointerCount, args->pointerProperties,
3304 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
3306 needWake = enqueueInboundEventLocked(newEntry);
3307 mLock.unlock();
3308 } // release lock
3309
3310 if (needWake) {
3311 mLooper->wake();
3312 }
3313}
3314
3315bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003316 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317}
3318
3319void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3320#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003321 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 "switchMask=0x%08x",
3323 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324#endif
3325
3326 uint32_t policyFlags = args->policyFlags;
3327 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329}
3330
3331void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3332#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3334 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335#endif
3336
3337 bool needWake;
3338 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003339 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340
Prabir Pradhan42611e02018-11-27 14:04:02 -08003341 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003342 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 needWake = enqueueInboundEventLocked(newEntry);
3344 } // release lock
3345
3346 if (needWake) {
3347 mLooper->wake();
3348 }
3349}
3350
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3352 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003353 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354#if DEBUG_INBOUND_EVENT_DETAILS
3355 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003356 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3357 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358#endif
3359
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003360 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
3362 policyFlags |= POLICY_FLAG_INJECTED;
3363 if (hasInjectionPermission(injectorPid, injectorUid)) {
3364 policyFlags |= POLICY_FLAG_TRUSTED;
3365 }
3366
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003367 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003370 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3371 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003372 if (!validateKeyEvent(action)) {
3373 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003376 int32_t flags = incomingKey.getFlags();
3377 int32_t keyCode = incomingKey.getKeyCode();
3378 int32_t metaState = incomingKey.getMetaState();
3379 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003380 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003381 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003382 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003383 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3384 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3385 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3388 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003389 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390
3391 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3392 android::base::Timer t;
3393 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3394 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3395 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3396 std::to_string(t.duration().count()).c_str());
3397 }
3398 }
3399
3400 mLock.lock();
3401 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003402 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3403 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003404 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3405 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003406 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 injectedEntries.push(injectedEntry);
3408 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
3410
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003411 case AINPUT_EVENT_TYPE_MOTION: {
3412 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3413 int32_t action = motionEvent->getAction();
3414 size_t pointerCount = motionEvent->getPointerCount();
3415 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3416 int32_t actionButton = motionEvent->getActionButton();
3417 int32_t displayId = motionEvent->getDisplayId();
3418 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3419 return INPUT_EVENT_INJECTION_FAILED;
3420 }
3421
3422 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3423 nsecs_t eventTime = motionEvent->getEventTime();
3424 android::base::Timer t;
3425 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3426 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3427 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3428 std::to_string(t.duration().count()).c_str());
3429 }
3430 }
3431
3432 mLock.lock();
3433 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3434 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3435 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003436 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3437 motionEvent->getSource(), motionEvent->getDisplayId(),
3438 policyFlags, action, actionButton, motionEvent->getFlags(),
3439 motionEvent->getMetaState(), motionEvent->getButtonState(),
3440 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3441 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003442 motionEvent->getRawXCursorPosition(),
3443 motionEvent->getRawYCursorPosition(),
3444 motionEvent->getDownTime(), uint32_t(pointerCount),
3445 pointerProperties, samplePointerCoords,
3446 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003447 injectedEntries.push(injectedEntry);
3448 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3449 sampleEventTimes += 1;
3450 samplePointerCoords += pointerCount;
3451 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003452 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003453 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003454 motionEvent->getDisplayId(), policyFlags, action,
3455 actionButton, motionEvent->getFlags(),
3456 motionEvent->getMetaState(), motionEvent->getButtonState(),
3457 motionEvent->getClassification(),
3458 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3459 motionEvent->getYPrecision(),
3460 motionEvent->getRawXCursorPosition(),
3461 motionEvent->getRawYCursorPosition(),
3462 motionEvent->getDownTime(), uint32_t(pointerCount),
3463 pointerProperties, samplePointerCoords,
3464 motionEvent->getXOffset(), motionEvent->getYOffset());
3465 injectedEntries.push(nextInjectedEntry);
3466 }
3467 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003471 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003472 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 }
3474
3475 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3476 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3477 injectionState->injectionIsAsync = true;
3478 }
3479
3480 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003481 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482
3483 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003484 while (!injectedEntries.empty()) {
3485 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3486 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
3488
3489 mLock.unlock();
3490
3491 if (needWake) {
3492 mLooper->wake();
3493 }
3494
3495 int32_t injectionResult;
3496 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003497 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498
3499 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3500 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3501 } else {
3502 for (;;) {
3503 injectionResult = injectionState->injectionResult;
3504 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3505 break;
3506 }
3507
3508 nsecs_t remainingTimeout = endTime - now();
3509 if (remainingTimeout <= 0) {
3510#if DEBUG_INJECTION
3511 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513#endif
3514 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3515 break;
3516 }
3517
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003518 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 }
3520
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003521 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3522 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 while (injectionState->pendingForegroundDispatches != 0) {
3524#if DEBUG_INJECTION
3525 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003526 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527#endif
3528 nsecs_t remainingTimeout = endTime - now();
3529 if (remainingTimeout <= 0) {
3530#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003531 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3532 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533#endif
3534 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3535 break;
3536 }
3537
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003538 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 }
3540 }
3541 }
3542
3543 injectionState->release();
3544 } // release lock
3545
3546#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003547 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003548 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549#endif
3550
3551 return injectionResult;
3552}
3553
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003554std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003555 std::array<uint8_t, 32> calculatedHmac;
3556 std::unique_ptr<VerifiedInputEvent> result;
3557 switch (event.getType()) {
3558 case AINPUT_EVENT_TYPE_KEY: {
3559 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3560 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3561 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3562 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3563 break;
3564 }
3565 case AINPUT_EVENT_TYPE_MOTION: {
3566 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3567 VerifiedMotionEvent verifiedMotionEvent =
3568 verifiedMotionEventFromMotionEvent(motionEvent);
3569 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3570 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3571 break;
3572 }
3573 default: {
3574 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3575 return nullptr;
3576 }
3577 }
3578 if (calculatedHmac == INVALID_HMAC) {
3579 return nullptr;
3580 }
3581 if (calculatedHmac != event.getHmac()) {
3582 return nullptr;
3583 }
3584 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003585}
3586
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 return injectorUid == 0 ||
3589 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590}
3591
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003592void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 InjectionState* injectionState = entry->injectionState;
3594 if (injectionState) {
3595#if DEBUG_INJECTION
3596 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003597 "injectorPid=%d, injectorUid=%d",
3598 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599#endif
3600
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003601 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 // Log the outcome since the injector did not wait for the injection result.
3603 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003604 case INPUT_EVENT_INJECTION_SUCCEEDED:
3605 ALOGV("Asynchronous input event injection succeeded.");
3606 break;
3607 case INPUT_EVENT_INJECTION_FAILED:
3608 ALOGW("Asynchronous input event injection failed.");
3609 break;
3610 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3611 ALOGW("Asynchronous input event injection permission denied.");
3612 break;
3613 case INPUT_EVENT_INJECTION_TIMED_OUT:
3614 ALOGW("Asynchronous input event injection timed out.");
3615 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617 }
3618
3619 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003620 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 }
3622}
3623
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003624void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 InjectionState* injectionState = entry->injectionState;
3626 if (injectionState) {
3627 injectionState->pendingForegroundDispatches += 1;
3628 }
3629}
3630
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003631void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 InjectionState* injectionState = entry->injectionState;
3633 if (injectionState) {
3634 injectionState->pendingForegroundDispatches -= 1;
3635
3636 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003637 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
3639 }
3640}
3641
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003642std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3643 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003644 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003645}
3646
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003648 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003649 if (windowHandleToken == nullptr) {
3650 return nullptr;
3651 }
3652
Arthur Hungb92218b2018-08-14 12:00:21 +08003653 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003654 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3655 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003656 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003657 return windowHandle;
3658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 }
3660 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003661 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662}
3663
Mady Mellor017bcd12020-06-23 19:12:00 +00003664bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3665 for (auto& it : mWindowHandlesByDisplay) {
3666 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3667 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003668 if (handle->getId() == windowHandle->getId() &&
3669 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003670 if (windowHandle->getInfo()->displayId != it.first) {
3671 ALOGE("Found window %s in display %" PRId32
3672 ", but it should belong to display %" PRId32,
3673 windowHandle->getName().c_str(), it.first,
3674 windowHandle->getInfo()->displayId);
3675 }
3676 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 }
3679 }
3680 return false;
3681}
3682
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003683bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3684 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3685 const bool noInputChannel =
3686 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3687 if (connection != nullptr && noInputChannel) {
3688 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3689 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3690 return false;
3691 }
3692
3693 if (connection == nullptr) {
3694 if (!noInputChannel) {
3695 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3696 }
3697 return false;
3698 }
3699 if (!connection->responsive) {
3700 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3701 return false;
3702 }
3703 return true;
3704}
3705
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003706std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3707 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003708 size_t count = mInputChannelsByToken.count(token);
3709 if (count == 0) {
3710 return nullptr;
3711 }
3712 return mInputChannelsByToken.at(token);
3713}
3714
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003715void InputDispatcher::updateWindowHandlesForDisplayLocked(
3716 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3717 if (inputWindowHandles.empty()) {
3718 // Remove all handles on a display if there are no windows left.
3719 mWindowHandlesByDisplay.erase(displayId);
3720 return;
3721 }
3722
3723 // Since we compare the pointer of input window handles across window updates, we need
3724 // to make sure the handle object for the same window stays unchanged across updates.
3725 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003726 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003727 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003728 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003729 }
3730
3731 std::vector<sp<InputWindowHandle>> newHandles;
3732 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3733 if (!handle->updateInfo()) {
3734 // handle no longer valid
3735 continue;
3736 }
3737
3738 const InputWindowInfo* info = handle->getInfo();
3739 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3740 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3741 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003742 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3743 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3744 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003745 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003746 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003747 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003748 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003749 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003750 }
3751
3752 if (info->displayId != displayId) {
3753 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3754 handle->getName().c_str(), displayId, info->displayId);
3755 continue;
3756 }
3757
Robert Carredd13602020-04-13 17:24:34 -07003758 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3759 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003760 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003761 oldHandle->updateFrom(handle);
3762 newHandles.push_back(oldHandle);
3763 } else {
3764 newHandles.push_back(handle);
3765 }
3766 }
3767
3768 // Insert or replace
3769 mWindowHandlesByDisplay[displayId] = newHandles;
3770}
3771
Arthur Hung72d8dc32020-03-28 00:48:39 +00003772void InputDispatcher::setInputWindows(
3773 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3774 { // acquire lock
3775 std::scoped_lock _l(mLock);
3776 for (auto const& i : handlesPerDisplay) {
3777 setInputWindowsLocked(i.second, i.first);
3778 }
3779 }
3780 // Wake up poll loop since it may need to make new input dispatching choices.
3781 mLooper->wake();
3782}
3783
Arthur Hungb92218b2018-08-14 12:00:21 +08003784/**
3785 * Called from InputManagerService, update window handle list by displayId that can receive input.
3786 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3787 * If set an empty list, remove all handles from the specific display.
3788 * For focused handle, check if need to change and send a cancel event to previous one.
3789 * For removed handle, check if need to send a cancel event if already in touch.
3790 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003791void InputDispatcher::setInputWindowsLocked(
3792 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003793 if (DEBUG_FOCUS) {
3794 std::string windowList;
3795 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3796 windowList += iwh->getName() + " ";
3797 }
3798 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003801 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3802 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3803 const bool noInputWindow =
3804 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3805 if (noInputWindow && window->getToken() != nullptr) {
3806 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3807 window->getName().c_str());
3808 window->releaseChannel();
3809 }
3810 }
3811
Arthur Hung72d8dc32020-03-28 00:48:39 +00003812 // Copy old handles for release if they are no longer present.
3813 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814
Arthur Hung72d8dc32020-03-28 00:48:39 +00003815 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003816
Arthur Hung72d8dc32020-03-28 00:48:39 +00003817 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3818 bool foundHoveredWindow = false;
3819 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3820 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3821 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3822 windowHandle->getInfo()->visible) {
3823 newFocusedWindowHandle = windowHandle;
3824 }
3825 if (windowHandle == mLastHoverWindowHandle) {
3826 foundHoveredWindow = true;
3827 }
3828 }
3829
3830 if (!foundHoveredWindow) {
3831 mLastHoverWindowHandle = nullptr;
3832 }
3833
3834 sp<InputWindowHandle> oldFocusedWindowHandle =
3835 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3836
3837 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07003838 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle, displayId,
3839 "setInputWindowsLocked");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003842 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3843 mTouchStatesByDisplay.find(displayId);
3844 if (stateIt != mTouchStatesByDisplay.end()) {
3845 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003846 for (size_t i = 0; i < state.windows.size();) {
3847 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003848 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003849 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003850 ALOGD("Touched window was removed: %s in display %" PRId32,
3851 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003852 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003853 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003854 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3855 if (touchedInputChannel != nullptr) {
3856 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3857 "touched window was removed");
3858 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003860 state.windows.erase(state.windows.begin() + i);
3861 } else {
3862 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 }
3864 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003865 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003866
Arthur Hung72d8dc32020-03-28 00:48:39 +00003867 // Release information for windows that are no longer present.
3868 // This ensures that unused input channels are released promptly.
3869 // Otherwise, they might stick around until the window handle is destroyed
3870 // which might not happen until the next GC.
3871 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003872 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003873 if (DEBUG_FOCUS) {
3874 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003875 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003876 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003877 }
chaviw291d88a2019-02-14 10:33:58 -08003878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879}
3880
3881void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003882 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003883 if (DEBUG_FOCUS) {
3884 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3885 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3886 }
Chris Yea209fde2020-07-22 13:54:51 -07003887 if (inputApplicationHandle != nullptr &&
3888 inputApplicationHandle->getApplicationToken() != nullptr) {
3889 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003890 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
Chris Yea209fde2020-07-22 13:54:51 -07003892 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003893 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003894
Chris Yea209fde2020-07-22 13:54:51 -07003895 // If oldFocusedApplicationHandle already exists
3896 if (oldFocusedApplicationHandle != nullptr) {
3897 // If a new focused application handle is different from the old one and
3898 // old focus application info is awaited focused application info.
3899 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3900 mAwaitedFocusedApplication != nullptr &&
3901 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3902 resetNoFocusedWindowTimeoutLocked();
3903 }
3904 // Erase the old application from container first
3905 mFocusedApplicationHandlesByDisplay.erase(displayId);
3906 // Should already get freed after removed from container but just double check.
3907 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003908 }
3909
Chris Yea209fde2020-07-22 13:54:51 -07003910 // Set the new application handle.
3911 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 } // release lock
3913
3914 // Wake up poll loop since it may need to make new input dispatching choices.
3915 mLooper->wake();
3916}
3917
Tiger Huang721e26f2018-07-24 22:26:19 +08003918/**
3919 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3920 * the display not specified.
3921 *
3922 * We track any unreleased events for each window. If a window loses the ability to receive the
3923 * released event, we will send a cancel event to it. So when the focused display is changed, we
3924 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3925 * display. The display-specified events won't be affected.
3926 */
3927void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003928 if (DEBUG_FOCUS) {
3929 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3930 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003931 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003932 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003933
3934 if (mFocusedDisplayId != displayId) {
3935 sp<InputWindowHandle> oldFocusedWindowHandle =
3936 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3937 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003938 std::shared_ptr<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003939 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003940 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 CancelationOptions
3942 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3943 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003944 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003945 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3946 }
3947 }
3948 mFocusedDisplayId = displayId;
3949
Chris Ye3c2d6f52020-08-09 10:39:48 -07003950 // Find new focused window and validate
Tiger Huang721e26f2018-07-24 22:26:19 +08003951 sp<InputWindowHandle> newFocusedWindowHandle =
3952 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07003953 notifyFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003954
Tiger Huang721e26f2018-07-24 22:26:19 +08003955 if (newFocusedWindowHandle == nullptr) {
3956 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3957 if (!mFocusedWindowHandlesByDisplay.empty()) {
3958 ALOGE("But another display has a focused window:");
3959 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003960 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003961 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003963 }
3964 }
3965 }
3966 }
3967
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003968 if (DEBUG_FOCUS) {
3969 logDispatchStateLocked();
3970 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003971 } // release lock
3972
3973 // Wake up poll loop since it may need to make new input dispatching choices.
3974 mLooper->wake();
3975}
3976
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003978 if (DEBUG_FOCUS) {
3979 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
3982 bool changed;
3983 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003984 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3987 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003988 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
3990
3991 if (mDispatchEnabled && !enabled) {
3992 resetAndDropEverythingLocked("dispatcher is being disabled");
3993 }
3994
3995 mDispatchEnabled = enabled;
3996 mDispatchFrozen = frozen;
3997 changed = true;
3998 } else {
3999 changed = false;
4000 }
4001
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004002 if (DEBUG_FOCUS) {
4003 logDispatchStateLocked();
4004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 } // release lock
4006
4007 if (changed) {
4008 // Wake up poll loop since it may need to make new input dispatching choices.
4009 mLooper->wake();
4010 }
4011}
4012
4013void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004014 if (DEBUG_FOCUS) {
4015 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017
4018 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004019 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020
4021 if (mInputFilterEnabled == enabled) {
4022 return;
4023 }
4024
4025 mInputFilterEnabled = enabled;
4026 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4027 } // release lock
4028
4029 // Wake up poll loop since there might be work to do to drop everything.
4030 mLooper->wake();
4031}
4032
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004033void InputDispatcher::setInTouchMode(bool inTouchMode) {
4034 std::scoped_lock lock(mLock);
4035 mInTouchMode = inTouchMode;
4036}
4037
chaviwfbe5d9c2018-12-26 12:23:37 -08004038bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4039 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004040 if (DEBUG_FOCUS) {
4041 ALOGD("Trivial transfer to same window.");
4042 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004043 return true;
4044 }
4045
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004047 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048
chaviwfbe5d9c2018-12-26 12:23:37 -08004049 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4050 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004051 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004052 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 return false;
4054 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004055 if (DEBUG_FOCUS) {
4056 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4057 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004060 if (DEBUG_FOCUS) {
4061 ALOGD("Cannot transfer focus because windows are on different displays.");
4062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 return false;
4064 }
4065
4066 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004067 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4068 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004069 for (size_t i = 0; i < state.windows.size(); i++) {
4070 const TouchedWindow& touchedWindow = state.windows[i];
4071 if (touchedWindow.windowHandle == fromWindowHandle) {
4072 int32_t oldTargetFlags = touchedWindow.targetFlags;
4073 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004075 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 int32_t newTargetFlags = oldTargetFlags &
4078 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4079 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004080 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
Jeff Brownf086ddb2014-02-11 14:28:48 -08004082 found = true;
4083 goto Found;
4084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 }
4086 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004090 if (DEBUG_FOCUS) {
4091 ALOGD("Focus transfer failed because from window did not have focus.");
4092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 return false;
4094 }
4095
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004096 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4097 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004098 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004099 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004100 CancelationOptions
4101 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4102 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004104 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 }
4106
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004107 if (DEBUG_FOCUS) {
4108 logDispatchStateLocked();
4109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 } // release lock
4111
4112 // Wake up poll loop since it may need to make new input dispatching choices.
4113 mLooper->wake();
4114 return true;
4115}
4116
4117void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004118 if (DEBUG_FOCUS) {
4119 ALOGD("Resetting and dropping all events (%s).", reason);
4120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121
4122 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4123 synthesizeCancelationEventsForAllConnectionsLocked(options);
4124
4125 resetKeyRepeatLocked();
4126 releasePendingEventLocked();
4127 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004128 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004130 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004131 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004133 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134}
4135
4136void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004137 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 dumpDispatchStateLocked(dump);
4139
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 std::istringstream stream(dump);
4141 std::string line;
4142
4143 while (std::getline(stream, line, '\n')) {
4144 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 }
4146}
4147
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004148void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004149 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4150 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4151 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004152 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153
Tiger Huang721e26f2018-07-24 22:26:19 +08004154 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4155 dump += StringPrintf(INDENT "FocusedApplications:\n");
4156 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4157 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004158 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004159 const std::chrono::duration timeout =
4160 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004162 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004163 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004166 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004168
4169 if (!mFocusedWindowHandlesByDisplay.empty()) {
4170 dump += StringPrintf(INDENT "FocusedWindows:\n");
4171 for (auto& it : mFocusedWindowHandlesByDisplay) {
4172 const int32_t displayId = it.first;
4173 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4175 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004176 }
4177 } else {
4178 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004181 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004183 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4184 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 state.displayId, toString(state.down), toString(state.split),
4187 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004188 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004189 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004190 for (size_t i = 0; i < state.windows.size(); i++) {
4191 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 dump += StringPrintf(INDENT4
4193 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4194 i, touchedWindow.windowHandle->getName().c_str(),
4195 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004196 }
4197 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004199 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004200 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004201 dump += INDENT3 "Portal windows:\n";
4202 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004203 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4205 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004206 }
4207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
4209 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004210 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 }
4212
Arthur Hungb92218b2018-08-14 12:00:21 +08004213 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004214 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004215 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004216 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004217 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004218 dump += INDENT2 "Windows:\n";
4219 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004220 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004221 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222
Arthur Hungb92218b2018-08-14 12:00:21 +08004223 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004225 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004226 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004228 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 i, windowInfo->name.c_str(), windowInfo->displayId,
4230 windowInfo->portalToDisplayId,
4231 toString(windowInfo->paused),
4232 toString(windowInfo->hasFocus),
4233 toString(windowInfo->hasWallpaper),
4234 toString(windowInfo->visible),
4235 toString(windowInfo->canReceiveKeys),
Michael Wright8759d672020-07-21 00:46:45 +01004236 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004237 static_cast<int32_t>(windowInfo->type),
4238 windowInfo->frameLeft, windowInfo->frameTop,
4239 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004240 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004241 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004242 dump += StringPrintf(", inputFeatures=%s",
4243 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004244 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4245 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004247 millis(windowInfo->dispatchingTimeout));
chaviw1ff3d1e2020-07-01 15:53:47 -07004248 windowInfo->transform.dump(dump, INDENT4 "transform=");
Arthur Hungb92218b2018-08-14 12:00:21 +08004249 }
4250 } else {
4251 dump += INDENT2 "Windows: <none>\n";
4252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 }
4254 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004255 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 }
4257
Michael Wright3dd60e22019-03-27 22:06:44 +00004258 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004260 const std::vector<Monitor>& monitors = it.second;
4261 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4262 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 }
4264 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004265 const std::vector<Monitor>& monitors = it.second;
4266 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4267 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004270 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 }
4272
4273 nsecs_t currentTime = now();
4274
4275 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004276 if (!mRecentQueue.empty()) {
4277 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4278 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004279 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004281 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004284 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 }
4286
4287 // Dump event currently being dispatched.
4288 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004289 dump += INDENT "PendingEvent:\n";
4290 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004292 dump += StringPrintf(", age=%" PRId64 "ms\n",
4293 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004295 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 }
4297
4298 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004299 if (!mInboundQueue.empty()) {
4300 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4301 for (EventEntry* entry : mInboundQueue) {
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 "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 }
4309
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004310 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004311 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004312 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4313 const KeyReplacement& replacement = pair.first;
4314 int32_t newKeyCode = pair.second;
4315 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004316 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004317 }
4318 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004319 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004320 }
4321
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004322 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004323 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004324 for (const auto& pair : mConnectionsByFd) {
4325 const sp<Connection>& connection = pair.second;
4326 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004327 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004328 pair.first, connection->getInputChannelName().c_str(),
4329 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004330 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004332 if (!connection->outboundQueue.empty()) {
4333 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4334 connection->outboundQueue.size());
4335 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 dump.append(INDENT4);
4337 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004338 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4339 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004340 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004341 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 }
4343 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004344 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 }
4346
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004347 if (!connection->waitQueue.empty()) {
4348 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4349 connection->waitQueue.size());
4350 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004351 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004353 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004354 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004355 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004356 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004357 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 }
4359 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004360 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 }
4362 }
4363 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004364 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 }
4366
4367 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004368 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4369 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004371 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 }
4373
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004374 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004375 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4376 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4377 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378}
4379
Michael Wright3dd60e22019-03-27 22:06:44 +00004380void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4381 const size_t numMonitors = monitors.size();
4382 for (size_t i = 0; i < numMonitors; i++) {
4383 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004384 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004385 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4386 dump += "\n";
4387 }
4388}
4389
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004390status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004392 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393#endif
4394
4395 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004396 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004397 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004398 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004400 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 return BAD_VALUE;
4402 }
4403
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004404 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
4406 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004407 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004408 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4411 } // release lock
4412
4413 // Wake the looper because some connections have changed.
4414 mLooper->wake();
4415 return OK;
4416}
4417
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004418status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004420 { // acquire lock
4421 std::scoped_lock _l(mLock);
4422
4423 if (displayId < 0) {
4424 ALOGW("Attempted to register input monitor without a specified display.");
4425 return BAD_VALUE;
4426 }
4427
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004428 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004429 ALOGW("Attempted to register input monitor without an identifying token.");
4430 return BAD_VALUE;
4431 }
4432
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004433 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004434
4435 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004436 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004437 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004438
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 auto& monitorsByDisplay =
4440 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004441 monitorsByDisplay[displayId].emplace_back(inputChannel);
4442
4443 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004444 }
4445 // Wake the looper because some connections have changed.
4446 mLooper->wake();
4447 return OK;
4448}
4449
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004450status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004452 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453#endif
4454
4455 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004456 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457
4458 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4459 if (status) {
4460 return status;
4461 }
4462 } // release lock
4463
4464 // Wake the poll loop because removing the connection may have changed the current
4465 // synchronization state.
4466 mLooper->wake();
4467 return OK;
4468}
4469
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004470status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004471 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004472 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004473 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004475 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 return BAD_VALUE;
4477 }
4478
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004479 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004480 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004481
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 if (connection->monitor) {
4483 removeMonitorChannelLocked(inputChannel);
4484 }
4485
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004486 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487
4488 nsecs_t currentTime = now();
4489 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4490
4491 connection->status = Connection::STATUS_ZOMBIE;
4492 return OK;
4493}
4494
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004495void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004496 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4497 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4498}
4499
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004500void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004501 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004502 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004504 std::vector<Monitor>& monitors = it->second;
4505 const size_t numMonitors = monitors.size();
4506 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004507 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004508 monitors.erase(monitors.begin() + i);
4509 break;
4510 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004511 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004512 if (monitors.empty()) {
4513 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004514 } else {
4515 ++it;
4516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 }
4518}
4519
Michael Wright3dd60e22019-03-27 22:06:44 +00004520status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4521 { // acquire lock
4522 std::scoped_lock _l(mLock);
4523 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4524
4525 if (!foundDisplayId) {
4526 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4527 return BAD_VALUE;
4528 }
4529 int32_t displayId = foundDisplayId.value();
4530
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004531 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4532 mTouchStatesByDisplay.find(displayId);
4533 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004534 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4535 return BAD_VALUE;
4536 }
4537
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004538 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004539 std::optional<int32_t> foundDeviceId;
4540 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004541 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004542 foundDeviceId = state.deviceId;
4543 }
4544 }
4545 if (!foundDeviceId || !state.down) {
4546 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004547 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004548 return BAD_VALUE;
4549 }
4550 int32_t deviceId = foundDeviceId.value();
4551
4552 // Send cancel events to all the input channels we're stealing from.
4553 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004554 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004555 options.deviceId = deviceId;
4556 options.displayId = displayId;
4557 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004558 std::shared_ptr<InputChannel> channel =
4559 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004560 if (channel != nullptr) {
4561 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4562 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004563 }
4564 // Then clear the current touch state so we stop dispatching to them as well.
4565 state.filterNonMonitors();
4566 }
4567 return OK;
4568}
4569
Michael Wright3dd60e22019-03-27 22:06:44 +00004570std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4571 const sp<IBinder>& token) {
4572 for (const auto& it : mGestureMonitorsByDisplay) {
4573 const std::vector<Monitor>& monitors = it.second;
4574 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004575 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004576 return it.first;
4577 }
4578 }
4579 }
4580 return std::nullopt;
4581}
4582
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004583sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004584 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004585 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004586 }
4587
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004588 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004589 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004590 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004591 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 }
4593 }
Robert Carr4e670e52018-08-15 13:26:12 -07004594
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004595 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596}
4597
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004598void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004599 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004600 removeByValue(mConnectionsByFd, connection);
4601}
4602
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004603void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4604 const sp<Connection>& connection, uint32_t seq,
4605 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004606 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4607 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 commandEntry->connection = connection;
4609 commandEntry->eventTime = currentTime;
4610 commandEntry->seq = seq;
4611 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004612 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613}
4614
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4616 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004620 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4621 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004623 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624}
4625
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07004626void InputDispatcher::notifyFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4627 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004628 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4629 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004630 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4631 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004632 commandEntry->oldToken = oldToken;
4633 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004634 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004635}
4636
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004637void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4638 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4639 // is already healthy again. Don't raise ANR in this situation
4640 if (connection->waitQueue.empty()) {
4641 ALOGI("Not raising ANR because the connection %s has recovered",
4642 connection->inputChannel->getName().c_str());
4643 return;
4644 }
4645 /**
4646 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4647 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4648 * has changed. This could cause newer entries to time out before the already dispatched
4649 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4650 * processes the events linearly. So providing information about the oldest entry seems to be
4651 * most useful.
4652 */
4653 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4654 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4655 std::string reason =
4656 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4657 connection->inputChannel->getName().c_str(),
4658 ns2ms(currentWait),
4659 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4662 reason);
4663
4664 std::unique_ptr<CommandEntry> commandEntry =
4665 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4666 commandEntry->inputApplicationHandle = nullptr;
4667 commandEntry->inputChannel = connection->inputChannel;
4668 commandEntry->reason = std::move(reason);
4669 postCommandLocked(std::move(commandEntry));
4670}
4671
Chris Yea209fde2020-07-22 13:54:51 -07004672void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004673 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4674 application->getName().c_str());
4675
4676 updateLastAnrStateLocked(application, reason);
4677
4678 std::unique_ptr<CommandEntry> commandEntry =
4679 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4680 commandEntry->inputApplicationHandle = application;
4681 commandEntry->inputChannel = nullptr;
4682 commandEntry->reason = std::move(reason);
4683 postCommandLocked(std::move(commandEntry));
4684}
4685
4686void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4687 const std::string& reason) {
4688 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4689 updateLastAnrStateLocked(windowLabel, reason);
4690}
4691
Chris Yea209fde2020-07-22 13:54:51 -07004692void InputDispatcher::updateLastAnrStateLocked(
4693 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004694 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4695 updateLastAnrStateLocked(windowLabel, reason);
4696}
4697
4698void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4699 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004701 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 struct tm tm;
4703 localtime_r(&t, &tm);
4704 char timestr[64];
4705 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004706 mLastAnrState.clear();
4707 mLastAnrState += INDENT "ANR:\n";
4708 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004709 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4710 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004711 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712}
4713
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004714void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 mLock.unlock();
4716
4717 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4718
4719 mLock.lock();
4720}
4721
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 sp<Connection> connection = commandEntry->connection;
4724
4725 if (connection->status != Connection::STATUS_ZOMBIE) {
4726 mLock.unlock();
4727
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004728 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729
4730 mLock.lock();
4731 }
4732}
4733
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004734void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004735 sp<IBinder> oldToken = commandEntry->oldToken;
4736 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004737 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004738 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004739 mLock.lock();
4740}
4741
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004742void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004743 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004744 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 mLock.unlock();
4746
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004747 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004748 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749
4750 mLock.lock();
4751
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004752 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004753 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4754 } else {
4755 // stop waking up for events in this connection, it is already not responding
4756 sp<Connection> connection = getConnectionLocked(token);
4757 if (connection == nullptr) {
4758 return;
4759 }
4760 cancelEventsForAnrLocked(connection);
4761 }
4762}
4763
Chris Yea209fde2020-07-22 13:54:51 -07004764void InputDispatcher::extendAnrTimeoutsLocked(
4765 const std::shared_ptr<InputApplicationHandle>& application,
4766 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004767 sp<Connection> connection = getConnectionLocked(connectionToken);
4768 if (connection == nullptr) {
4769 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4770 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004771 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004772 mAwaitedFocusedApplication = application;
4773 } else {
4774 // It's also possible that the connection already disappeared. No action necessary.
4775 }
4776 return;
4777 }
4778
4779 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004780 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781
4782 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004783 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004784 for (DispatchEntry* entry : connection->waitQueue) {
4785 if (newTimeout >= entry->timeoutTime) {
4786 // Already removed old entries when connection was marked unresponsive
4787 entry->timeoutTime = newTimeout;
4788 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4789 }
4790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791}
4792
4793void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4794 CommandEntry* commandEntry) {
4795 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004796 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797
4798 mLock.unlock();
4799
Michael Wright2b3c3302018-03-02 17:19:13 +00004800 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004801 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004802 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004803 : nullptr;
4804 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004805 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4806 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004807 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809
4810 mLock.lock();
4811
4812 if (delay < 0) {
4813 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4814 } else if (!delay) {
4815 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4816 } else {
4817 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4818 entry->interceptKeyWakeupTime = now() + delay;
4819 }
4820 entry->release();
4821}
4822
chaviwfd6d3512019-03-25 13:23:49 -07004823void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4824 mLock.unlock();
4825 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4826 mLock.lock();
4827}
4828
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004829/**
4830 * Connection is responsive if it has no events in the waitQueue that are older than the
4831 * current time.
4832 */
4833static bool isConnectionResponsive(const Connection& connection) {
4834 const nsecs_t currentTime = now();
4835 for (const DispatchEntry* entry : connection.waitQueue) {
4836 if (entry->timeoutTime < currentTime) {
4837 return false;
4838 }
4839 }
4840 return true;
4841}
4842
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004843void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004845 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004847 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
4849 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004850 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004851 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004852 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004854 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004855 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004856 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004857 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4858 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004859 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004860 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004861
4862 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004863 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004864 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4865 restartEvent =
4866 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004867 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004868 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4869 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4870 handled);
4871 } else {
4872 restartEvent = false;
4873 }
4874
4875 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004876 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004877 // contents of the wait queue to have been drained, so we need to double-check
4878 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004879 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4880 if (dispatchEntryIt != connection->waitQueue.end()) {
4881 dispatchEntry = *dispatchEntryIt;
4882 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004883 mAnrTracker.erase(dispatchEntry->timeoutTime,
4884 connection->inputChannel->getConnectionToken());
4885 if (!connection->responsive) {
4886 connection->responsive = isConnectionResponsive(*connection);
4887 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004888 traceWaitQueueLength(connection);
4889 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004890 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004891 traceOutboundQueueLength(connection);
4892 } else {
4893 releaseDispatchEntry(dispatchEntry);
4894 }
4895 }
4896
4897 // Start the next dispatch cycle for this connection.
4898 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899}
4900
4901bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004902 DispatchEntry* dispatchEntry,
4903 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004904 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004905 if (!handled) {
4906 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004907 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004908 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004909 return false;
4910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004912 // Get the fallback key state.
4913 // Clear it out after dispatching the UP.
4914 int32_t originalKeyCode = keyEntry->keyCode;
4915 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4916 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4917 connection->inputState.removeFallbackKey(originalKeyCode);
4918 }
4919
4920 if (handled || !dispatchEntry->hasForegroundTarget()) {
4921 // If the application handles the original key for which we previously
4922 // generated a fallback or if the window is not a foreground window,
4923 // then cancel the associated fallback key, if any.
4924 if (fallbackKeyCode != -1) {
4925 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004927 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004928 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4929 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4930 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004932 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004933 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934
4935 mLock.unlock();
4936
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004937 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004938 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939
4940 mLock.lock();
4941
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004942 // Cancel the fallback key.
4943 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004945 "application handled the original non-fallback key "
4946 "or is no longer a foreground target, "
4947 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 options.keyCode = fallbackKeyCode;
4949 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004951 connection->inputState.removeFallbackKey(originalKeyCode);
4952 }
4953 } else {
4954 // If the application did not handle a non-fallback key, first check
4955 // that we are in a good state to perform unhandled key event processing
4956 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004957 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004958 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004960 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004961 "since this is not an initial down. "
4962 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4963 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004965 return false;
4966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004968 // Dispatch the unhandled key to the policy.
4969#if DEBUG_OUTBOUND_EVENT_DETAILS
4970 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004971 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4972 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004973#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004974 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004975
4976 mLock.unlock();
4977
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004978 bool fallback =
4979 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4980 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004981
4982 mLock.lock();
4983
4984 if (connection->status != Connection::STATUS_NORMAL) {
4985 connection->inputState.removeFallbackKey(originalKeyCode);
4986 return false;
4987 }
4988
4989 // Latch the fallback keycode for this key on an initial down.
4990 // The fallback keycode cannot change at any other point in the lifecycle.
4991 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004993 fallbackKeyCode = event.getKeyCode();
4994 } else {
4995 fallbackKeyCode = AKEYCODE_UNKNOWN;
4996 }
4997 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4998 }
4999
5000 ALOG_ASSERT(fallbackKeyCode != -1);
5001
5002 // Cancel the fallback key if the policy decides not to send it anymore.
5003 // We will continue to dispatch the key to the policy but we will no
5004 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005005 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5006 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005007#if DEBUG_OUTBOUND_EVENT_DETAILS
5008 if (fallback) {
5009 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005010 "as a fallback for %d, but on the DOWN it had requested "
5011 "to send %d instead. Fallback canceled.",
5012 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005013 } else {
5014 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005015 "but on the DOWN it had requested to send %d. "
5016 "Fallback canceled.",
5017 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005018 }
5019#endif
5020
5021 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5022 "canceling fallback, policy no longer desires it");
5023 options.keyCode = fallbackKeyCode;
5024 synthesizeCancelationEventsForConnectionLocked(connection, options);
5025
5026 fallback = false;
5027 fallbackKeyCode = AKEYCODE_UNKNOWN;
5028 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005029 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005030 }
5031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032
5033#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005034 {
5035 std::string msg;
5036 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5037 connection->inputState.getFallbackKeys();
5038 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005039 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005041 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005042 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005043 }
5044#endif
5045
5046 if (fallback) {
5047 // Restart the dispatch cycle using the fallback key.
5048 keyEntry->eventTime = event.getEventTime();
5049 keyEntry->deviceId = event.getDeviceId();
5050 keyEntry->source = event.getSource();
5051 keyEntry->displayId = event.getDisplayId();
5052 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5053 keyEntry->keyCode = fallbackKeyCode;
5054 keyEntry->scanCode = event.getScanCode();
5055 keyEntry->metaState = event.getMetaState();
5056 keyEntry->repeatCount = event.getRepeatCount();
5057 keyEntry->downTime = event.getDownTime();
5058 keyEntry->syntheticRepeat = false;
5059
5060#if DEBUG_OUTBOUND_EVENT_DETAILS
5061 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005062 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5063 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005064#endif
5065 return true; // restart the event
5066 } else {
5067#if DEBUG_OUTBOUND_EVENT_DETAILS
5068 ALOGD("Unhandled key event: No fallback key.");
5069#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005070
5071 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005072 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 }
5074 }
5075 return false;
5076}
5077
5078bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005079 DispatchEntry* dispatchEntry,
5080 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 return false;
5082}
5083
5084void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5085 mLock.unlock();
5086
5087 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5088
5089 mLock.lock();
5090}
5091
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005092KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5093 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005094 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005095 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5096 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005097 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098}
5099
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005100void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5101 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 // TODO Write some statistics about how long we spend waiting.
5103}
5104
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005105/**
5106 * Report the touch event latency to the statsd server.
5107 * Input events are reported for statistics if:
5108 * - This is a touchscreen event
5109 * - InputFilter is not enabled
5110 * - Event is not injected or synthesized
5111 *
5112 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5113 * from getting aggregated with the "old" data.
5114 */
5115void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5116 REQUIRES(mLock) {
5117 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5118 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5119 if (!reportForStatistics) {
5120 return;
5121 }
5122
5123 if (mTouchStatistics.shouldReport()) {
5124 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5125 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5126 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5127 mTouchStatistics.reset();
5128 }
5129 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5130 mTouchStatistics.addValue(latencyMicros);
5131}
5132
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133void InputDispatcher::traceInboundQueueLengthLocked() {
5134 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005135 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 }
5137}
5138
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005139void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 if (ATRACE_ENABLED()) {
5141 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005142 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005143 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 }
5145}
5146
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005147void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148 if (ATRACE_ENABLED()) {
5149 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005150 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005151 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 }
5153}
5154
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005155void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005156 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005158 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 dumpDispatchStateLocked(dump);
5160
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005161 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005162 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005163 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 }
5165}
5166
5167void InputDispatcher::monitor() {
5168 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005169 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005171 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172}
5173
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005174/**
5175 * Wake up the dispatcher and wait until it processes all events and commands.
5176 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5177 * this method can be safely called from any thread, as long as you've ensured that
5178 * the work you are interested in completing has already been queued.
5179 */
5180bool InputDispatcher::waitForIdle() {
5181 /**
5182 * Timeout should represent the longest possible time that a device might spend processing
5183 * events and commands.
5184 */
5185 constexpr std::chrono::duration TIMEOUT = 100ms;
5186 std::unique_lock lock(mLock);
5187 mLooper->wake();
5188 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5189 return result == std::cv_status::no_timeout;
5190}
5191
Vishnu Naire798b472020-07-23 13:52:21 -07005192/**
5193 * Sets focus to the window identified by the token. This must be called
5194 * after updating any input window handles.
5195 *
5196 * Params:
5197 * request.token - input channel token used to identify the window that should gain focus.
5198 * request.focusedToken - the token that the caller expects currently to be focused. If the
5199 * specified token does not match the currently focused window, this request will be dropped.
5200 * If the specified focused token matches the currently focused window, the call will succeed.
5201 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5202 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5203 * when requesting the focus change. This determines which request gets
5204 * precedence if there is a focus change request from another source such as pointer down.
5205 */
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005206void InputDispatcher::setFocusedWindow(const FocusRequest& request) {}
5207
5208void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocusedWindowHandle,
5209 const sp<InputWindowHandle>& newFocusedWindowHandle,
5210 int32_t displayId, std::string_view reason) {
5211 if (oldFocusedWindowHandle) {
5212 if (DEBUG_FOCUS) {
5213 ALOGD("Focus left window: %s in display %" PRId32,
5214 oldFocusedWindowHandle->getName().c_str(), displayId);
5215 }
5216 std::shared_ptr<InputChannel> focusedInputChannel =
5217 getInputChannelLocked(oldFocusedWindowHandle->getToken());
5218 if (focusedInputChannel) {
5219 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5220 "focus left window");
5221 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
5222 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/, reason);
5223 }
5224 mFocusedWindowHandlesByDisplay.erase(displayId);
5225 }
5226 if (newFocusedWindowHandle) {
5227 if (DEBUG_FOCUS) {
5228 ALOGD("Focus entered window: %s in display %" PRId32,
5229 newFocusedWindowHandle->getName().c_str(), displayId);
5230 }
5231 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
5232 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/, reason);
5233 }
5234
5235 if (mFocusedDisplayId == displayId) {
5236 notifyFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
5237 }
5238}
Garfield Tane84e6f92019-08-29 17:28:41 -07005239} // namespace android::inputdispatcher