blob: 323e5389083718ab50c0463e692f5b0a4a746a29 [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
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -070065#include <log/log_event_list.h>
Gang Wang342c9272020-01-13 13:15:04 -050066#include <openssl/hmac.h>
67#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070068#include <powermanager/PowerManager.h>
69#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
71#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -070082constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow for all pending events to be processed when an app switch
85// key is on the way. This is used to preempt input dispatch and drop input events
86// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000087constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow for an event to be dispatched (measured since its eventTime)
90// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Michael Wrightd02c5b62014-02-10 15:10:22 -080093// 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 +000094constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
95
96// Log a warning when an interception call takes longer than this to process.
97constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
Siarhei Vishniakoue4623042020-03-25 16:16:40 -070099// Additional key latency in case a connection is still processing some motion events.
100// This will help with the case when a user touched a button that opens a new window,
101// and gives us the chance to dispatch the key to this new window.
102constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -0700107// Event log tags. See EventLogTags.logtags for reference
108constexpr int LOGTAG_INPUT_INTERACTION = 62000;
109constexpr int LOGTAG_INPUT_FOCUS = 62001;
110
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111static inline nsecs_t now() {
112 return systemTime(SYSTEM_TIME_MONOTONIC);
113}
114
115static inline const char* toString(bool value) {
116 return value ? "true" : "false";
117}
118
119static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700120 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
121 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122}
123
124static bool isValidKeyAction(int32_t action) {
125 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700126 case AKEY_EVENT_ACTION_DOWN:
127 case AKEY_EVENT_ACTION_UP:
128 return true;
129 default:
130 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131 }
132}
133
134static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700135 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136 ALOGE("Key event has invalid action code 0x%x", action);
137 return false;
138 }
139 return true;
140}
141
Michael Wright7b159c92015-05-14 14:48:03 +0100142static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 case AMOTION_EVENT_ACTION_DOWN:
145 case AMOTION_EVENT_ACTION_UP:
146 case AMOTION_EVENT_ACTION_CANCEL:
147 case AMOTION_EVENT_ACTION_MOVE:
148 case AMOTION_EVENT_ACTION_OUTSIDE:
149 case AMOTION_EVENT_ACTION_HOVER_ENTER:
150 case AMOTION_EVENT_ACTION_HOVER_MOVE:
151 case AMOTION_EVENT_ACTION_HOVER_EXIT:
152 case AMOTION_EVENT_ACTION_SCROLL:
153 return true;
154 case AMOTION_EVENT_ACTION_POINTER_DOWN:
155 case AMOTION_EVENT_ACTION_POINTER_UP: {
156 int32_t index = getMotionEventActionPointerIndex(action);
157 return index >= 0 && index < pointerCount;
158 }
159 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
160 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
161 return actionButton != 0;
162 default:
163 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800164 }
165}
166
Michael Wright7b159c92015-05-14 14:48:03 +0100167static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 const PointerProperties* pointerProperties) {
169 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170 ALOGE("Motion event has invalid action code 0x%x", action);
171 return false;
172 }
173 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000174 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 return false;
177 }
178 BitSet32 pointerIdBits;
179 for (size_t i = 0; i < pointerCount; i++) {
180 int32_t id = pointerProperties[i].id;
181 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700182 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
183 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 return false;
185 }
186 if (pointerIdBits.hasBit(id)) {
187 ALOGE("Motion event has duplicate pointer id %d", id);
188 return false;
189 }
190 pointerIdBits.markBit(id);
191 }
192 return true;
193}
194
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800195static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800197 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 return;
199 }
200
201 bool first = true;
202 Region::const_iterator cur = region.begin();
203 Region::const_iterator const tail = region.end();
204 while (cur != tail) {
205 if (first) {
206 first = false;
207 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800208 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800210 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 cur++;
212 }
213}
214
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700215/**
216 * Find the entry in std::unordered_map by key, and return it.
217 * If the entry is not found, return a default constructed entry.
218 *
219 * Useful when the entries are vectors, since an empty vector will be returned
220 * if the entry is not found.
221 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
222 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700223template <typename K, typename V>
224static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700225 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700226 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800227}
228
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700229/**
230 * Find the entry in std::unordered_map by value, and remove it.
231 * If more than one entry has the same value, then all matching
232 * key-value pairs will be removed.
233 *
234 * Return true if at least one value has been removed.
235 */
236template <typename K, typename V>
237static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
238 bool removed = false;
239 for (auto it = map.begin(); it != map.end();) {
240 if (it->second == value) {
241 it = map.erase(it);
242 removed = true;
243 } else {
244 it++;
245 }
246 }
247 return removed;
248}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249
chaviwaf87b3e2019-10-01 16:59:28 -0700250static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
251 if (first == second) {
252 return true;
253 }
254
255 if (first == nullptr || second == nullptr) {
256 return false;
257 }
258
259 return first->getToken() == second->getToken();
260}
261
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800262static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
263 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
264}
265
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000266static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
267 EventEntry* eventEntry,
268 int32_t inputTargetFlags) {
269 if (inputTarget.useDefaultPointerInfo()) {
270 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
271 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
272 inputTargetFlags, pointerInfo.xOffset,
273 pointerInfo.yOffset, inputTarget.globalScaleFactor,
274 pointerInfo.windowXScale, pointerInfo.windowYScale);
275 }
276
277 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
278 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
279
280 PointerCoords pointerCoords[motionEntry.pointerCount];
281
282 // Use the first pointer information to normalize all other pointers. This could be any pointer
283 // as long as all other pointers are normalized to the same value and the final DispatchEntry
284 // uses the offset and scale for the normalized pointer.
285 const PointerInfo& firstPointerInfo =
286 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
287
288 // Iterate through all pointers in the event to normalize against the first.
289 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
290 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
291 uint32_t pointerId = uint32_t(pointerProperties.id);
292 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
293
294 // The scale factor is the ratio of the current pointers scale to the normalized scale.
295 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
296 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
297
298 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
299 // First apply the current pointers offset to set the window at 0,0
300 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
301 // Next scale the coordinates.
302 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
303 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
304 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
305 -firstPointerInfo.yOffset);
306 }
307
308 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800309 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
311 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
312 motionEntry.metaState, motionEntry.buttonState,
313 motionEntry.classification, motionEntry.edgeFlags,
314 motionEntry.xPrecision, motionEntry.yPrecision,
315 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
316 motionEntry.downTime, motionEntry.pointerCount,
317 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
318 0 /* yOffset */);
319
320 if (motionEntry.injectionState) {
321 combinedMotionEntry->injectionState = motionEntry.injectionState;
322 combinedMotionEntry->injectionState->refCount += 1;
323 }
324
325 std::unique_ptr<DispatchEntry> dispatchEntry =
326 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
327 inputTargetFlags, firstPointerInfo.xOffset,
328 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
329 firstPointerInfo.windowXScale,
330 firstPointerInfo.windowYScale);
331 combinedMotionEntry->release();
332 return dispatchEntry;
333}
334
Siarhei Vishniakoue0fb6bd2020-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 Arriaga3d61bc12020-04-16 18:46:48 -0700372 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500373}
374
Edgar Arriaga3d61bc12020-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 Arriaga3d61bc12020-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 Tan1c7bc862020-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 Vishniakoue4623042020-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;
431 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 Vishniakoue4623042020-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 Vishniakoue4623042020-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);
501 mAwaitedFocusedApplication.clear();
502 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
530nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
531 sp<InputWindowHandle> window = getWindowHandleLocked(token);
532 if (window != nullptr) {
533 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
534 }
535 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
536}
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 Vishniakoude1bc4a2020-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 Vishniakoue4623042020-03-25 16:16:40 -0700694 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700695 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoue4623042020-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 Vishniakoude1bc4a2020-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));
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700707 sp<InputWindowHandle> touchedWindowHandle =
708 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700709 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700710 touchedWindowHandle->getApplicationToken() !=
711 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700712 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoue4623042020-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 Vishniakoude1bc4a2020-05-26 22:39:43 -0700716 return true;
717 }
Siarhei Vishniakoue4623042020-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());
725 if (connection->responsive) {
726 // 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 Vishniakoude1bc4a2020-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 Vishniakoude1bc4a2020-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 Vishniakoude1bc4a2020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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) {
820 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821
822 if (windowInfo->visible) {
823 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 bool isTouchModal = (flags &
825 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
826 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800828 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829 if (portalToDisplayId != ADISPLAY_ID_NONE &&
830 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800831 if (addPortalWindows) {
832 // For the monitoring channels of the display.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700833 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800834 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700835 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700836 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 // Found window.
839 return windowHandle;
840 }
841 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800842
843 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700844 touchState->addOrUpdateWindow(windowHandle,
845 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
846 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
850 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700851 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852}
853
Garfield Tane84e6f92019-08-29 17:28:41 -0700854std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700855 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000856 std::vector<TouchedMonitor> touchedMonitors;
857
858 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
859 addGestureMonitors(monitors, touchedMonitors);
860 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
861 const InputWindowInfo* windowInfo = portalWindow->getInfo();
862 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
864 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000865 }
866 return touchedMonitors;
867}
868
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700869void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 const char* reason;
871 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700872 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 reason = "inbound event was dropped because the policy consumed it";
877 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700878 case DropReason::DISABLED:
879 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 ALOGI("Dropped event because input dispatch is disabled.");
881 }
882 reason = "inbound event was dropped because input dispatch is disabled";
883 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 ALOGI("Dropped event because of pending overdue app switch.");
886 reason = "inbound event was dropped because of pending overdue app switch";
887 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700888 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 ALOGI("Dropped event because the current application is not responding and the user "
890 "has started interacting with a different application.");
891 reason = "inbound event was dropped because the current application is not responding "
892 "and the user has started interacting with a different application";
893 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 ALOGI("Dropped event because it is stale.");
896 reason = "inbound event was dropped because it is stale";
897 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700898 case DropReason::NOT_DROPPED: {
899 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
903
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700905 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
907 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700910 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700911 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
912 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
914 synthesizeCancelationEventsForAllConnectionsLocked(options);
915 } else {
916 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
917 synthesizeCancelationEventsForAllConnectionsLocked(options);
918 }
919 break;
920 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100921 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700922 case EventEntry::Type::CONFIGURATION_CHANGED:
923 case EventEntry::Type::DEVICE_RESET: {
924 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
925 break;
926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
928}
929
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800930static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
932 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933}
934
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700935bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
936 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
937 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
938 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939}
940
941bool InputDispatcher::isAppSwitchPendingLocked() {
942 return mAppSwitchDueTime != LONG_LONG_MAX;
943}
944
945void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
946 mAppSwitchDueTime = LONG_LONG_MAX;
947
948#if DEBUG_APP_SWITCH
949 if (handled) {
950 ALOGD("App switch has arrived.");
951 } else {
952 ALOGD("App switch was abandoned.");
953 }
954#endif
955}
956
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700958 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959}
960
961bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700962 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 return false;
964 }
965
966 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700967 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700968 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700970 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971
972 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700973 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 return true;
975}
976
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700977void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
978 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979}
980
981void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700982 while (!mInboundQueue.empty()) {
983 EventEntry* entry = mInboundQueue.front();
984 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 releaseInboundEventLocked(entry);
986 }
987 traceInboundQueueLengthLocked();
988}
989
990void InputDispatcher::releasePendingEventLocked() {
991 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700993 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
995}
996
997void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
998 InjectionState* injectionState = entry->injectionState;
999 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1000#if DEBUG_DISPATCH_CYCLE
1001 ALOGD("Injected inbound event was dropped.");
1002#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001003 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
1005 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001006 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 }
1008 addRecentEventLocked(entry);
1009 entry->release();
1010}
1011
1012void InputDispatcher::resetKeyRepeatLocked() {
1013 if (mKeyRepeatState.lastKeyEntry) {
1014 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001015 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017}
1018
Garfield Tane84e6f92019-08-29 17:28:41 -07001019KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1021
1022 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001023 uint32_t policyFlags = entry->policyFlags &
1024 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 if (entry->refCount == 1) {
1026 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -08001027 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 entry->eventTime = currentTime;
1029 entry->policyFlags = policyFlags;
1030 entry->repeatCount += 1;
1031 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001033 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001034 entry->displayId, policyFlags, entry->action, entry->flags,
1035 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037
1038 mKeyRepeatState.lastKeyEntry = newEntry;
1039 entry->release();
1040
1041 entry = newEntry;
1042 }
1043 entry->syntheticRepeat = true;
1044
1045 // Increment reference count since we keep a reference to the event in
1046 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1047 entry->refCount += 1;
1048
1049 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1050 return entry;
1051}
1052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1054 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001056 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057#endif
1058
1059 // Reset key repeating in case a keyboard device was added or removed or something.
1060 resetKeyRepeatLocked();
1061
1062 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001063 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1064 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001066 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 return true;
1068}
1069
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001072 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074#endif
1075
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 options.deviceId = entry->deviceId;
1078 synthesizeCancelationEventsForAllConnectionsLocked(options);
1079 return true;
1080}
1081
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001082void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-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 =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001091 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-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) {
1104 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1105 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 Vishniakou7394eaa2020-04-09 11:16:18 -07001112 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1113 channel->getName();
1114 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001115 dispatchEventLocked(currentTime, entry, {target});
1116}
1117
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 if (!entry->dispatchInProgress) {
1122 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1123 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1124 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1125 if (mKeyRepeatState.lastKeyEntry &&
1126 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 // We have seen two identical key downs in a row which indicates that the device
1128 // driver is automatically generating key repeats itself. We take note of the
1129 // repeat here, but we disable our own next key repeat timer since it is clear that
1130 // we will not need to synthesize key repeats ourselves.
1131 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1132 resetKeyRepeatLocked();
1133 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1134 } else {
1135 // Not a repeat. Save key down state in case we do see a repeat later.
1136 resetKeyRepeatLocked();
1137 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1138 }
1139 mKeyRepeatState.lastKeyEntry = entry;
1140 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 resetKeyRepeatLocked();
1143 }
1144
1145 if (entry->repeatCount == 1) {
1146 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1147 } else {
1148 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1149 }
1150
1151 entry->dispatchInProgress = true;
1152
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001153 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
1155
1156 // Handle case where the policy asked us to try again later last time.
1157 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1158 if (currentTime < entry->interceptKeyWakeupTime) {
1159 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1160 *nextWakeupTime = entry->interceptKeyWakeupTime;
1161 }
1162 return false; // wait until next wakeup
1163 }
1164 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1165 entry->interceptKeyWakeupTime = 0;
1166 }
1167
1168 // Give the policy a chance to intercept the key.
1169 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1170 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001171 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001172 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001173 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001174 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001175 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
1178 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001179 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 entry->refCount += 1;
1181 return false; // wait for the command to run
1182 } else {
1183 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1184 }
1185 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001186 if (*dropReason == DropReason::NOT_DROPPED) {
1187 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 }
1189 }
1190
1191 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001192 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001193 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001194 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001196 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 return true;
1198 }
1199
1200 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001201 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001203 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1205 return false;
1206 }
1207
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001208 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1210 return true;
1211 }
1212
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001213 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001214 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215
1216 // Dispatch the key.
1217 dispatchEventLocked(currentTime, entry, inputTargets);
1218 return true;
1219}
1220
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001221void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001223 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001224 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1225 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001226 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1227 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1228 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229#endif
1230}
1231
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1233 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001234 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001236 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 entry->dispatchInProgress = true;
1238
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001239 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
1241
1242 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001243 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001244 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001245 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001246 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 return true;
1248 }
1249
1250 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1251
1252 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001253 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254
1255 bool conflictingPointerActions = false;
1256 int32_t injectionResult;
1257 if (isPointerEvent) {
1258 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 } else {
1263 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001265 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1268 return false;
1269 }
1270
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001271 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001272 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1273 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1274 return true;
1275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001277 CancelationOptions::Mode mode(isPointerEvent
1278 ? CancelationOptions::CANCEL_POINTER_EVENTS
1279 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1280 CancelationOptions options(mode, "input event injection failed");
1281 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 return true;
1283 }
1284
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001285 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001286 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001288 if (isPointerEvent) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001289 std::unordered_map<int32_t, TouchState>::iterator it =
1290 mTouchStatesByDisplay.find(entry->displayId);
1291 if (it != mTouchStatesByDisplay.end()) {
1292 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001293 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001294 // The event has gone through these portal windows, so we add monitoring targets of
1295 // the corresponding displays as well.
1296 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001297 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001298 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001300 }
1301 }
1302 }
1303 }
1304
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 // Dispatch the motion.
1306 if (conflictingPointerActions) {
1307 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 synthesizeCancelationEventsForAllConnectionsLocked(options);
1310 }
1311 dispatchEventLocked(currentTime, entry, inputTargets);
1312 return true;
1313}
1314
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001317 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001318 ", policyFlags=0x%x, "
1319 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1320 "metaState=0x%x, buttonState=0x%x,"
1321 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001322 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1323 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1324 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001326 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 "x=%f, y=%f, pressure=%f, size=%f, "
1329 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1330 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001331 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1338 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1339 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1340 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 }
1342#endif
1343}
1344
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001345void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1346 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001347 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348#if DEBUG_DISPATCH_CYCLE
1349 ALOGD("dispatchEventToCurrentInputTargets");
1350#endif
1351
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -07001352 updateInteractionTokensLocked(*eventEntry, inputTargets);
1353
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1355
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001356 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001358 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001359 sp<Connection> connection =
1360 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001361 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001362 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001364 if (DEBUG_FOCUS) {
1365 ALOGD("Dropping event delivery to target with channel '%s' because it "
1366 "is no longer registered with the input dispatcher.",
1367 inputTarget.inputChannel->getName().c_str());
1368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 }
1370 }
1371}
1372
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001373void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1374 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1375 // If the policy decides to close the app, we will get a channel removal event via
1376 // unregisterInputChannel, and will clean up the connection that way. We are already not
1377 // sending new pointers to the connection when it blocked, but focused events will continue to
1378 // pile up.
1379 ALOGW("Canceling events for %s because it is unresponsive",
1380 connection->inputChannel->getName().c_str());
1381 if (connection->status == Connection::STATUS_NORMAL) {
1382 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1383 "application not responding");
1384 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 }
1386}
1387
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001388void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001389 if (DEBUG_FOCUS) {
1390 ALOGD("Resetting ANR timeouts.");
1391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392
1393 // Reset input target wait timeout.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001394 mNoFocusedWindowTimeoutTime = std::nullopt;
1395 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396}
1397
Tiger Huang721e26f2018-07-24 22:26:19 +08001398/**
1399 * Get the display id that the given event should go to. If this event specifies a valid display id,
1400 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1401 * Focused display is the display that the user most recently interacted with.
1402 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001403int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001404 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001405 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1408 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 break;
1410 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001411 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001412 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1413 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414 break;
1415 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001416 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001417 case EventEntry::Type::CONFIGURATION_CHANGED:
1418 case EventEntry::Type::DEVICE_RESET: {
1419 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001420 return ADISPLAY_ID_NONE;
1421 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001422 }
1423 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1424}
1425
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001426bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1427 const char* focusedWindowName) {
1428 if (mAnrTracker.empty()) {
1429 // already processed all events that we waited for
1430 mKeyIsWaitingForEventsTimeout = std::nullopt;
1431 return false;
1432 }
1433
1434 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1435 // Start the timer
1436 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1437 "focus to change",
1438 focusedWindowName);
1439 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1440 return true;
1441 }
1442
1443 // We still have pending events, and already started the timer
1444 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1445 return true; // Still waiting
1446 }
1447
1448 // Waited too long, and some connection still hasn't processed all motions
1449 // Just send the key to the focused window
1450 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1451 focusedWindowName);
1452 mKeyIsWaitingForEventsTimeout = std::nullopt;
1453 return false;
1454}
1455
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001457 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001458 std::vector<InputTarget>& inputTargets,
1459 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001460 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461
Tiger Huang721e26f2018-07-24 22:26:19 +08001462 int32_t displayId = getTargetDisplayId(entry);
1463 sp<InputWindowHandle> focusedWindowHandle =
1464 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1465 sp<InputApplicationHandle> focusedApplicationHandle =
1466 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1467
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 // If there is no currently focused window and no focused application
1469 // then drop the event.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001470 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1471 ALOGI("Dropping %s event because there is no focused window or focused application in "
1472 "display %" PRId32 ".",
1473 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001474 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 }
1476
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001477 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1478 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1479 // start interacting with another application via touch (app switch). This code can be removed
1480 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1481 // an app is expected to have a focused window.
1482 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1483 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1484 // We just discovered that there's no focused window. Start the ANR timer
1485 const nsecs_t timeout = focusedApplicationHandle->getDispatchingTimeout(
1486 DEFAULT_INPUT_DISPATCHING_TIMEOUT.count());
1487 mNoFocusedWindowTimeoutTime = currentTime + timeout;
1488 mAwaitedFocusedApplication = focusedApplicationHandle;
1489 ALOGW("Waiting because no window has focus but %s may eventually add a "
1490 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1491 mAwaitedFocusedApplication->getName().c_str(), ns2ms(timeout));
1492 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1493 return INPUT_EVENT_INJECTION_PENDING;
1494 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1495 // Already raised ANR. Drop the event
1496 ALOGE("Dropping %s event because there is no focused window",
1497 EventEntry::typeToString(entry.type));
1498 return INPUT_EVENT_INJECTION_FAILED;
1499 } else {
1500 // Still waiting for the focused window
1501 return INPUT_EVENT_INJECTION_PENDING;
1502 }
1503 }
1504
1505 // we have a valid, non-null focused window
1506 resetNoFocusedWindowTimeoutLocked();
1507
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001509 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001510 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 }
1512
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001513 if (focusedWindowHandle->getInfo()->paused) {
1514 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1515 return INPUT_EVENT_INJECTION_PENDING;
1516 }
1517
1518 // If the event is a key event, then we must wait for all previous events to
1519 // complete before delivering it because previous events may have the
1520 // side-effect of transferring focus to a different window and we want to
1521 // ensure that the following keys are sent to the new window.
1522 //
1523 // Suppose the user touches a button in a window then immediately presses "A".
1524 // If the button causes a pop-up window to appear then we want to ensure that
1525 // the "A" key is delivered to the new pop-up window. This is because users
1526 // often anticipate pending UI changes when typing on a keyboard.
1527 // To obtain this behavior, we must serialize key events with respect to all
1528 // prior input events.
1529 if (entry.type == EventEntry::Type::KEY) {
1530 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1531 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1532 return INPUT_EVENT_INJECTION_PENDING;
1533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 }
1535
1536 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001537 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001538 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1539 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540
1541 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001542 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543}
1544
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001545/**
1546 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1547 * that are currently unresponsive.
1548 */
1549std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1550 const std::vector<TouchedMonitor>& monitors) const {
1551 std::vector<TouchedMonitor> responsiveMonitors;
1552 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1553 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1554 sp<Connection> connection = getConnectionLocked(
1555 monitor.monitor.inputChannel->getConnectionToken());
1556 if (connection == nullptr) {
1557 ALOGE("Could not find connection for monitor %s",
1558 monitor.monitor.inputChannel->getName().c_str());
1559 return false;
1560 }
1561 if (!connection->responsive) {
1562 ALOGW("Unresponsive monitor %s will not get the new gesture",
1563 connection->inputChannel->getName().c_str());
1564 return false;
1565 }
1566 return true;
1567 });
1568 return responsiveMonitors;
1569}
1570
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001572 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001573 std::vector<InputTarget>& inputTargets,
1574 nsecs_t* nextWakeupTime,
1575 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001576 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 enum InjectionPermission {
1578 INJECTION_PERMISSION_UNKNOWN,
1579 INJECTION_PERMISSION_GRANTED,
1580 INJECTION_PERMISSION_DENIED
1581 };
1582
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 // For security reasons, we defer updating the touch state until we are sure that
1584 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001585 int32_t displayId = entry.displayId;
1586 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1588
1589 // Update the touch state as needed based on the properties of the touch event.
1590 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1591 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1592 sp<InputWindowHandle> newHoverWindowHandle;
1593
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001594 // Copy current touch state into tempTouchState.
1595 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1596 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001597 const TouchState* oldState = nullptr;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001598 TouchState tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001599 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1600 mTouchStatesByDisplay.find(displayId);
1601 if (oldStateIt != mTouchStatesByDisplay.end()) {
1602 oldState = &(oldStateIt->second);
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001603 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001604 }
1605
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001606 bool isSplit = tempTouchState.split;
1607 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1608 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1609 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1611 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1612 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1613 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1614 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001615 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 bool wrongDevice = false;
1617 if (newGesture) {
1618 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001619 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001620 ALOGI("Dropping event because a pointer for a different device is already down "
1621 "in display %" PRId32,
1622 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001623 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1625 switchedDevice = false;
1626 wrongDevice = true;
1627 goto Failed;
1628 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001629 tempTouchState.reset();
1630 tempTouchState.down = down;
1631 tempTouchState.deviceId = entry.deviceId;
1632 tempTouchState.source = entry.source;
1633 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001635 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001636 ALOGI("Dropping move event because a pointer for a different device is already active "
1637 "in display %" PRId32,
1638 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001639 // TODO: test multiple simultaneous input streams.
1640 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1641 switchedDevice = false;
1642 wrongDevice = true;
1643 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 }
1645
1646 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1647 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1648
Garfield Tan00f511d2019-06-12 16:55:40 -07001649 int32_t x;
1650 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001652 // Always dispatch mouse events to cursor position.
1653 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 x = int32_t(entry.xCursorPosition);
1655 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001656 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1658 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001659 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001660 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001662 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1663 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001664
1665 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001666 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001667 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001670 if (newTouchedWindowHandle != nullptr &&
1671 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001672 // New window supports splitting, but we should never split mouse events.
1673 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 } else if (isSplit) {
1675 // New window does not support splitting but we have already split events.
1676 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001677 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 }
1679
1680 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001681 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001683 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001684 }
1685
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001686 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1687 ALOGI("Not sending touch event to %s because it is paused",
1688 newTouchedWindowHandle->getName().c_str());
1689 newTouchedWindowHandle = nullptr;
1690 }
1691
1692 if (newTouchedWindowHandle != nullptr) {
1693 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1694 if (connection == nullptr) {
1695 ALOGI("Could not find connection for %s",
1696 newTouchedWindowHandle->getName().c_str());
1697 newTouchedWindowHandle = nullptr;
1698 } else if (!connection->responsive) {
1699 // don't send the new touch to an unresponsive window
1700 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1701 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.
1730 if (isHoverAction) {
1731 newHoverWindowHandle = newTouchedWindowHandle;
1732 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1733 newHoverWindowHandle = mLastHoverWindowHandle;
1734 }
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 Vishniakou1ea3cf12020-03-24 19:50:03 -07001742 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 }
1744
Siarhei Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-03-24 19:50:03 -07001767 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001769 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001770 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1771 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001772 if (DEBUG_FOCUS) {
1773 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1774 oldTouchedWindowHandle->getName().c_str(),
1775 newTouchedWindowHandle->getName().c_str(), displayId);
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 // Make a slippery exit from the old window.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001778 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1779 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1780 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781
1782 // Make a slippery entrance into the new window.
1783 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1784 isSplit = true;
1785 }
1786
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001787 int32_t targetFlags =
1788 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 if (isSplit) {
1790 targetFlags |= InputTarget::FLAG_SPLIT;
1791 }
1792 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1793 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1794 }
1795
1796 BitSet32 pointerIds;
1797 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001798 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001800 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 }
1802 }
1803 }
1804
1805 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1806 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001807 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808#if DEBUG_HOVER
1809 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001810 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001812 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1813 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 }
1815
1816 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001817 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818#if DEBUG_HOVER
1819 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001822 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1823 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1824 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 }
1826 }
1827
1828 // Check permission to inject into all touched foreground windows and ensure there
1829 // is at least one touched foreground window.
1830 {
1831 bool haveForegroundWindow = false;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001832 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1834 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001835 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1837 injectionPermission = INJECTION_PERMISSION_DENIED;
1838 goto Failed;
1839 }
1840 }
1841 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001842 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001843 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001844 ALOGI("Dropping event because there is no touched foreground window in display "
1845 "%" PRId32 " or gesture monitor to receive it.",
1846 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1848 goto Failed;
1849 }
1850
1851 // Permission granted to injection into all touched foreground windows.
1852 injectionPermission = INJECTION_PERMISSION_GRANTED;
1853 }
1854
1855 // Check whether windows listening for outside touches are owned by the same UID. If it is
1856 // set the policy flag that we will not reveal coordinate information to this window.
1857 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1858 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001859 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001860 if (foregroundWindowHandle) {
1861 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001862 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001863 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1864 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1865 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001866 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1867 InputTarget::FLAG_ZERO_COORDS,
1868 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
1871 }
1872 }
1873 }
1874
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 // If this is the first pointer going down and the touched window has a wallpaper
1876 // then also add the touched wallpaper windows so they are locked in for the duration
1877 // of the touch gesture.
1878 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1879 // engine only supports touch events. We would need to add a mechanism similar
1880 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1881 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1882 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001883 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001884 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001885 const std::vector<sp<InputWindowHandle>> windowHandles =
1886 getWindowHandlesLocked(displayId);
1887 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001889 if (info->displayId == displayId &&
1890 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001891 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 .addOrUpdateWindow(windowHandle,
1893 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1894 InputTarget::
1895 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1896 InputTarget::FLAG_DISPATCH_AS_IS,
1897 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
1899 }
1900 }
1901 }
1902
1903 // Success! Output targets.
1904 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1905
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001906 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001908 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001911 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001912 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001913 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001914 }
1915
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 // Drop the outside or hover touch windows since we will not care about them
1917 // in the next iteration.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001918 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919
1920Failed:
1921 // Check injection permission once and for all.
1922 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001923 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 injectionPermission = INJECTION_PERMISSION_GRANTED;
1925 } else {
1926 injectionPermission = INJECTION_PERMISSION_DENIED;
1927 }
1928 }
1929
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001930 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1931 return injectionResult;
1932 }
1933
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001935 if (!wrongDevice) {
1936 if (switchedDevice) {
1937 if (DEBUG_FOCUS) {
1938 ALOGD("Conflicting pointer actions: Switched to a different device.");
1939 }
1940 *outConflictingPointerActions = true;
1941 }
1942
1943 if (isHoverAction) {
1944 // Started hovering, therefore no longer down.
1945 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001946 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001947 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1948 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 *outConflictingPointerActions = true;
1951 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001952 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001953 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1954 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001955 tempTouchState.deviceId = entry.deviceId;
1956 tempTouchState.source = entry.source;
1957 tempTouchState.displayId = displayId;
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001958 }
1959 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1960 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1961 // All pointers up or canceled.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001962 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001963 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1964 // First pointer went down.
1965 if (oldState && oldState->down) {
1966 if (DEBUG_FOCUS) {
1967 ALOGD("Conflicting pointer actions: Down received while already down.");
1968 }
1969 *outConflictingPointerActions = true;
1970 }
1971 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1972 // One pointer went up.
1973 if (isSplit) {
1974 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1975 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001977 for (size_t i = 0; i < tempTouchState.windows.size();) {
1978 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001979 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1980 touchedWindow.pointerIds.clearBit(pointerId);
1981 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001982 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001983 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001986 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001988 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001989 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001990
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001991 // Save changes unless the action was scroll in which case the temporary touch
1992 // state was only valid for this one action.
1993 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001994 if (tempTouchState.displayId >= 0) {
1995 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001996 } else {
1997 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002001 // Update hover state.
2002 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 }
2004
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 return injectionResult;
2006}
2007
2008void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002009 int32_t targetFlags, BitSet32 pointerIds,
2010 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002011 std::vector<InputTarget>::iterator it =
2012 std::find_if(inputTargets.begin(), inputTargets.end(),
2013 [&windowHandle](const InputTarget& inputTarget) {
2014 return inputTarget.inputChannel->getConnectionToken() ==
2015 windowHandle->getToken();
2016 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002017
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002018 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002019
2020 if (it == inputTargets.end()) {
2021 InputTarget inputTarget;
2022 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2023 if (inputChannel == nullptr) {
2024 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2025 return;
2026 }
2027 inputTarget.inputChannel = inputChannel;
2028 inputTarget.flags = targetFlags;
2029 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2030 inputTargets.push_back(inputTarget);
2031 it = inputTargets.end() - 1;
2032 }
2033
2034 ALOG_ASSERT(it->flags == targetFlags);
2035 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2036
2037 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2038 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039}
2040
Michael Wright3dd60e22019-03-27 22:06:44 +00002041void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002042 int32_t displayId, float xOffset,
2043 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002044 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2045 mGlobalMonitorsByDisplay.find(displayId);
2046
2047 if (it != mGlobalMonitorsByDisplay.end()) {
2048 const std::vector<Monitor>& monitors = it->second;
2049 for (const Monitor& monitor : monitors) {
2050 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 }
2053}
2054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002055void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2056 float yOffset,
2057 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002058 InputTarget target;
2059 target.inputChannel = monitor.inputChannel;
2060 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002061 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 inputTargets.push_back(target);
2063}
2064
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002066 const InjectionState* injectionState) {
2067 if (injectionState &&
2068 (windowHandle == nullptr ||
2069 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2070 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002071 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002073 "owned by uid %d",
2074 injectionState->injectorPid, injectionState->injectorUid,
2075 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 } else {
2077 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002078 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080 return false;
2081 }
2082 return true;
2083}
2084
Robert Carr9cada032020-04-13 17:21:08 -07002085/**
2086 * Indicate whether one window handle should be considered as obscuring
2087 * another window handle. We only check a few preconditions. Actually
2088 * checking the bounds is left to the caller.
2089 */
2090static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2091 const sp<InputWindowHandle>& otherHandle) {
2092 // Compare by token so cloned layers aren't counted
2093 if (haveSameToken(windowHandle, otherHandle)) {
2094 return false;
2095 }
2096 auto info = windowHandle->getInfo();
2097 auto otherInfo = otherHandle->getInfo();
2098 if (!otherInfo->visible) {
2099 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002100 } else if (info->ownerPid == otherInfo->ownerPid) {
2101 // If ownerPid is the same we don't generate occlusion events as there
2102 // is no in-process security boundary.
Robert Carr9cada032020-04-13 17:21:08 -07002103 return false;
2104 } else if (otherInfo->isTrustedOverlay()) {
2105 return false;
2106 } else if (otherInfo->displayId != info->displayId) {
2107 return false;
2108 }
2109 return true;
2110}
2111
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002112bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2113 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002115 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2116 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002117 if (windowHandle == otherHandle) {
2118 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002121 if (canBeObscuredBy(windowHandle, otherHandle) &&
2122 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 return true;
2124 }
2125 }
2126 return false;
2127}
2128
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002129bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2130 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002131 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002132 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002133 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002134 if (windowHandle == otherHandle) {
2135 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002136 }
2137
2138 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002139 if (canBeObscuredBy(windowHandle, otherHandle) &&
2140 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002141 return true;
2142 }
2143 }
2144 return false;
2145}
2146
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002147std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 const sp<InputApplicationHandle>& applicationHandle,
2149 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002150 if (applicationHandle != nullptr) {
2151 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002152 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 } else {
2154 return applicationHandle->getName();
2155 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002156 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002157 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002159 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161}
2162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002164 if (eventEntry.type == EventEntry::Type::FOCUS) {
2165 // Focus events are passed to apps, but do not represent user activity.
2166 return;
2167 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002168 int32_t displayId = getTargetDisplayId(eventEntry);
2169 sp<InputWindowHandle> focusedWindowHandle =
2170 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2171 if (focusedWindowHandle != nullptr) {
2172 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2174#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002175 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176#endif
2177 return;
2178 }
2179 }
2180
2181 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002183 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002184 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2185 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002186 return;
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002190 eventType = USER_ACTIVITY_EVENT_TOUCH;
2191 }
2192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002194 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002195 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2196 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 return;
2198 }
2199 eventType = USER_ACTIVITY_EVENT_BUTTON;
2200 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002202 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002203 case EventEntry::Type::CONFIGURATION_CHANGED:
2204 case EventEntry::Type::DEVICE_RESET: {
2205 LOG_ALWAYS_FATAL("%s events are not user activity",
2206 EventEntry::typeToString(eventEntry.type));
2207 break;
2208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 }
2210
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002211 std::unique_ptr<CommandEntry> commandEntry =
2212 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002213 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216}
2217
2218void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 const sp<Connection>& connection,
2220 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002221 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002224 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002225 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002226 ATRACE_NAME(message.c_str());
2227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#if DEBUG_DISPATCH_CYCLE
2229 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002230 "globalScaleFactor=%f, pointerIds=0x%x %s",
2231 connection->getInputChannelName().c_str(), inputTarget.flags,
2232 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2233 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#endif
2235
2236 // Skip this event if the connection status is not normal.
2237 // We don't want to enqueue additional outbound events if the connection is broken.
2238 if (connection->status != Connection::STATUS_NORMAL) {
2239#if DEBUG_DISPATCH_CYCLE
2240 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242#endif
2243 return;
2244 }
2245
2246 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2248 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2249 "Entry type %s should not have FLAG_SPLIT",
2250 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002253 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002255 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 if (!splitMotionEntry) {
2257 return; // split event was dropped
2258 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002259 if (DEBUG_FOCUS) {
2260 ALOGD("channel '%s' ~ Split motion event.",
2261 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002262 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002263 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 splitMotionEntry->release();
2266 return;
2267 }
2268 }
2269
2270 // Not splitting. Enqueue dispatch entries for the event as is.
2271 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2272}
2273
2274void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 const sp<Connection>& connection,
2276 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002277 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002280 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002281 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 ATRACE_NAME(message.c_str());
2283 }
2284
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002285 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
2301 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002302 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 startDispatchCycleLocked(currentTime, connection);
2304 }
2305}
2306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2308 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002309 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002311 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2313 connection->getInputChannelName().c_str(),
2314 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002315 ATRACE_NAME(message.c_str());
2316 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002317 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 if (!(inputTargetFlags & dispatchMode)) {
2319 return;
2320 }
2321 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2322
2323 // This is a new event.
2324 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002325 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2329 // different EventEntry than what was passed in.
2330 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002333 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002335 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002336 dispatchEntry->resolvedAction = keyEntry.action;
2337 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2340 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2343 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 return; // skip the inconsistent event
2346 }
2347 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002350 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002351 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002352 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2353 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2354 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2355 static_cast<int32_t>(IdGenerator::Source::OTHER);
2356 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2359 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2361 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2367 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002368 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002369 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 }
2371 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2373 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2376 "event",
2377 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002382 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2384 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2385 }
2386 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2387 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2391 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002393 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2394 "event",
2395 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 return; // skip the inconsistent event
2398 }
2399
Garfield Tan1c7bc862020-01-28 13:24:04 -08002400 dispatchEntry->resolvedEventId =
2401 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2402 ? mIdGenerator.nextId()
2403 : motionEntry.id;
2404 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2405 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2406 ") to MotionEvent(id=0x%" PRIx32 ").",
2407 motionEntry.id, dispatchEntry->resolvedEventId);
2408 ATRACE_NAME(message.c_str());
2409 }
2410
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002411 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002412 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413
2414 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002416 case EventEntry::Type::FOCUS: {
2417 break;
2418 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002419 case EventEntry::Type::CONFIGURATION_CHANGED:
2420 case EventEntry::Type::DEVICE_RESET: {
2421 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002422 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002423 break;
2424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426
2427 // Remember that we are waiting for this dispatch to complete.
2428 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002429 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
2432 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002433 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002434 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002435}
2436
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -07002437/**
2438 * This function is purely for debugging. It helps us understand where the user interaction
2439 * was taking place. For example, if user is touching launcher, we will see a log that user
2440 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2441 * We will see both launcher and wallpaper in that list.
2442 * Once the interaction with a particular set of connections starts, no new logs will be printed
2443 * until the set of interacted connections changes.
2444 *
2445 * The following items are skipped, to reduce the logspam:
2446 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2447 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2448 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2449 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2450 * Both of those ACTION_UP events would not be logged
2451 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2452 * will not be logged. This is omitted to reduce the amount of data printed.
2453 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2454 * gesture monitor is the only connection receiving the remainder of the gesture.
2455 */
2456void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2457 const std::vector<InputTarget>& targets) {
2458 // Skip ACTION_UP events, and all events other than keys and motions
2459 if (entry.type == EventEntry::Type::KEY) {
2460 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2461 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2462 return;
2463 }
2464 } else if (entry.type == EventEntry::Type::MOTION) {
2465 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2466 if (motionEntry.action == AMOTION_EVENT_ACTION_UP) {
2467 return;
2468 }
2469 } else {
2470 return; // Not a key or a motion
2471 }
2472
2473 std::unordered_set<sp<IBinder>, IBinderHash> newConnections;
2474 for (const InputTarget& target : targets) {
2475 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2476 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2477 continue; // Skip windows that receive ACTION_OUTSIDE
2478 }
2479
2480 sp<IBinder> token = target.inputChannel->getConnectionToken();
2481 sp<Connection> connection = getConnectionLocked(token); // get connection
2482 if (connection->monitor) {
2483 continue; // We only need to keep track of the non-monitor connections.
2484 }
2485
2486 newConnections.insert(std::move(token));
2487 }
2488 if (newConnections == mInteractionConnections) {
2489 return; // no change
2490 }
2491 mInteractionConnections = newConnections;
2492 std::string windowList;
2493 for (const sp<IBinder>& token : newConnections) {
2494 sp<Connection> connection = getConnectionLocked(token);
2495 windowList += connection->getWindowName() + ", ";
2496 }
2497 std::string message = "Interaction with windows: " + windowList;
2498 if (windowList.empty()) {
2499 message += "<none>";
2500 }
2501 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2502}
2503
chaviwfd6d3512019-03-25 13:23:49 -07002504void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002505 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002506 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002507 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2508 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002509 return;
2510 }
2511
2512 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2513 if (inputWindowHandle == nullptr) {
2514 return;
2515 }
2516
chaviw8c9cf542019-03-25 13:02:48 -07002517 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002518 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002519
2520 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2521
2522 if (!hasFocusChanged) {
2523 return;
2524 }
2525
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002526 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2527 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002528 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002529 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530}
2531
2532void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002534 if (ATRACE_ENABLED()) {
2535 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002537 ATRACE_NAME(message.c_str());
2538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541#endif
2542
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002543 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2544 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002546 const nsecs_t timeout =
2547 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2548 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549
2550 // Publish the event.
2551 status_t status;
2552 EventEntry* eventEntry = dispatchEntry->eventEntry;
2553 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002554 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002555 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2556 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002558 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002559 status =
2560 connection->inputPublisher
2561 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2562 keyEntry->deviceId, keyEntry->source,
2563 keyEntry->displayId, std::move(hmac),
2564 dispatchEntry->resolvedAction,
2565 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2566 keyEntry->scanCode, keyEntry->metaState,
2567 keyEntry->repeatCount, keyEntry->downTime,
2568 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002572 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 PointerCoords scaledCoords[MAX_POINTERS];
2576 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2577
chaviw82357092020-01-28 13:13:06 -08002578 // Set the X and Y offset and X and Y scale depending on the input source.
2579 float xOffset = 0.0f, yOffset = 0.0f;
2580 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2582 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2583 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002584 xScale = dispatchEntry->windowXScale;
2585 yScale = dispatchEntry->windowYScale;
2586 xOffset = dispatchEntry->xOffset * xScale;
2587 yOffset = dispatchEntry->yOffset * yScale;
2588 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2590 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002591 // Don't apply window scale here since we don't want scale to affect raw
2592 // coordinates. The scale will be sent back to the client and applied
2593 // later when requesting relative coordinates.
2594 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2595 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002596 }
2597 usingCoords = scaledCoords;
2598 }
2599 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002600 // We don't want the dispatch target to know.
2601 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2602 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2603 scaledCoords[i].clear();
2604 }
2605 usingCoords = scaledCoords;
2606 }
2607 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002608
2609 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002610
2611 // Publish the motion event.
2612 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002613 .publishMotionEvent(dispatchEntry->seq,
2614 dispatchEntry->resolvedEventId,
2615 motionEntry->deviceId, motionEntry->source,
2616 motionEntry->displayId, std::move(hmac),
2617 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002618 motionEntry->actionButton,
2619 dispatchEntry->resolvedFlags,
2620 motionEntry->edgeFlags, motionEntry->metaState,
2621 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002622 motionEntry->classification, xScale, yScale,
2623 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002624 motionEntry->yPrecision,
2625 motionEntry->xCursorPosition,
2626 motionEntry->yCursorPosition,
2627 motionEntry->downTime, motionEntry->eventTime,
2628 motionEntry->pointerCount,
2629 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002630 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002631 break;
2632 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002633 case EventEntry::Type::FOCUS: {
2634 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2635 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002636 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002637 focusEntry->hasFocus,
2638 mInTouchMode);
2639 break;
2640 }
2641
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002642 case EventEntry::Type::CONFIGURATION_CHANGED:
2643 case EventEntry::Type::DEVICE_RESET: {
2644 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2645 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 }
2649
2650 // Check the result.
2651 if (status) {
2652 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002653 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 "This is unexpected because the wait queue is empty, so the pipe "
2656 "should be empty and we shouldn't have any problems writing an "
2657 "event to it, status=%d",
2658 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2660 } else {
2661 // Pipe is full and we are waiting for the app to finish process some events
2662 // before sending more events to it.
2663#if DEBUG_DISPATCH_CYCLE
2664 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 "waiting for the application to catch up",
2666 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 }
2669 } else {
2670 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002671 "status=%d",
2672 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2674 }
2675 return;
2676 }
2677
2678 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002679 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2680 connection->outboundQueue.end(),
2681 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002682 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002683 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002684 if (connection->responsive) {
2685 mAnrTracker.insert(dispatchEntry->timeoutTime,
2686 connection->inputChannel->getConnectionToken());
2687 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002688 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 }
2690}
2691
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002692const std::array<uint8_t, 32> InputDispatcher::getSignature(
2693 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2694 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2695 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2696 // Only sign events up and down events as the purely move events
2697 // are tied to their up/down counterparts so signing would be redundant.
2698 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2699 verifiedEvent.actionMasked = actionMasked;
2700 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2701 return mHmacKeyManager.sign(verifiedEvent);
2702 }
2703 return INVALID_HMAC;
2704}
2705
2706const std::array<uint8_t, 32> InputDispatcher::getSignature(
2707 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2708 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2709 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2710 verifiedEvent.action = dispatchEntry.resolvedAction;
2711 return mHmacKeyManager.sign(verifiedEvent);
2712}
2713
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002715 const sp<Connection>& connection, uint32_t seq,
2716 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717#if DEBUG_DISPATCH_CYCLE
2718 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720#endif
2721
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 if (connection->status == Connection::STATUS_BROKEN ||
2723 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 return;
2725 }
2726
2727 // Notify other system components and prepare to start the next dispatch cycle.
2728 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2729}
2730
2731void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 const sp<Connection>& connection,
2733 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734#if DEBUG_DISPATCH_CYCLE
2735 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737#endif
2738
2739 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002740 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002741 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002742 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002743 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744
2745 // The connection appears to be unrecoverably broken.
2746 // Ignore already broken or zombie connections.
2747 if (connection->status == Connection::STATUS_NORMAL) {
2748 connection->status = Connection::STATUS_BROKEN;
2749
2750 if (notify) {
2751 // Notify other system components.
2752 onDispatchCycleBrokenLocked(currentTime, connection);
2753 }
2754 }
2755}
2756
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002757void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2758 while (!queue.empty()) {
2759 DispatchEntry* dispatchEntry = queue.front();
2760 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002761 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
2763}
2764
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002765void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002767 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 }
2769 delete dispatchEntry;
2770}
2771
2772int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2773 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2774
2775 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002776 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002778 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 "fd=%d, events=0x%x",
2781 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 return 0; // remove the callback
2783 }
2784
2785 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002786 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2788 if (!(events & ALOOPER_EVENT_INPUT)) {
2789 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 "events=0x%x",
2791 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 return 1;
2793 }
2794
2795 nsecs_t currentTime = now();
2796 bool gotOne = false;
2797 status_t status;
2798 for (;;) {
2799 uint32_t seq;
2800 bool handled;
2801 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2802 if (status) {
2803 break;
2804 }
2805 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2806 gotOne = true;
2807 }
2808 if (gotOne) {
2809 d->runCommandsLockedInterruptible();
2810 if (status == WOULD_BLOCK) {
2811 return 1;
2812 }
2813 }
2814
2815 notify = status != DEAD_OBJECT || !connection->monitor;
2816 if (notify) {
2817 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 }
2820 } else {
2821 // Monitor channels are never explicitly unregistered.
2822 // We do it automatically when the remote endpoint is closed so don't warn
2823 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002824 const bool stillHaveWindowHandle =
2825 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2826 nullptr;
2827 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 if (notify) {
2829 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830 "events=0x%x",
2831 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 }
2833 }
2834
2835 // Unregister the channel.
2836 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2837 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839}
2840
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002843 for (const auto& pair : mConnectionsByFd) {
2844 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 }
2846}
2847
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002848void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002849 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002850 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2851 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2852}
2853
2854void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2855 const CancelationOptions& options,
2856 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2857 for (const auto& it : monitorsByDisplay) {
2858 const std::vector<Monitor>& monitors = it.second;
2859 for (const Monitor& monitor : monitors) {
2860 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002861 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002862 }
2863}
2864
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2866 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002867 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002868 if (connection == nullptr) {
2869 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002871
2872 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873}
2874
2875void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2876 const sp<Connection>& connection, const CancelationOptions& options) {
2877 if (connection->status == Connection::STATUS_BROKEN) {
2878 return;
2879 }
2880
2881 nsecs_t currentTime = now();
2882
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002883 std::vector<EventEntry*> cancelationEvents =
2884 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002886 if (cancelationEvents.empty()) {
2887 return;
2888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002890 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2891 "with reality: %s, mode=%d.",
2892 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2893 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002895
2896 InputTarget target;
2897 sp<InputWindowHandle> windowHandle =
2898 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2899 if (windowHandle != nullptr) {
2900 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2901 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2902 windowInfo->windowXScale, windowInfo->windowYScale);
2903 target.globalScaleFactor = windowInfo->globalScaleFactor;
2904 }
2905 target.inputChannel = connection->inputChannel;
2906 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2907
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002908 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2909 EventEntry* cancelationEventEntry = cancelationEvents[i];
2910 switch (cancelationEventEntry->type) {
2911 case EventEntry::Type::KEY: {
2912 logOutboundKeyDetails("cancel - ",
2913 static_cast<const KeyEntry&>(*cancelationEventEntry));
2914 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002916 case EventEntry::Type::MOTION: {
2917 logOutboundMotionDetails("cancel - ",
2918 static_cast<const MotionEntry&>(*cancelationEventEntry));
2919 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002921 case EventEntry::Type::FOCUS: {
2922 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2923 break;
2924 }
2925 case EventEntry::Type::CONFIGURATION_CHANGED:
2926 case EventEntry::Type::DEVICE_RESET: {
2927 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2928 EventEntry::typeToString(cancelationEventEntry->type));
2929 break;
2930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
2932
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002933 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2934 target, InputTarget::FLAG_DISPATCH_AS_IS);
2935
2936 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002938
2939 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940}
2941
Svet Ganov5d3bc372020-01-26 23:11:07 -08002942void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2943 const sp<Connection>& connection) {
2944 if (connection->status == Connection::STATUS_BROKEN) {
2945 return;
2946 }
2947
2948 nsecs_t currentTime = now();
2949
2950 std::vector<EventEntry*> downEvents =
2951 connection->inputState.synthesizePointerDownEvents(currentTime);
2952
2953 if (downEvents.empty()) {
2954 return;
2955 }
2956
2957#if DEBUG_OUTBOUND_EVENT_DETAILS
2958 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2959 connection->getInputChannelName().c_str(), downEvents.size());
2960#endif
2961
2962 InputTarget target;
2963 sp<InputWindowHandle> windowHandle =
2964 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2965 if (windowHandle != nullptr) {
2966 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2967 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2968 windowInfo->windowXScale, windowInfo->windowYScale);
2969 target.globalScaleFactor = windowInfo->globalScaleFactor;
2970 }
2971 target.inputChannel = connection->inputChannel;
2972 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2973
2974 for (EventEntry* downEventEntry : downEvents) {
2975 switch (downEventEntry->type) {
2976 case EventEntry::Type::MOTION: {
2977 logOutboundMotionDetails("down - ",
2978 static_cast<const MotionEntry&>(*downEventEntry));
2979 break;
2980 }
2981
2982 case EventEntry::Type::KEY:
2983 case EventEntry::Type::FOCUS:
2984 case EventEntry::Type::CONFIGURATION_CHANGED:
2985 case EventEntry::Type::DEVICE_RESET: {
2986 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2987 EventEntry::typeToString(downEventEntry->type));
2988 break;
2989 }
2990 }
2991
2992 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2993 target, InputTarget::FLAG_DISPATCH_AS_IS);
2994
2995 downEventEntry->release();
2996 }
2997
2998 startDispatchCycleLocked(currentTime, connection);
2999}
3000
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003001MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003002 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 ALOG_ASSERT(pointerIds.value != 0);
3004
3005 uint32_t splitPointerIndexMap[MAX_POINTERS];
3006 PointerProperties splitPointerProperties[MAX_POINTERS];
3007 PointerCoords splitPointerCoords[MAX_POINTERS];
3008
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003009 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 uint32_t splitPointerCount = 0;
3011
3012 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003015 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016 uint32_t pointerId = uint32_t(pointerProperties.id);
3017 if (pointerIds.hasBit(pointerId)) {
3018 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3019 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3020 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003021 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 splitPointerCount += 1;
3023 }
3024 }
3025
3026 if (splitPointerCount != pointerIds.count()) {
3027 // This is bad. We are missing some of the pointers that we expected to deliver.
3028 // Most likely this indicates that we received an ACTION_MOVE events that has
3029 // different pointer ids than we expected based on the previous ACTION_DOWN
3030 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3031 // in this way.
3032 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003033 "we expected there to be %d pointers. This probably means we received "
3034 "a broken sequence of pointer ids from the input device.",
3035 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003036 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 }
3038
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003039 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3042 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3044 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003045 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 uint32_t pointerId = uint32_t(pointerProperties.id);
3047 if (pointerIds.hasBit(pointerId)) {
3048 if (pointerIds.count() == 1) {
3049 // The first/last pointer went down/up.
3050 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003051 ? AMOTION_EVENT_ACTION_DOWN
3052 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 } else {
3054 // A secondary pointer went down/up.
3055 uint32_t splitPointerIndex = 0;
3056 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3057 splitPointerIndex += 1;
3058 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003059 action = maskedAction |
3060 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061 }
3062 } else {
3063 // An unrelated pointer changed.
3064 action = AMOTION_EVENT_ACTION_MOVE;
3065 }
3066 }
3067
Garfield Tan1c7bc862020-01-28 13:24:04 -08003068 int32_t newId = mIdGenerator.nextId();
3069 if (ATRACE_ENABLED()) {
3070 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3071 ") to MotionEvent(id=0x%" PRIx32 ").",
3072 originalMotionEntry.id, newId);
3073 ATRACE_NAME(message.c_str());
3074 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003075 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08003076 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3077 originalMotionEntry.source, originalMotionEntry.displayId,
3078 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003079 originalMotionEntry.actionButton, originalMotionEntry.flags,
3080 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3081 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3082 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3083 originalMotionEntry.xCursorPosition,
3084 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003085 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003087 if (originalMotionEntry.injectionState) {
3088 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089 splitMotionEntry->injectionState->refCount += 1;
3090 }
3091
3092 return splitMotionEntry;
3093}
3094
3095void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3096#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003097 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098#endif
3099
3100 bool needWake;
3101 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003102 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
Prabir Pradhan42611e02018-11-27 14:04:02 -08003104 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003105 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 needWake = enqueueInboundEventLocked(newEntry);
3107 } // release lock
3108
3109 if (needWake) {
3110 mLooper->wake();
3111 }
3112}
3113
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003114/**
3115 * If one of the meta shortcuts is detected, process them here:
3116 * Meta + Backspace -> generate BACK
3117 * Meta + Enter -> generate HOME
3118 * This will potentially overwrite keyCode and metaState.
3119 */
3120void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003122 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3123 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3124 if (keyCode == AKEYCODE_DEL) {
3125 newKeyCode = AKEYCODE_BACK;
3126 } else if (keyCode == AKEYCODE_ENTER) {
3127 newKeyCode = AKEYCODE_HOME;
3128 }
3129 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003130 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003131 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003132 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003133 keyCode = newKeyCode;
3134 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3135 }
3136 } else if (action == AKEY_EVENT_ACTION_UP) {
3137 // In order to maintain a consistent stream of up and down events, check to see if the key
3138 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3139 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003140 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003141 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003142 auto replacementIt = mReplacedKeys.find(replacement);
3143 if (replacementIt != mReplacedKeys.end()) {
3144 keyCode = replacementIt->second;
3145 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003146 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3147 }
3148 }
3149}
3150
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3152#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003153 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3154 "policyFlags=0x%x, action=0x%x, "
3155 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3156 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3157 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3158 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159#endif
3160 if (!validateKeyEvent(args->action)) {
3161 return;
3162 }
3163
3164 uint32_t policyFlags = args->policyFlags;
3165 int32_t flags = args->flags;
3166 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003167 // InputDispatcher tracks and generates key repeats on behalf of
3168 // whatever notifies it, so repeatCount should always be set to 0
3169 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3171 policyFlags |= POLICY_FLAG_VIRTUAL;
3172 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 if (policyFlags & POLICY_FLAG_FUNCTION) {
3175 metaState |= AMETA_FUNCTION_ON;
3176 }
3177
3178 policyFlags |= POLICY_FLAG_TRUSTED;
3179
Michael Wright78f24442014-08-06 15:55:28 -07003180 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003181 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003182
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003184 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003185 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3186 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187
Michael Wright2b3c3302018-03-02 17:19:13 +00003188 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003190 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3191 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 bool needWake;
3196 { // acquire lock
3197 mLock.lock();
3198
3199 if (shouldSendKeyToInputFilterLocked(args)) {
3200 mLock.unlock();
3201
3202 policyFlags |= POLICY_FLAG_FILTERED;
3203 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3204 return; // event was consumed by the filter
3205 }
3206
3207 mLock.lock();
3208 }
3209
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003210 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003211 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 args->displayId, policyFlags, args->action, flags, keyCode,
3213 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214
3215 needWake = enqueueInboundEventLocked(newEntry);
3216 mLock.unlock();
3217 } // release lock
3218
3219 if (needWake) {
3220 mLooper->wake();
3221 }
3222}
3223
3224bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3225 return mInputFilterEnabled;
3226}
3227
3228void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3229#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003230 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3231 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003232 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3233 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003234 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003235 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3236 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3237 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3238 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 for (uint32_t i = 0; i < args->pointerCount; i++) {
3240 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003241 "x=%f, y=%f, pressure=%f, size=%f, "
3242 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3243 "orientation=%f",
3244 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3245 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3246 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3247 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3248 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3249 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3250 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3251 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3252 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3253 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 }
3255#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3257 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 return;
3259 }
3260
3261 uint32_t policyFlags = args->policyFlags;
3262 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003263
3264 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003265 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003266 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3267 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003268 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270
3271 bool needWake;
3272 { // acquire lock
3273 mLock.lock();
3274
3275 if (shouldSendMotionToInputFilterLocked(args)) {
3276 mLock.unlock();
3277
3278 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003279 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3280 args->action, args->actionButton, args->flags, args->edgeFlags,
3281 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3282 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3283 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3284 args->downTime, args->eventTime, args->pointerCount,
3285 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286
3287 policyFlags |= POLICY_FLAG_FILTERED;
3288 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3289 return; // event was consumed by the filter
3290 }
3291
3292 mLock.lock();
3293 }
3294
3295 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003296 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003297 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003298 args->displayId, policyFlags, args->action, args->actionButton,
3299 args->flags, args->metaState, args->buttonState,
3300 args->classification, args->edgeFlags, args->xPrecision,
3301 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3302 args->downTime, args->pointerCount, args->pointerProperties,
3303 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304
3305 needWake = enqueueInboundEventLocked(newEntry);
3306 mLock.unlock();
3307 } // release lock
3308
3309 if (needWake) {
3310 mLooper->wake();
3311 }
3312}
3313
3314bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003315 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316}
3317
3318void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3319#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003320 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 "switchMask=0x%08x",
3322 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323#endif
3324
3325 uint32_t policyFlags = args->policyFlags;
3326 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328}
3329
3330void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3331#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3333 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334#endif
3335
3336 bool needWake;
3337 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003338 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339
Prabir Pradhan42611e02018-11-27 14:04:02 -08003340 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003341 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 needWake = enqueueInboundEventLocked(newEntry);
3343 } // release lock
3344
3345 if (needWake) {
3346 mLooper->wake();
3347 }
3348}
3349
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3351 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003352 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353#if DEBUG_INBOUND_EVENT_DETAILS
3354 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003355 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3356 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357#endif
3358
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003359 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
3361 policyFlags |= POLICY_FLAG_INJECTED;
3362 if (hasInjectionPermission(injectorPid, injectorUid)) {
3363 policyFlags |= POLICY_FLAG_TRUSTED;
3364 }
3365
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003366 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003369 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3370 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003371 if (!validateKeyEvent(action)) {
3372 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003375 int32_t flags = incomingKey.getFlags();
3376 int32_t keyCode = incomingKey.getKeyCode();
3377 int32_t metaState = incomingKey.getMetaState();
3378 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003380 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003381 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003382 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3383 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3384 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3387 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003388 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389
3390 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3391 android::base::Timer t;
3392 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3393 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3394 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3395 std::to_string(t.duration().count()).c_str());
3396 }
3397 }
3398
3399 mLock.lock();
3400 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003401 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3402 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003403 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3404 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003405 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 injectedEntries.push(injectedEntry);
3407 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 }
3409
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003410 case AINPUT_EVENT_TYPE_MOTION: {
3411 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3412 int32_t action = motionEvent->getAction();
3413 size_t pointerCount = motionEvent->getPointerCount();
3414 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3415 int32_t actionButton = motionEvent->getActionButton();
3416 int32_t displayId = motionEvent->getDisplayId();
3417 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3418 return INPUT_EVENT_INJECTION_FAILED;
3419 }
3420
3421 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3422 nsecs_t eventTime = motionEvent->getEventTime();
3423 android::base::Timer t;
3424 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3425 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3426 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3427 std::to_string(t.duration().count()).c_str());
3428 }
3429 }
3430
3431 mLock.lock();
3432 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3433 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3434 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003435 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3436 motionEvent->getSource(), motionEvent->getDisplayId(),
3437 policyFlags, action, actionButton, motionEvent->getFlags(),
3438 motionEvent->getMetaState(), motionEvent->getButtonState(),
3439 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3440 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003441 motionEvent->getRawXCursorPosition(),
3442 motionEvent->getRawYCursorPosition(),
3443 motionEvent->getDownTime(), uint32_t(pointerCount),
3444 pointerProperties, samplePointerCoords,
3445 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 injectedEntries.push(injectedEntry);
3447 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3448 sampleEventTimes += 1;
3449 samplePointerCoords += pointerCount;
3450 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003451 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003452 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 motionEvent->getDisplayId(), policyFlags, action,
3454 actionButton, motionEvent->getFlags(),
3455 motionEvent->getMetaState(), motionEvent->getButtonState(),
3456 motionEvent->getClassification(),
3457 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3458 motionEvent->getYPrecision(),
3459 motionEvent->getRawXCursorPosition(),
3460 motionEvent->getRawYCursorPosition(),
3461 motionEvent->getDownTime(), uint32_t(pointerCount),
3462 pointerProperties, samplePointerCoords,
3463 motionEvent->getXOffset(), motionEvent->getYOffset());
3464 injectedEntries.push(nextInjectedEntry);
3465 }
3466 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003470 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003471 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 }
3473
3474 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3475 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3476 injectionState->injectionIsAsync = true;
3477 }
3478
3479 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003480 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481
3482 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003483 while (!injectedEntries.empty()) {
3484 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3485 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487
3488 mLock.unlock();
3489
3490 if (needWake) {
3491 mLooper->wake();
3492 }
3493
3494 int32_t injectionResult;
3495 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003496 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3499 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3500 } else {
3501 for (;;) {
3502 injectionResult = injectionState->injectionResult;
3503 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3504 break;
3505 }
3506
3507 nsecs_t remainingTimeout = endTime - now();
3508 if (remainingTimeout <= 0) {
3509#if DEBUG_INJECTION
3510 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512#endif
3513 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3514 break;
3515 }
3516
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003517 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
3519
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3521 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 while (injectionState->pendingForegroundDispatches != 0) {
3523#if DEBUG_INJECTION
3524 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003525 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526#endif
3527 nsecs_t remainingTimeout = endTime - now();
3528 if (remainingTimeout <= 0) {
3529#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003530 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3531 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532#endif
3533 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3534 break;
3535 }
3536
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003537 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 }
3539 }
3540 }
3541
3542 injectionState->release();
3543 } // release lock
3544
3545#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003546 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003547 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548#endif
3549
3550 return injectionResult;
3551}
3552
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003553std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003554 std::array<uint8_t, 32> calculatedHmac;
3555 std::unique_ptr<VerifiedInputEvent> result;
3556 switch (event.getType()) {
3557 case AINPUT_EVENT_TYPE_KEY: {
3558 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3559 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3560 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3561 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3562 break;
3563 }
3564 case AINPUT_EVENT_TYPE_MOTION: {
3565 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3566 VerifiedMotionEvent verifiedMotionEvent =
3567 verifiedMotionEventFromMotionEvent(motionEvent);
3568 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3569 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3570 break;
3571 }
3572 default: {
3573 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3574 return nullptr;
3575 }
3576 }
3577 if (calculatedHmac == INVALID_HMAC) {
3578 return nullptr;
3579 }
3580 if (calculatedHmac != event.getHmac()) {
3581 return nullptr;
3582 }
3583 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003584}
3585
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003587 return injectorUid == 0 ||
3588 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589}
3590
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003591void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 InjectionState* injectionState = entry->injectionState;
3593 if (injectionState) {
3594#if DEBUG_INJECTION
3595 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003596 "injectorPid=%d, injectorUid=%d",
3597 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598#endif
3599
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 // Log the outcome since the injector did not wait for the injection result.
3602 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003603 case INPUT_EVENT_INJECTION_SUCCEEDED:
3604 ALOGV("Asynchronous input event injection succeeded.");
3605 break;
3606 case INPUT_EVENT_INJECTION_FAILED:
3607 ALOGW("Asynchronous input event injection failed.");
3608 break;
3609 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3610 ALOGW("Asynchronous input event injection permission denied.");
3611 break;
3612 case INPUT_EVENT_INJECTION_TIMED_OUT:
3613 ALOGW("Asynchronous input event injection timed out.");
3614 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616 }
3617
3618 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003619 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621}
3622
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003623void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 InjectionState* injectionState = entry->injectionState;
3625 if (injectionState) {
3626 injectionState->pendingForegroundDispatches += 1;
3627 }
3628}
3629
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003630void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 InjectionState* injectionState = entry->injectionState;
3632 if (injectionState) {
3633 injectionState->pendingForegroundDispatches -= 1;
3634
3635 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003636 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638 }
3639}
3640
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003641std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3642 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003643 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003644}
3645
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003647 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003648 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003649 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3650 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003651 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003652 return windowHandle;
3653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 }
3655 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003656 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657}
3658
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003659bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003660 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003661 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3662 for (const sp<InputWindowHandle>& handle : windowHandles) {
3663 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003664 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003665 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003666 ", but it should belong to display %" PRId32,
3667 windowHandle->getName().c_str(), it.first,
3668 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003669 }
3670 return true;
3671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
3673 }
3674 return false;
3675}
3676
Robert Carr5c8a0262018-10-03 16:30:44 -07003677sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3678 size_t count = mInputChannelsByToken.count(token);
3679 if (count == 0) {
3680 return nullptr;
3681 }
3682 return mInputChannelsByToken.at(token);
3683}
3684
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003685void InputDispatcher::updateWindowHandlesForDisplayLocked(
3686 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3687 if (inputWindowHandles.empty()) {
3688 // Remove all handles on a display if there are no windows left.
3689 mWindowHandlesByDisplay.erase(displayId);
3690 return;
3691 }
3692
3693 // Since we compare the pointer of input window handles across window updates, we need
3694 // to make sure the handle object for the same window stays unchanged across updates.
3695 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003696 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003697 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003698 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003699 }
3700
3701 std::vector<sp<InputWindowHandle>> newHandles;
3702 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3703 if (!handle->updateInfo()) {
3704 // handle no longer valid
3705 continue;
3706 }
3707
3708 const InputWindowInfo* info = handle->getInfo();
3709 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3710 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3711 const bool noInputChannel =
3712 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3713 const bool canReceiveInput =
3714 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3715 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3716 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003717 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003718 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003719 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003720 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003721 }
3722
3723 if (info->displayId != displayId) {
3724 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3725 handle->getName().c_str(), displayId, info->displayId);
3726 continue;
3727 }
3728
Robert Carredd13602020-04-13 17:24:34 -07003729 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3730 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003731 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003732 oldHandle->updateFrom(handle);
3733 newHandles.push_back(oldHandle);
3734 } else {
3735 newHandles.push_back(handle);
3736 }
3737 }
3738
3739 // Insert or replace
3740 mWindowHandlesByDisplay[displayId] = newHandles;
3741}
3742
Arthur Hung72d8dc32020-03-28 00:48:39 +00003743void InputDispatcher::setInputWindows(
3744 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3745 { // acquire lock
3746 std::scoped_lock _l(mLock);
3747 for (auto const& i : handlesPerDisplay) {
3748 setInputWindowsLocked(i.second, i.first);
3749 }
3750 }
3751 // Wake up poll loop since it may need to make new input dispatching choices.
3752 mLooper->wake();
3753}
3754
Arthur Hungb92218b2018-08-14 12:00:21 +08003755/**
3756 * Called from InputManagerService, update window handle list by displayId that can receive input.
3757 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3758 * If set an empty list, remove all handles from the specific display.
3759 * For focused handle, check if need to change and send a cancel event to previous one.
3760 * For removed handle, check if need to send a cancel event if already in touch.
3761 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003762void InputDispatcher::setInputWindowsLocked(
3763 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003764 if (DEBUG_FOCUS) {
3765 std::string windowList;
3766 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3767 windowList += iwh->getName() + " ";
3768 }
3769 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771
Arthur Hung72d8dc32020-03-28 00:48:39 +00003772 // Copy old handles for release if they are no longer present.
3773 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774
Arthur Hung72d8dc32020-03-28 00:48:39 +00003775 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003776
Arthur Hung72d8dc32020-03-28 00:48:39 +00003777 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3778 bool foundHoveredWindow = false;
3779 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3780 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3781 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3782 windowHandle->getInfo()->visible) {
3783 newFocusedWindowHandle = windowHandle;
3784 }
3785 if (windowHandle == mLastHoverWindowHandle) {
3786 foundHoveredWindow = true;
3787 }
3788 }
3789
3790 if (!foundHoveredWindow) {
3791 mLastHoverWindowHandle = nullptr;
3792 }
3793
3794 sp<InputWindowHandle> oldFocusedWindowHandle =
3795 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3796
3797 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3798 if (oldFocusedWindowHandle != nullptr) {
3799 if (DEBUG_FOCUS) {
3800 ALOGD("Focus left window: %s in display %" PRId32,
3801 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003802 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003803 sp<InputChannel> focusedInputChannel =
3804 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3805 if (focusedInputChannel != nullptr) {
3806 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3807 "focus left window");
3808 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3809 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003810 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003811 mFocusedWindowHandlesByDisplay.erase(displayId);
3812 }
3813 if (newFocusedWindowHandle != nullptr) {
3814 if (DEBUG_FOCUS) {
3815 ALOGD("Focus entered window: %s in display %" PRId32,
3816 newFocusedWindowHandle->getName().c_str(), displayId);
3817 }
3818 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3819 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
3821
Arthur Hung72d8dc32020-03-28 00:48:39 +00003822 if (mFocusedDisplayId == displayId) {
3823 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003827 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3828 mTouchStatesByDisplay.find(displayId);
3829 if (stateIt != mTouchStatesByDisplay.end()) {
3830 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003831 for (size_t i = 0; i < state.windows.size();) {
3832 TouchedWindow& touchedWindow = state.windows[i];
3833 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003834 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003835 ALOGD("Touched window was removed: %s in display %" PRId32,
3836 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003837 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003838 sp<InputChannel> touchedInputChannel =
3839 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3840 if (touchedInputChannel != nullptr) {
3841 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3842 "touched window was removed");
3843 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003845 state.windows.erase(state.windows.begin() + i);
3846 } else {
3847 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003850 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003851
Arthur Hung72d8dc32020-03-28 00:48:39 +00003852 // Release information for windows that are no longer present.
3853 // This ensures that unused input channels are released promptly.
3854 // Otherwise, they might stick around until the window handle is destroyed
3855 // which might not happen until the next GC.
3856 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3857 if (!hasWindowHandleLocked(oldWindowHandle)) {
3858 if (DEBUG_FOCUS) {
3859 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003860 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003861 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003862 }
chaviw291d88a2019-02-14 10:33:58 -08003863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864}
3865
3866void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003867 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003868 if (DEBUG_FOCUS) {
3869 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3870 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Tiger Huang721e26f2018-07-24 22:26:19 +08003875 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3876 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003877
3878 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3879 inputApplicationHandle != oldFocusedApplicationHandle) {
3880 resetNoFocusedWindowTimeoutLocked();
3881 }
3882
Yi Kong9b14ac62018-07-17 13:48:38 -07003883 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003884 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003885 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003887 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003888 oldFocusedApplicationHandle.clear();
3889 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 } // release lock
3892
3893 // Wake up poll loop since it may need to make new input dispatching choices.
3894 mLooper->wake();
3895}
3896
Tiger Huang721e26f2018-07-24 22:26:19 +08003897/**
3898 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3899 * the display not specified.
3900 *
3901 * We track any unreleased events for each window. If a window loses the ability to receive the
3902 * released event, we will send a cancel event to it. So when the focused display is changed, we
3903 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3904 * display. The display-specified events won't be affected.
3905 */
3906void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003907 if (DEBUG_FOCUS) {
3908 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3909 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003910 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003911 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003912
3913 if (mFocusedDisplayId != displayId) {
3914 sp<InputWindowHandle> oldFocusedWindowHandle =
3915 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3916 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003917 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003918 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003919 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003920 CancelationOptions
3921 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3922 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003923 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003924 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3925 }
3926 }
3927 mFocusedDisplayId = displayId;
3928
3929 // Sanity check
3930 sp<InputWindowHandle> newFocusedWindowHandle =
3931 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003932 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003933
Tiger Huang721e26f2018-07-24 22:26:19 +08003934 if (newFocusedWindowHandle == nullptr) {
3935 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3936 if (!mFocusedWindowHandlesByDisplay.empty()) {
3937 ALOGE("But another display has a focused window:");
3938 for (auto& it : mFocusedWindowHandlesByDisplay) {
3939 const int32_t displayId = it.first;
3940 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3942 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003943 }
3944 }
3945 }
3946 }
3947
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003948 if (DEBUG_FOCUS) {
3949 logDispatchStateLocked();
3950 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003951 } // release lock
3952
3953 // Wake up poll loop since it may need to make new input dispatching choices.
3954 mLooper->wake();
3955}
3956
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003958 if (DEBUG_FOCUS) {
3959 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961
3962 bool changed;
3963 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003964 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
3966 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3967 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003968 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 }
3970
3971 if (mDispatchEnabled && !enabled) {
3972 resetAndDropEverythingLocked("dispatcher is being disabled");
3973 }
3974
3975 mDispatchEnabled = enabled;
3976 mDispatchFrozen = frozen;
3977 changed = true;
3978 } else {
3979 changed = false;
3980 }
3981
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003982 if (DEBUG_FOCUS) {
3983 logDispatchStateLocked();
3984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 } // release lock
3986
3987 if (changed) {
3988 // Wake up poll loop since it may need to make new input dispatching choices.
3989 mLooper->wake();
3990 }
3991}
3992
3993void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003994 if (DEBUG_FOCUS) {
3995 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997
3998 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003999 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000
4001 if (mInputFilterEnabled == enabled) {
4002 return;
4003 }
4004
4005 mInputFilterEnabled = enabled;
4006 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4007 } // release lock
4008
4009 // Wake up poll loop since there might be work to do to drop everything.
4010 mLooper->wake();
4011}
4012
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004013void InputDispatcher::setInTouchMode(bool inTouchMode) {
4014 std::scoped_lock lock(mLock);
4015 mInTouchMode = inTouchMode;
4016}
4017
chaviwfbe5d9c2018-12-26 12:23:37 -08004018bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4019 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004020 if (DEBUG_FOCUS) {
4021 ALOGD("Trivial transfer to same window.");
4022 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004023 return true;
4024 }
4025
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004027 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028
chaviwfbe5d9c2018-12-26 12:23:37 -08004029 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4030 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004031 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004032 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 return false;
4034 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004035 if (DEBUG_FOCUS) {
4036 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4037 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004040 if (DEBUG_FOCUS) {
4041 ALOGD("Cannot transfer focus because windows are on different displays.");
4042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 return false;
4044 }
4045
4046 bool found = false;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004047 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4048 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004049 for (size_t i = 0; i < state.windows.size(); i++) {
4050 const TouchedWindow& touchedWindow = state.windows[i];
4051 if (touchedWindow.windowHandle == fromWindowHandle) {
4052 int32_t oldTargetFlags = touchedWindow.targetFlags;
4053 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004055 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004057 int32_t newTargetFlags = oldTargetFlags &
4058 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4059 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004060 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061
Jeff Brownf086ddb2014-02-11 14:28:48 -08004062 found = true;
4063 goto Found;
4064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 }
4066 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004069 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004070 if (DEBUG_FOCUS) {
4071 ALOGD("Focus transfer failed because from window did not have focus.");
4072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 return false;
4074 }
4075
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004076 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4077 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004078 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004079 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080 CancelationOptions
4081 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4082 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004084 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 }
4086
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004087 if (DEBUG_FOCUS) {
4088 logDispatchStateLocked();
4089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 } // release lock
4091
4092 // Wake up poll loop since it may need to make new input dispatching choices.
4093 mLooper->wake();
4094 return true;
4095}
4096
4097void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004098 if (DEBUG_FOCUS) {
4099 ALOGD("Resetting and dropping all events (%s).", reason);
4100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101
4102 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4103 synthesizeCancelationEventsForAllConnectionsLocked(options);
4104
4105 resetKeyRepeatLocked();
4106 releasePendingEventLocked();
4107 drainInboundQueueLocked();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004108 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004110 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004111 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004113 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114}
4115
4116void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004117 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 dumpDispatchStateLocked(dump);
4119
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004120 std::istringstream stream(dump);
4121 std::string line;
4122
4123 while (std::getline(stream, line, '\n')) {
4124 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 }
4126}
4127
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004128void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004129 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4130 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4131 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004132 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
Tiger Huang721e26f2018-07-24 22:26:19 +08004134 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4135 dump += StringPrintf(INDENT "FocusedApplications:\n");
4136 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4137 const int32_t displayId = it.first;
4138 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004139 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004140 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004142 ns2ms(applicationHandle
4143 ->getDispatchingTimeout(
4144 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4145 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004148 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004150
4151 if (!mFocusedWindowHandlesByDisplay.empty()) {
4152 dump += StringPrintf(INDENT "FocusedWindows:\n");
4153 for (auto& it : mFocusedWindowHandlesByDisplay) {
4154 const int32_t displayId = it.first;
4155 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4157 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004158 }
4159 } else {
4160 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004163 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004165 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4166 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168 state.displayId, toString(state.down), toString(state.split),
4169 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004170 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004172 for (size_t i = 0; i < state.windows.size(); i++) {
4173 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174 dump += StringPrintf(INDENT4
4175 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4176 i, touchedWindow.windowHandle->getName().c_str(),
4177 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004178 }
4179 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004181 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004182 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004183 dump += INDENT3 "Portal windows:\n";
4184 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004185 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4187 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004188 }
4189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 }
4191 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
4194
Arthur Hungb92218b2018-08-14 12:00:21 +08004195 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004197 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004198 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004199 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004200 dump += INDENT2 "Windows:\n";
4201 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004202 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004203 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
Arthur Hungb92218b2018-08-14 12:00:21 +08004205 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004207 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4208 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004210 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 i, windowInfo->name.c_str(), windowInfo->displayId,
4212 windowInfo->portalToDisplayId,
4213 toString(windowInfo->paused),
4214 toString(windowInfo->hasFocus),
4215 toString(windowInfo->hasWallpaper),
4216 toString(windowInfo->visible),
4217 toString(windowInfo->canReceiveKeys),
4218 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004219 windowInfo->layoutParamsType, windowInfo->frameLeft,
4220 windowInfo->frameTop, windowInfo->frameRight,
4221 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4222 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004223 dumpRegion(dump, windowInfo->touchableRegion);
4224 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004225 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4226 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004228 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004229 }
4230 } else {
4231 dump += INDENT2 "Windows: <none>\n";
4232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 }
4234 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004235 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237
Michael Wright3dd60e22019-03-27 22:06:44 +00004238 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004240 const std::vector<Monitor>& monitors = it.second;
4241 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4242 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 }
4244 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004245 const std::vector<Monitor>& monitors = it.second;
4246 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4247 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004250 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252
4253 nsecs_t currentTime = now();
4254
4255 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004256 if (!mRecentQueue.empty()) {
4257 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4258 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004259 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004261 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
4263 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004264 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 }
4266
4267 // Dump event currently being dispatched.
4268 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004269 dump += INDENT "PendingEvent:\n";
4270 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004272 dump += StringPrintf(", age=%" PRId64 "ms\n",
4273 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 }
4277
4278 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004279 if (!mInboundQueue.empty()) {
4280 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4281 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004282 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004284 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 }
4286 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004287 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 }
4289
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004290 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004291 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004292 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4293 const KeyReplacement& replacement = pair.first;
4294 int32_t newKeyCode = pair.second;
4295 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004297 }
4298 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004299 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004300 }
4301
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004302 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004303 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004304 for (const auto& pair : mConnectionsByFd) {
4305 const sp<Connection>& connection = pair.second;
4306 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004307 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004308 pair.first, connection->getInputChannelName().c_str(),
4309 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004310 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004312 if (!connection->outboundQueue.empty()) {
4313 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4314 connection->outboundQueue.size());
4315 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 dump.append(INDENT4);
4317 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004318 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4319 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004320 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004321 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004324 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 }
4326
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004327 if (!connection->waitQueue.empty()) {
4328 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4329 connection->waitQueue.size());
4330 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004331 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004333 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004334 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004335 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004336 ns2ms(currentTime - entry->eventEntry->eventTime),
4337 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004340 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
4342 }
4343 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004344 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 }
4346
4347 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004348 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4349 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004351 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
4353
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004354 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004355 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4356 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4357 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358}
4359
Michael Wright3dd60e22019-03-27 22:06:44 +00004360void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4361 const size_t numMonitors = monitors.size();
4362 for (size_t i = 0; i < numMonitors; i++) {
4363 const Monitor& monitor = monitors[i];
4364 const sp<InputChannel>& channel = monitor.inputChannel;
4365 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4366 dump += "\n";
4367 }
4368}
4369
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004370status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004372 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373#endif
4374
4375 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004376 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004377 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004378 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 return BAD_VALUE;
4382 }
4383
Garfield Tan1c7bc862020-01-28 13:24:04 -08004384 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385
4386 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004387 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004388 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4391 } // release lock
4392
4393 // Wake the looper because some connections have changed.
4394 mLooper->wake();
4395 return OK;
4396}
4397
Michael Wright3dd60e22019-03-27 22:06:44 +00004398status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004399 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004400 { // acquire lock
4401 std::scoped_lock _l(mLock);
4402
4403 if (displayId < 0) {
4404 ALOGW("Attempted to register input monitor without a specified display.");
4405 return BAD_VALUE;
4406 }
4407
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004408 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004409 ALOGW("Attempted to register input monitor without an identifying token.");
4410 return BAD_VALUE;
4411 }
4412
Garfield Tan1c7bc862020-01-28 13:24:04 -08004413 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004414
4415 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004416 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004417 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004418
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 auto& monitorsByDisplay =
4420 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004421 monitorsByDisplay[displayId].emplace_back(inputChannel);
4422
4423 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004424 }
4425 // Wake the looper because some connections have changed.
4426 mLooper->wake();
4427 return OK;
4428}
4429
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4431#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004432 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433#endif
4434
4435 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004436 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
4438 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4439 if (status) {
4440 return status;
4441 }
4442 } // release lock
4443
4444 // Wake the poll loop because removing the connection may have changed the current
4445 // synchronization state.
4446 mLooper->wake();
4447 return OK;
4448}
4449
4450status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004451 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004452 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004453 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 return BAD_VALUE;
4457 }
4458
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004459 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004460 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004461
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 if (connection->monitor) {
4463 removeMonitorChannelLocked(inputChannel);
4464 }
4465
4466 mLooper->removeFd(inputChannel->getFd());
4467
4468 nsecs_t currentTime = now();
4469 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4470
4471 connection->status = Connection::STATUS_ZOMBIE;
4472 return OK;
4473}
4474
4475void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004476 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4477 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4478}
4479
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004480void InputDispatcher::removeMonitorChannelLocked(
4481 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004482 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004483 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004484 std::vector<Monitor>& monitors = it->second;
4485 const size_t numMonitors = monitors.size();
4486 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004487 if (monitors[i].inputChannel == inputChannel) {
4488 monitors.erase(monitors.begin() + i);
4489 break;
4490 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004491 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004492 if (monitors.empty()) {
4493 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004494 } else {
4495 ++it;
4496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 }
4498}
4499
Michael Wright3dd60e22019-03-27 22:06:44 +00004500status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4501 { // acquire lock
4502 std::scoped_lock _l(mLock);
4503 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4504
4505 if (!foundDisplayId) {
4506 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4507 return BAD_VALUE;
4508 }
4509 int32_t displayId = foundDisplayId.value();
4510
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004511 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4512 mTouchStatesByDisplay.find(displayId);
4513 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004514 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4515 return BAD_VALUE;
4516 }
4517
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004518 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004519 std::optional<int32_t> foundDeviceId;
4520 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004521 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004522 foundDeviceId = state.deviceId;
4523 }
4524 }
4525 if (!foundDeviceId || !state.down) {
4526 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004527 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004528 return BAD_VALUE;
4529 }
4530 int32_t deviceId = foundDeviceId.value();
4531
4532 // Send cancel events to all the input channels we're stealing from.
4533 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004534 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004535 options.deviceId = deviceId;
4536 options.displayId = displayId;
4537 for (const TouchedWindow& window : state.windows) {
4538 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004539 if (channel != nullptr) {
4540 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4541 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004542 }
4543 // Then clear the current touch state so we stop dispatching to them as well.
4544 state.filterNonMonitors();
4545 }
4546 return OK;
4547}
4548
Michael Wright3dd60e22019-03-27 22:06:44 +00004549std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4550 const sp<IBinder>& token) {
4551 for (const auto& it : mGestureMonitorsByDisplay) {
4552 const std::vector<Monitor>& monitors = it.second;
4553 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004554 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004555 return it.first;
4556 }
4557 }
4558 }
4559 return std::nullopt;
4560}
4561
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004562sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004563 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004564 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004565 }
4566
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004567 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004568 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004569 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004570 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 }
4572 }
Robert Carr4e670e52018-08-15 13:26:12 -07004573
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004574 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575}
4576
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004577void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004578 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004579 removeByValue(mConnectionsByFd, connection);
4580}
4581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004582void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4583 const sp<Connection>& connection, uint32_t seq,
4584 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004585 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4586 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 commandEntry->connection = connection;
4588 commandEntry->eventTime = currentTime;
4589 commandEntry->seq = seq;
4590 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004591 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592}
4593
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004594void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4595 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004597 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004599 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4600 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004602 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603}
4604
chaviw0c06c6e2019-01-09 13:27:07 -08004605void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004607 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4608 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004609 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4610 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004611 commandEntry->oldToken = oldToken;
4612 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004613 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004614}
4615
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004616void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4617 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4618 // is already healthy again. Don't raise ANR in this situation
4619 if (connection->waitQueue.empty()) {
4620 ALOGI("Not raising ANR because the connection %s has recovered",
4621 connection->inputChannel->getName().c_str());
4622 return;
4623 }
4624 /**
4625 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4626 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4627 * has changed. This could cause newer entries to time out before the already dispatched
4628 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4629 * processes the events linearly. So providing information about the oldest entry seems to be
4630 * most useful.
4631 */
4632 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4633 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4634 std::string reason =
4635 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4636 connection->inputChannel->getName().c_str(),
4637 ns2ms(currentWait),
4638 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004640 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4641 reason);
4642
4643 std::unique_ptr<CommandEntry> commandEntry =
4644 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4645 commandEntry->inputApplicationHandle = nullptr;
4646 commandEntry->inputChannel = connection->inputChannel;
4647 commandEntry->reason = std::move(reason);
4648 postCommandLocked(std::move(commandEntry));
4649}
4650
4651void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4652 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4653 application->getName().c_str());
4654
4655 updateLastAnrStateLocked(application, reason);
4656
4657 std::unique_ptr<CommandEntry> commandEntry =
4658 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4659 commandEntry->inputApplicationHandle = application;
4660 commandEntry->inputChannel = nullptr;
4661 commandEntry->reason = std::move(reason);
4662 postCommandLocked(std::move(commandEntry));
4663}
4664
4665void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4666 const std::string& reason) {
4667 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4668 updateLastAnrStateLocked(windowLabel, reason);
4669}
4670
4671void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4672 const std::string& reason) {
4673 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4674 updateLastAnrStateLocked(windowLabel, reason);
4675}
4676
4677void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4678 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004680 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 struct tm tm;
4682 localtime_r(&t, &tm);
4683 char timestr[64];
4684 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004685 mLastAnrState.clear();
4686 mLastAnrState += INDENT "ANR:\n";
4687 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004688 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4689 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004690 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691}
4692
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004693void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 mLock.unlock();
4695
4696 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4697
4698 mLock.lock();
4699}
4700
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004701void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 sp<Connection> connection = commandEntry->connection;
4703
4704 if (connection->status != Connection::STATUS_ZOMBIE) {
4705 mLock.unlock();
4706
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004707 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708
4709 mLock.lock();
4710 }
4711}
4712
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004714 sp<IBinder> oldToken = commandEntry->oldToken;
4715 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004716 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004717 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004718 mLock.lock();
4719}
4720
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004721void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004722 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004723 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 mLock.unlock();
4725
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004726 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004727 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728
4729 mLock.lock();
4730
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004731 if (timeoutExtension > 0) {
4732 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4733 } else {
4734 // stop waking up for events in this connection, it is already not responding
4735 sp<Connection> connection = getConnectionLocked(token);
4736 if (connection == nullptr) {
4737 return;
4738 }
4739 cancelEventsForAnrLocked(connection);
4740 }
4741}
4742
4743void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4744 const sp<IBinder>& connectionToken,
4745 nsecs_t timeoutExtension) {
4746 sp<Connection> connection = getConnectionLocked(connectionToken);
4747 if (connection == nullptr) {
4748 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4749 // Maybe ANR happened because there's no focused window?
4750 mNoFocusedWindowTimeoutTime = now() + timeoutExtension;
4751 mAwaitedFocusedApplication = application;
4752 } else {
4753 // It's also possible that the connection already disappeared. No action necessary.
4754 }
4755 return;
4756 }
4757
4758 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
4759 connection->inputChannel->getName().c_str(), ns2ms(timeoutExtension));
4760
4761 connection->responsive = true;
4762 const nsecs_t newTimeout = now() + timeoutExtension;
4763 for (DispatchEntry* entry : connection->waitQueue) {
4764 if (newTimeout >= entry->timeoutTime) {
4765 // Already removed old entries when connection was marked unresponsive
4766 entry->timeoutTime = newTimeout;
4767 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4768 }
4769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770}
4771
4772void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4773 CommandEntry* commandEntry) {
4774 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004775 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776
4777 mLock.unlock();
4778
Michael Wright2b3c3302018-03-02 17:19:13 +00004779 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004780 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004781 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004782 : nullptr;
4783 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004784 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4785 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004786 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788
4789 mLock.lock();
4790
4791 if (delay < 0) {
4792 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4793 } else if (!delay) {
4794 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4795 } else {
4796 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4797 entry->interceptKeyWakeupTime = now() + delay;
4798 }
4799 entry->release();
4800}
4801
chaviwfd6d3512019-03-25 13:23:49 -07004802void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4803 mLock.unlock();
4804 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4805 mLock.lock();
4806}
4807
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004808/**
4809 * Connection is responsive if it has no events in the waitQueue that are older than the
4810 * current time.
4811 */
4812static bool isConnectionResponsive(const Connection& connection) {
4813 const nsecs_t currentTime = now();
4814 for (const DispatchEntry* entry : connection.waitQueue) {
4815 if (entry->timeoutTime < currentTime) {
4816 return false;
4817 }
4818 }
4819 return true;
4820}
4821
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004824 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004826 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827
4828 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004829 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004830 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004831 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004833 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004834 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004835 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004836 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4837 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004838 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004839 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004840
4841 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004842 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004843 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4844 restartEvent =
4845 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004846 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004847 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4848 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4849 handled);
4850 } else {
4851 restartEvent = false;
4852 }
4853
4854 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004855 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004856 // contents of the wait queue to have been drained, so we need to double-check
4857 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004858 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4859 if (dispatchEntryIt != connection->waitQueue.end()) {
4860 dispatchEntry = *dispatchEntryIt;
4861 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004862 mAnrTracker.erase(dispatchEntry->timeoutTime,
4863 connection->inputChannel->getConnectionToken());
4864 if (!connection->responsive) {
4865 connection->responsive = isConnectionResponsive(*connection);
4866 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004867 traceWaitQueueLength(connection);
4868 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004869 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004870 traceOutboundQueueLength(connection);
4871 } else {
4872 releaseDispatchEntry(dispatchEntry);
4873 }
4874 }
4875
4876 // Start the next dispatch cycle for this connection.
4877 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878}
4879
4880bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004881 DispatchEntry* dispatchEntry,
4882 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004883 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004884 if (!handled) {
4885 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004886 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004887 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004888 return false;
4889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004891 // Get the fallback key state.
4892 // Clear it out after dispatching the UP.
4893 int32_t originalKeyCode = keyEntry->keyCode;
4894 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4895 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4896 connection->inputState.removeFallbackKey(originalKeyCode);
4897 }
4898
4899 if (handled || !dispatchEntry->hasForegroundTarget()) {
4900 // If the application handles the original key for which we previously
4901 // generated a fallback or if the window is not a foreground window,
4902 // then cancel the associated fallback key, if any.
4903 if (fallbackKeyCode != -1) {
4904 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004906 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004907 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4908 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4909 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004911 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004912 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913
4914 mLock.unlock();
4915
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004916 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004917 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918
4919 mLock.lock();
4920
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004921 // Cancel the fallback key.
4922 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004924 "application handled the original non-fallback key "
4925 "or is no longer a foreground target, "
4926 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 options.keyCode = fallbackKeyCode;
4928 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004930 connection->inputState.removeFallbackKey(originalKeyCode);
4931 }
4932 } else {
4933 // If the application did not handle a non-fallback key, first check
4934 // that we are in a good state to perform unhandled key event processing
4935 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004936 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004937 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004939 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004940 "since this is not an initial down. "
4941 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4942 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004944 return false;
4945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004947 // Dispatch the unhandled key to the policy.
4948#if DEBUG_OUTBOUND_EVENT_DETAILS
4949 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004950 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4951 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004952#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004953 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004954
4955 mLock.unlock();
4956
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004957 bool fallback =
4958 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4959 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004960
4961 mLock.lock();
4962
4963 if (connection->status != Connection::STATUS_NORMAL) {
4964 connection->inputState.removeFallbackKey(originalKeyCode);
4965 return false;
4966 }
4967
4968 // Latch the fallback keycode for this key on an initial down.
4969 // The fallback keycode cannot change at any other point in the lifecycle.
4970 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004972 fallbackKeyCode = event.getKeyCode();
4973 } else {
4974 fallbackKeyCode = AKEYCODE_UNKNOWN;
4975 }
4976 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4977 }
4978
4979 ALOG_ASSERT(fallbackKeyCode != -1);
4980
4981 // Cancel the fallback key if the policy decides not to send it anymore.
4982 // We will continue to dispatch the key to the policy but we will no
4983 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4985 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004986#if DEBUG_OUTBOUND_EVENT_DETAILS
4987 if (fallback) {
4988 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 "as a fallback for %d, but on the DOWN it had requested "
4990 "to send %d instead. Fallback canceled.",
4991 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004992 } else {
4993 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004994 "but on the DOWN it had requested to send %d. "
4995 "Fallback canceled.",
4996 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004997 }
4998#endif
4999
5000 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5001 "canceling fallback, policy no longer desires it");
5002 options.keyCode = fallbackKeyCode;
5003 synthesizeCancelationEventsForConnectionLocked(connection, options);
5004
5005 fallback = false;
5006 fallbackKeyCode = AKEYCODE_UNKNOWN;
5007 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005008 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005009 }
5010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011
5012#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005013 {
5014 std::string msg;
5015 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5016 connection->inputState.getFallbackKeys();
5017 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005018 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005020 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005021 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005022 }
5023#endif
5024
5025 if (fallback) {
5026 // Restart the dispatch cycle using the fallback key.
5027 keyEntry->eventTime = event.getEventTime();
5028 keyEntry->deviceId = event.getDeviceId();
5029 keyEntry->source = event.getSource();
5030 keyEntry->displayId = event.getDisplayId();
5031 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5032 keyEntry->keyCode = fallbackKeyCode;
5033 keyEntry->scanCode = event.getScanCode();
5034 keyEntry->metaState = event.getMetaState();
5035 keyEntry->repeatCount = event.getRepeatCount();
5036 keyEntry->downTime = event.getDownTime();
5037 keyEntry->syntheticRepeat = false;
5038
5039#if DEBUG_OUTBOUND_EVENT_DETAILS
5040 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5042 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005043#endif
5044 return true; // restart the event
5045 } else {
5046#if DEBUG_OUTBOUND_EVENT_DETAILS
5047 ALOGD("Unhandled key event: No fallback key.");
5048#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005049
5050 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08005051 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 }
5053 }
5054 return false;
5055}
5056
5057bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 DispatchEntry* dispatchEntry,
5059 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 return false;
5061}
5062
5063void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5064 mLock.unlock();
5065
5066 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5067
5068 mLock.lock();
5069}
5070
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005071KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5072 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08005073 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08005074 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5075 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005076 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077}
5078
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07005079void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5080 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 // TODO Write some statistics about how long we spend waiting.
5082}
5083
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005084/**
5085 * Report the touch event latency to the statsd server.
5086 * Input events are reported for statistics if:
5087 * - This is a touchscreen event
5088 * - InputFilter is not enabled
5089 * - Event is not injected or synthesized
5090 *
5091 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5092 * from getting aggregated with the "old" data.
5093 */
5094void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5095 REQUIRES(mLock) {
5096 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5097 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5098 if (!reportForStatistics) {
5099 return;
5100 }
5101
5102 if (mTouchStatistics.shouldReport()) {
5103 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5104 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5105 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5106 mTouchStatistics.reset();
5107 }
5108 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5109 mTouchStatistics.addValue(latencyMicros);
5110}
5111
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112void InputDispatcher::traceInboundQueueLengthLocked() {
5113 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005114 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 }
5116}
5117
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005118void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 if (ATRACE_ENABLED()) {
5120 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005121 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005122 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 }
5124}
5125
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005126void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 if (ATRACE_ENABLED()) {
5128 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005129 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005130 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 }
5132}
5133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005134void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005135 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005137 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 dumpDispatchStateLocked(dump);
5139
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005140 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005141 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005142 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
5144}
5145
5146void InputDispatcher::monitor() {
5147 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005148 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005150 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151}
5152
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005153/**
5154 * Wake up the dispatcher and wait until it processes all events and commands.
5155 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5156 * this method can be safely called from any thread, as long as you've ensured that
5157 * the work you are interested in completing has already been queued.
5158 */
5159bool InputDispatcher::waitForIdle() {
5160 /**
5161 * Timeout should represent the longest possible time that a device might spend processing
5162 * events and commands.
5163 */
5164 constexpr std::chrono::duration TIMEOUT = 100ms;
5165 std::unique_lock lock(mLock);
5166 mLooper->wake();
5167 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5168 return result == std::cv_status::no_timeout;
5169}
5170
Garfield Tane84e6f92019-08-29 17:28:41 -07005171} // namespace android::inputdispatcher