blob: 8dcf1e0692aa933716a28f3a29ff1567d2cb9b0d [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>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080054#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070055#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070056#include <queue>
57#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058
Michael Wright2b3c3302018-03-02 17:19:13 +000059#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080060#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070061#include <binder/Binder.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070062#include <log/log.h>
63#include <powermanager/PowerManager.h>
64#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
66#define INDENT " "
67#define INDENT2 " "
68#define INDENT3 " "
69#define INDENT4 " "
70
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080071using android::base::StringPrintf;
72
Garfield Tane84e6f92019-08-29 17:28:41 -070073namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
75// Default input dispatching timeout if there is no focused application or paused window
76// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000077constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Amount of time to allow for all pending events to be processed when an app switch
80// key is on the way. This is used to preempt input dispatch and drop input events
81// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000082constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow for an event to be dispatched (measured since its eventTime)
85// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow touch events to be streamed out to a connection before requiring
89// that the first event be finished. This value extends the ANR timeout by the specified
90// amount. For example, if streaming is allowed to get ahead by one second relative to the
91// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
94// 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 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000101constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103static inline nsecs_t now() {
104 return systemTime(SYSTEM_TIME_MONOTONIC);
105}
106
107static inline const char* toString(bool value) {
108 return value ? "true" : "false";
109}
110
111static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700112 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
113 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114}
115
116static bool isValidKeyAction(int32_t action) {
117 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700118 case AKEY_EVENT_ACTION_DOWN:
119 case AKEY_EVENT_ACTION_UP:
120 return true;
121 default:
122 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123 }
124}
125
126static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128 ALOGE("Key event has invalid action code 0x%x", action);
129 return false;
130 }
131 return true;
132}
133
Michael Wright7b159c92015-05-14 14:48:03 +0100134static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 case AMOTION_EVENT_ACTION_DOWN:
137 case AMOTION_EVENT_ACTION_UP:
138 case AMOTION_EVENT_ACTION_CANCEL:
139 case AMOTION_EVENT_ACTION_MOVE:
140 case AMOTION_EVENT_ACTION_OUTSIDE:
141 case AMOTION_EVENT_ACTION_HOVER_ENTER:
142 case AMOTION_EVENT_ACTION_HOVER_MOVE:
143 case AMOTION_EVENT_ACTION_HOVER_EXIT:
144 case AMOTION_EVENT_ACTION_SCROLL:
145 return true;
146 case AMOTION_EVENT_ACTION_POINTER_DOWN:
147 case AMOTION_EVENT_ACTION_POINTER_UP: {
148 int32_t index = getMotionEventActionPointerIndex(action);
149 return index >= 0 && index < pointerCount;
150 }
151 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
152 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
153 return actionButton != 0;
154 default:
155 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156 }
157}
158
Michael Wright7b159c92015-05-14 14:48:03 +0100159static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 const PointerProperties* pointerProperties) {
161 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 ALOGE("Motion event has invalid action code 0x%x", action);
163 return false;
164 }
165 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000166 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168 return false;
169 }
170 BitSet32 pointerIdBits;
171 for (size_t i = 0; i < pointerCount; i++) {
172 int32_t id = pointerProperties[i].id;
173 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
175 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 return false;
177 }
178 if (pointerIdBits.hasBit(id)) {
179 ALOGE("Motion event has duplicate pointer id %d", id);
180 return false;
181 }
182 pointerIdBits.markBit(id);
183 }
184 return true;
185}
186
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800187static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800189 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 return;
191 }
192
193 bool first = true;
194 Region::const_iterator cur = region.begin();
195 Region::const_iterator const tail = region.end();
196 while (cur != tail) {
197 if (first) {
198 first = false;
199 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 cur++;
204 }
205}
206
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700207/**
208 * Find the entry in std::unordered_map by key, and return it.
209 * If the entry is not found, return a default constructed entry.
210 *
211 * Useful when the entries are vectors, since an empty vector will be returned
212 * if the entry is not found.
213 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
214 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700215template <typename K, typename V>
216static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700217 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700218 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800219}
220
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700221/**
222 * Find the entry in std::unordered_map by value, and remove it.
223 * If more than one entry has the same value, then all matching
224 * key-value pairs will be removed.
225 *
226 * Return true if at least one value has been removed.
227 */
228template <typename K, typename V>
229static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
230 bool removed = false;
231 for (auto it = map.begin(); it != map.end();) {
232 if (it->second == value) {
233 it = map.erase(it);
234 removed = true;
235 } else {
236 it++;
237 }
238 }
239 return removed;
240}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241
242// --- InputDispatcher ---
243
Garfield Tan00f511d2019-06-12 16:55:40 -0700244InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
245 : mPolicy(policy),
246 mPendingEvent(nullptr),
247 mLastDropReason(DROP_REASON_NOT_DROPPED),
248 mAppSwitchSawKeyDown(false),
249 mAppSwitchDueTime(LONG_LONG_MAX),
250 mNextUnblockedEvent(nullptr),
251 mDispatchEnabled(false),
252 mDispatchFrozen(false),
253 mInputFilterEnabled(false),
254 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
255 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800257 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258
Yi Kong9b14ac62018-07-17 13:48:38 -0700259 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260
261 policy->getDispatcherConfiguration(&mConfig);
262}
263
264InputDispatcher::~InputDispatcher() {
265 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800266 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267
268 resetKeyRepeatLocked();
269 releasePendingEventLocked();
270 drainInboundQueueLocked();
271 }
272
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700273 while (!mConnectionsByFd.empty()) {
274 sp<Connection> connection = mConnectionsByFd.begin()->second;
275 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276 }
277}
278
279void InputDispatcher::dispatchOnce() {
280 nsecs_t nextWakeupTime = LONG_LONG_MAX;
281 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800282 std::scoped_lock _l(mLock);
283 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284
285 // Run a dispatch loop if there are no pending commands.
286 // The dispatch loop might enqueue commands to run afterwards.
287 if (!haveCommandsLocked()) {
288 dispatchOnceInnerLocked(&nextWakeupTime);
289 }
290
291 // Run all pending commands if there are any.
292 // If any commands were run then force the next poll to wake up immediately.
293 if (runCommandsLockedInterruptible()) {
294 nextWakeupTime = LONG_LONG_MIN;
295 }
296 } // release lock
297
298 // Wait for callback or timeout or wake. (make sure we round up, not down)
299 nsecs_t currentTime = now();
300 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
301 mLooper->pollOnce(timeoutMillis);
302}
303
304void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
305 nsecs_t currentTime = now();
306
Jeff Browndc5992e2014-04-11 01:27:26 -0700307 // Reset the key repeat timer whenever normal dispatch is suspended while the
308 // device is in a non-interactive state. This is to ensure that we abort a key
309 // repeat if the device is just coming out of sleep.
310 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800311 resetKeyRepeatLocked();
312 }
313
314 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
315 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100316 if (DEBUG_FOCUS) {
317 ALOGD("Dispatch frozen. Waiting some more.");
318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800319 return;
320 }
321
322 // Optimize latency of app switches.
323 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
324 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
325 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
326 if (mAppSwitchDueTime < *nextWakeupTime) {
327 *nextWakeupTime = mAppSwitchDueTime;
328 }
329
330 // Ready to start a new event.
331 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700332 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700333 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334 if (isAppSwitchDue) {
335 // The inbound queue is empty so the app switch key we were waiting
336 // for will never arrive. Stop waiting for it.
337 resetPendingAppSwitchLocked(false);
338 isAppSwitchDue = false;
339 }
340
341 // Synthesize a key repeat if appropriate.
342 if (mKeyRepeatState.lastKeyEntry) {
343 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
344 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
345 } else {
346 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
347 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
348 }
349 }
350 }
351
352 // Nothing to do if there is no pending event.
353 if (!mPendingEvent) {
354 return;
355 }
356 } else {
357 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700358 mPendingEvent = mInboundQueue.front();
359 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360 traceInboundQueueLengthLocked();
361 }
362
363 // Poke user activity for this event.
364 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
365 pokeUserActivityLocked(mPendingEvent);
366 }
367
368 // Get ready to dispatch the event.
369 resetANRTimeoutsLocked();
370 }
371
372 // Now we have an event to dispatch.
373 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700374 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375 bool done = false;
376 DropReason dropReason = DROP_REASON_NOT_DROPPED;
377 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
378 dropReason = DROP_REASON_POLICY;
379 } else if (!mDispatchEnabled) {
380 dropReason = DROP_REASON_DISABLED;
381 }
382
383 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700384 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 }
386
387 switch (mPendingEvent->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700388 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
389 ConfigurationChangedEntry* typedEntry =
390 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
391 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
392 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
393 break;
394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700396 case EventEntry::TYPE_DEVICE_RESET: {
397 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
398 done = dispatchDeviceResetLocked(currentTime, typedEntry);
399 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
400 break;
401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800402
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700403 case EventEntry::TYPE_KEY: {
404 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
405 if (isAppSwitchDue) {
406 if (isAppSwitchKeyEvent(typedEntry)) {
407 resetPendingAppSwitchLocked(true);
408 isAppSwitchDue = false;
409 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
410 dropReason = DROP_REASON_APP_SWITCH;
411 }
412 }
413 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
414 dropReason = DROP_REASON_STALE;
415 }
416 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
417 dropReason = DROP_REASON_BLOCKED;
418 }
419 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
420 break;
421 }
422
423 case EventEntry::TYPE_MOTION: {
424 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
425 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 dropReason = DROP_REASON_APP_SWITCH;
427 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700428 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
435 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700438 default:
439 ALOG_ASSERT(false);
440 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 }
442
443 if (done) {
444 if (dropReason != DROP_REASON_NOT_DROPPED) {
445 dropInboundEventLocked(mPendingEvent, dropReason);
446 }
Michael Wright3a981722015-06-10 15:26:13 +0100447 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
449 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700450 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451 }
452}
453
454bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700455 bool needWake = mInboundQueue.empty();
456 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457 traceInboundQueueLengthLocked();
458
459 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700460 case EventEntry::TYPE_KEY: {
461 // Optimize app switch latency.
462 // If the application takes too long to catch up then we drop all events preceding
463 // the app switch key.
464 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
465 if (isAppSwitchKeyEvent(keyEntry)) {
466 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
467 mAppSwitchSawKeyDown = true;
468 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
469 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700471 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700473 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
474 mAppSwitchSawKeyDown = false;
475 needWake = true;
476 }
477 }
478 }
479 break;
480 }
481
482 case EventEntry::TYPE_MOTION: {
483 // Optimize case where the current application is unresponsive and the user
484 // decides to touch a window in a different application.
485 // If the application takes too long to catch up then we drop all events preceding
486 // the touch into the other window.
487 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
488 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
489 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
490 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
491 mInputTargetWaitApplicationToken != nullptr) {
492 int32_t displayId = motionEntry->displayId;
493 int32_t x =
494 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
495 int32_t y =
496 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
497 sp<InputWindowHandle> touchedWindowHandle =
498 findTouchedWindowAtLocked(displayId, x, y);
499 if (touchedWindowHandle != nullptr &&
500 touchedWindowHandle->getApplicationToken() !=
501 mInputTargetWaitApplicationToken) {
502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 needWake = true;
506 }
507 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700508 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700517 mRecentQueue.push_back(entry);
518 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.front()->release();
520 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 }
522}
523
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700524sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
525 int32_t y, bool addOutsideTargets,
526 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800528 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
529 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 const InputWindowInfo* windowInfo = windowHandle->getInfo();
531 if (windowInfo->displayId == displayId) {
532 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 if (windowInfo->visible) {
535 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700536 bool isTouchModal = (flags &
537 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
538 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800540 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700541 if (portalToDisplayId != ADISPLAY_ID_NONE &&
542 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800543 if (addPortalWindows) {
544 // For the monitoring channels of the display.
545 mTempTouchState.addPortalWindow(windowHandle);
546 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700547 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
548 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 // Found window.
551 return windowHandle;
552 }
553 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800554
555 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700556 mTempTouchState.addOrUpdateWindow(windowHandle,
557 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
558 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 }
562 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700563 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564}
565
Garfield Tane84e6f92019-08-29 17:28:41 -0700566std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000567 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
568 std::vector<TouchedMonitor> touchedMonitors;
569
570 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
571 addGestureMonitors(monitors, touchedMonitors);
572 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
573 const InputWindowInfo* windowInfo = portalWindow->getInfo();
574 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700575 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
576 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000577 }
578 return touchedMonitors;
579}
580
581void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700582 std::vector<TouchedMonitor>& outTouchedMonitors,
583 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000584 if (monitors.empty()) {
585 return;
586 }
587 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
588 for (const Monitor& monitor : monitors) {
589 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
590 }
591}
592
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
594 const char* reason;
595 switch (dropReason) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700596 case DROP_REASON_POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700598 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 reason = "inbound event was dropped because the policy consumed it";
601 break;
602 case DROP_REASON_DISABLED:
603 if (mLastDropReason != DROP_REASON_DISABLED) {
604 ALOGI("Dropped event because input dispatch is disabled.");
605 }
606 reason = "inbound event was dropped because input dispatch is disabled";
607 break;
608 case DROP_REASON_APP_SWITCH:
609 ALOGI("Dropped event because of pending overdue app switch.");
610 reason = "inbound event was dropped because of pending overdue app switch";
611 break;
612 case DROP_REASON_BLOCKED:
613 ALOGI("Dropped event because the current application is not responding and the user "
614 "has started interacting with a different application.");
615 reason = "inbound event was dropped because the current application is not responding "
616 "and the user has started interacting with a different application";
617 break;
618 case DROP_REASON_STALE:
619 ALOGI("Dropped event because it is stale.");
620 reason = "inbound event was dropped because it is stale";
621 break;
622 default:
623 ALOG_ASSERT(false);
624 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 }
626
627 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700628 case EventEntry::TYPE_KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
630 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700633 case EventEntry::TYPE_MOTION: {
634 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
635 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
636 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
637 synthesizeCancelationEventsForAllConnectionsLocked(options);
638 } else {
639 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
640 synthesizeCancelationEventsForAllConnectionsLocked(options);
641 }
642 break;
643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 }
645}
646
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800647static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
649 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650}
651
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800652bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700653 return !(keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry->keyCode) &&
654 (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) &&
655 (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656}
657
658bool InputDispatcher::isAppSwitchPendingLocked() {
659 return mAppSwitchDueTime != LONG_LONG_MAX;
660}
661
662void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
663 mAppSwitchDueTime = LONG_LONG_MAX;
664
665#if DEBUG_APP_SWITCH
666 if (handled) {
667 ALOGD("App switch has arrived.");
668 } else {
669 ALOGD("App switch was abandoned.");
670 }
671#endif
672}
673
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800674bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
676}
677
678bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700679 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680}
681
682bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700683 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 return false;
685 }
686
687 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700688 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700689 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700691 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692
693 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700694 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 return true;
696}
697
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700698void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
699 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700}
701
702void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700703 while (!mInboundQueue.empty()) {
704 EventEntry* entry = mInboundQueue.front();
705 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 releaseInboundEventLocked(entry);
707 }
708 traceInboundQueueLengthLocked();
709}
710
711void InputDispatcher::releasePendingEventLocked() {
712 if (mPendingEvent) {
713 resetANRTimeoutsLocked();
714 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700715 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717}
718
719void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
720 InjectionState* injectionState = entry->injectionState;
721 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
722#if DEBUG_DISPATCH_CYCLE
723 ALOGD("Injected inbound event was dropped.");
724#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800725 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 }
727 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700728 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 }
730 addRecentEventLocked(entry);
731 entry->release();
732}
733
734void InputDispatcher::resetKeyRepeatLocked() {
735 if (mKeyRepeatState.lastKeyEntry) {
736 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700737 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 }
739}
740
Garfield Tane84e6f92019-08-29 17:28:41 -0700741KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
743
744 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700745 uint32_t policyFlags = entry->policyFlags &
746 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 if (entry->refCount == 1) {
748 entry->recycle();
749 entry->eventTime = currentTime;
750 entry->policyFlags = policyFlags;
751 entry->repeatCount += 1;
752 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 KeyEntry* newEntry =
754 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
755 entry->source, entry->displayId, policyFlags, entry->action,
756 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
757 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758
759 mKeyRepeatState.lastKeyEntry = newEntry;
760 entry->release();
761
762 entry = newEntry;
763 }
764 entry->syntheticRepeat = true;
765
766 // Increment reference count since we keep a reference to the event in
767 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
768 entry->refCount += 1;
769
770 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
771 return entry;
772}
773
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
775 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700777 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778#endif
779
780 // Reset key repeating in case a keyboard device was added or removed or something.
781 resetKeyRepeatLocked();
782
783 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700784 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
785 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700787 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 return true;
789}
790
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700791bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700793 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795#endif
796
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 options.deviceId = entry->deviceId;
799 synthesizeCancelationEventsForAllConnectionsLocked(options);
800 return true;
801}
802
803bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 if (!entry->dispatchInProgress) {
807 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
808 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
809 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
810 if (mKeyRepeatState.lastKeyEntry &&
811 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 // We have seen two identical key downs in a row which indicates that the device
813 // driver is automatically generating key repeats itself. We take note of the
814 // repeat here, but we disable our own next key repeat timer since it is clear that
815 // we will not need to synthesize key repeats ourselves.
816 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
817 resetKeyRepeatLocked();
818 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
819 } else {
820 // Not a repeat. Save key down state in case we do see a repeat later.
821 resetKeyRepeatLocked();
822 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
823 }
824 mKeyRepeatState.lastKeyEntry = entry;
825 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 resetKeyRepeatLocked();
828 }
829
830 if (entry->repeatCount == 1) {
831 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
832 } else {
833 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
834 }
835
836 entry->dispatchInProgress = true;
837
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800838 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
840
841 // Handle case where the policy asked us to try again later last time.
842 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
843 if (currentTime < entry->interceptKeyWakeupTime) {
844 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
845 *nextWakeupTime = entry->interceptKeyWakeupTime;
846 }
847 return false; // wait until next wakeup
848 }
849 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
850 entry->interceptKeyWakeupTime = 0;
851 }
852
853 // Give the policy a chance to intercept the key.
854 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
855 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700856 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700857 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800858 sp<InputWindowHandle> focusedWindowHandle =
859 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
860 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
863 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700864 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 entry->refCount += 1;
866 return false; // wait for the command to run
867 } else {
868 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
869 }
870 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
871 if (*dropReason == DROP_REASON_NOT_DROPPED) {
872 *dropReason = DROP_REASON_POLICY;
873 }
874 }
875
876 // Clean up if dropping the event.
877 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 setInjectionResult(entry,
879 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
880 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800881 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 return true;
883 }
884
885 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800886 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 int32_t injectionResult =
888 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
890 return false;
891 }
892
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800893 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
895 return true;
896 }
897
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800898 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000899 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
901 // Dispatch the key.
902 dispatchEventLocked(currentTime, entry, inputTargets);
903 return true;
904}
905
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800906void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100908 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
910 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
911 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
912 entry->policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode,
913 entry->metaState, entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914#endif
915}
916
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700917bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
918 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000919 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 entry->dispatchInProgress = true;
923
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800924 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
926
927 // Clean up if dropping the event.
928 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 setInjectionResult(entry,
930 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
931 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 return true;
933 }
934
935 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
936
937 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800938 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939
940 bool conflictingPointerActions = false;
941 int32_t injectionResult;
942 if (isPointerEvent) {
943 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 injectionResult =
945 findTouchedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime,
946 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 } else {
948 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 injectionResult =
950 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 }
952 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
953 return false;
954 }
955
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800956 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100958 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 CancelationOptions::Mode mode(isPointerEvent
960 ? CancelationOptions::CANCEL_POINTER_EVENTS
961 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100962 CancelationOptions options(mode, "input event injection failed");
963 synthesizeCancelationEventsForMonitorsLocked(options);
964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 return true;
966 }
967
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800968 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000969 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800971 if (isPointerEvent) {
972 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
973 if (stateIndex >= 0) {
974 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800975 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800976 // The event has gone through these portal windows, so we add monitoring targets of
977 // the corresponding displays as well.
978 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800979 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000980 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800982 }
983 }
984 }
985 }
986
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 // Dispatch the motion.
988 if (conflictingPointerActions) {
989 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 synthesizeCancelationEventsForAllConnectionsLocked(options);
992 }
993 dispatchEventLocked(currentTime, entry, inputTargets);
994 return true;
995}
996
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800997void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800999 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 ", policyFlags=0x%x, "
1001 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1002 "metaState=0x%x, buttonState=0x%x,"
1003 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1004 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
1005 entry->policyFlags, entry->action, entry->actionButton, entry->flags, entry->metaState,
1006 entry->buttonState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
1007 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008
1009 for (uint32_t i = 0; i < entry->pointerCount; i++) {
1010 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 "x=%f, y=%f, pressure=%f, size=%f, "
1012 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1013 "orientation=%f",
1014 i, entry->pointerProperties[i].id, entry->pointerProperties[i].toolType,
1015 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1016 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1017 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1018 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1019 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1020 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1021 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1022 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1023 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
1025#endif
1026}
1027
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1029 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001030 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031#if DEBUG_DISPATCH_CYCLE
1032 ALOGD("dispatchEventToCurrentInputTargets");
1033#endif
1034
1035 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1036
1037 pokeUserActivityLocked(eventEntry);
1038
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001039 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001040 sp<Connection> connection = getConnectionLocked(inputTarget.inputChannel);
1041 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1043 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001044 if (DEBUG_FOCUS) {
1045 ALOGD("Dropping event delivery to target with channel '%s' because it "
1046 "is no longer registered with the input dispatcher.",
1047 inputTarget.inputChannel->getName().c_str());
1048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
1050 }
1051}
1052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053int32_t InputDispatcher::handleTargetsNotReadyLocked(
1054 nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001057 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001059 if (DEBUG_FOCUS) {
1060 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1063 mInputTargetWaitStartTime = currentTime;
1064 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1065 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001066 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068 } else {
1069 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001070 if (DEBUG_FOCUS) {
1071 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1072 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001075 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001077 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 timeout =
1079 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 } else {
1081 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1082 }
1083
1084 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1085 mInputTargetWaitStartTime = currentTime;
1086 mInputTargetWaitTimeoutTime = currentTime + timeout;
1087 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001088 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089
Yi Kong9b14ac62018-07-17 13:48:38 -07001090 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001091 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
Robert Carr740167f2018-10-11 19:03:41 -07001093 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1094 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096 }
1097 }
1098
1099 if (mInputTargetWaitTimeoutExpired) {
1100 return INPUT_EVENT_INJECTION_TIMED_OUT;
1101 }
1102
1103 if (currentTime >= mInputTargetWaitTimeoutTime) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 onANRLocked(currentTime, applicationHandle, windowHandle, entry->eventTime,
1105 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106
1107 // Force poll loop to wake up immediately on next iteration once we get the
1108 // ANR response back from the policy.
1109 *nextWakeupTime = LONG_LONG_MIN;
1110 return INPUT_EVENT_INJECTION_PENDING;
1111 } else {
1112 // Force poll loop to wake up when timeout is due.
1113 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1114 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1115 }
1116 return INPUT_EVENT_INJECTION_PENDING;
1117 }
1118}
1119
Robert Carr803535b2018-08-02 16:38:15 -07001120void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1121 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1122 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1123 state.removeWindowByToken(token);
1124 }
1125}
1126
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
1128 nsecs_t newTimeout, const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 if (newTimeout > 0) {
1130 // Extend the timeout.
1131 mInputTargetWaitTimeoutTime = now() + newTimeout;
1132 } else {
1133 // Give up.
1134 mInputTargetWaitTimeoutExpired = true;
1135
1136 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001137 sp<Connection> connection = getConnectionLocked(inputChannel);
1138 if (connection != nullptr) {
1139 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001141 if (token != nullptr) {
1142 removeWindowByTokenLocked(token);
1143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001145 if (connection->status == Connection::STATUS_NORMAL) {
1146 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1147 "application not responding");
1148 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150 }
1151 }
1152}
1153
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1156 return currentTime - mInputTargetWaitStartTime;
1157 }
1158 return 0;
1159}
1160
1161void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001162 if (DEBUG_FOCUS) {
1163 ALOGD("Resetting ANR timeouts.");
1164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165
1166 // Reset input target wait timeout.
1167 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001168 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169}
1170
Tiger Huang721e26f2018-07-24 22:26:19 +08001171/**
1172 * Get the display id that the given event should go to. If this event specifies a valid display id,
1173 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1174 * Focused display is the display that the user most recently interacted with.
1175 */
1176int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1177 int32_t displayId;
1178 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 case EventEntry::TYPE_KEY: {
1180 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1181 displayId = typedEntry->displayId;
1182 break;
1183 }
1184 case EventEntry::TYPE_MOTION: {
1185 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1186 displayId = typedEntry->displayId;
1187 break;
1188 }
1189 default: {
1190 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1191 return ADISPLAY_ID_NONE;
1192 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001193 }
1194 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1195}
1196
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001198 const EventEntry* entry,
1199 std::vector<InputTarget>& inputTargets,
1200 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001202 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203
Tiger Huang721e26f2018-07-24 22:26:19 +08001204 int32_t displayId = getTargetDisplayId(entry);
1205 sp<InputWindowHandle> focusedWindowHandle =
1206 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1207 sp<InputApplicationHandle> focusedApplicationHandle =
1208 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1209
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 // If there is no currently focused window and no focused application
1211 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001212 if (focusedWindowHandle == nullptr) {
1213 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 injectionResult =
1215 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1216 nullptr, nextWakeupTime,
1217 "Waiting because no window has focus but there is "
1218 "a focused application that may eventually add a "
1219 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 goto Unresponsive;
1221 }
1222
Arthur Hung3b413f22018-10-26 18:05:34 +08001223 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001224 "%" PRId32 ".",
1225 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1227 goto Failed;
1228 }
1229
1230 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001231 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1233 goto Failed;
1234 }
1235
Jeff Brownffb49772014-10-10 19:01:34 -07001236 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001238 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 injectionResult =
1240 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1241 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 goto Unresponsive;
1243 }
1244
1245 // Success! Output targets.
1246 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001247 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001248 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1249 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250
1251 // Done.
1252Failed:
1253Unresponsive:
1254 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001255 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001256 if (DEBUG_FOCUS) {
1257 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1258 "timeSpentWaitingForApplication=%0.1fms",
1259 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 return injectionResult;
1262}
1263
1264int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 const MotionEntry* entry,
1266 std::vector<InputTarget>& inputTargets,
1267 nsecs_t* nextWakeupTime,
1268 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001269 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 enum InjectionPermission {
1271 INJECTION_PERMISSION_UNKNOWN,
1272 INJECTION_PERMISSION_GRANTED,
1273 INJECTION_PERMISSION_DENIED
1274 };
1275
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 // For security reasons, we defer updating the touch state until we are sure that
1277 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 int32_t displayId = entry->displayId;
1279 int32_t action = entry->action;
1280 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1281
1282 // Update the touch state as needed based on the properties of the touch event.
1283 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1284 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1285 sp<InputWindowHandle> newHoverWindowHandle;
1286
Jeff Brownf086ddb2014-02-11 14:28:48 -08001287 // Copy current touch state into mTempTouchState.
1288 // This state is always reset at the end of this function, so if we don't find state
1289 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001290 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001291 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1292 if (oldStateIndex >= 0) {
1293 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1294 mTempTouchState.copyFrom(*oldState);
1295 }
1296
1297 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
1299 (mTempTouchState.deviceId != entry->deviceId ||
1300 mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId);
1301 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1302 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1303 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1304 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1305 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Garfield Tan00f511d2019-06-12 16:55:40 -07001306 const bool isFromMouse = entry->source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 bool wrongDevice = false;
1308 if (newGesture) {
1309 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001310 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001311 if (DEBUG_FOCUS) {
1312 ALOGD("Dropping event because a pointer for a different device is already down "
1313 "in display %" PRId32,
1314 displayId);
1315 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001316 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1318 switchedDevice = false;
1319 wrongDevice = true;
1320 goto Failed;
1321 }
1322 mTempTouchState.reset();
1323 mTempTouchState.down = down;
1324 mTempTouchState.deviceId = entry->deviceId;
1325 mTempTouchState.source = entry->source;
1326 mTempTouchState.displayId = displayId;
1327 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001328 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001329 if (DEBUG_FOCUS) {
1330 ALOGI("Dropping move event because a pointer for a different device is already active "
1331 "in display %" PRId32,
1332 displayId);
1333 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001334 // TODO: test multiple simultaneous input streams.
1335 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1336 switchedDevice = false;
1337 wrongDevice = true;
1338 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340
1341 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1342 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1343
Garfield Tan00f511d2019-06-12 16:55:40 -07001344 int32_t x;
1345 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001347 // Always dispatch mouse events to cursor position.
1348 if (isFromMouse) {
1349 x = int32_t(entry->xCursorPosition);
1350 y = int32_t(entry->yCursorPosition);
1351 } else {
1352 x = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1353 y = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
1354 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001355 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 sp<InputWindowHandle> newTouchedWindowHandle =
1357 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1358 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001359
1360 std::vector<TouchedMonitor> newGestureMonitors = isDown
1361 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1362 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 if (newTouchedWindowHandle != nullptr &&
1366 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001367 // New window supports splitting, but we should never split mouse events.
1368 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 } else if (isSplit) {
1370 // New window does not support splitting but we have already split events.
1371 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001372 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 }
1374
1375 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001376 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 // Try to assign the pointer to the first foreground window we find, if there is one.
1378 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001379 }
1380
1381 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1382 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 "(%d, %d) in display %" PRId32 ".",
1384 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001385 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1386 goto Failed;
1387 }
1388
1389 if (newTouchedWindowHandle != nullptr) {
1390 // Set target flags.
1391 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1392 if (isSplit) {
1393 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001395 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1396 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1397 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1398 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1399 }
1400
1401 // Update hover state.
1402 if (isHoverAction) {
1403 newHoverWindowHandle = newTouchedWindowHandle;
1404 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1405 newHoverWindowHandle = mLastHoverWindowHandle;
1406 }
1407
1408 // Update the temporary touch state.
1409 BitSet32 pointerIds;
1410 if (isSplit) {
1411 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1412 pointerIds.markBit(pointerId);
1413 }
1414 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 }
1416
Michael Wright3dd60e22019-03-27 22:06:44 +00001417 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 } else {
1419 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1420
1421 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001423 if (DEBUG_FOCUS) {
1424 ALOGD("Dropping event because the pointer is not down or we previously "
1425 "dropped the pointer down event in display %" PRId32,
1426 displayId);
1427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1429 goto Failed;
1430 }
1431
1432 // Check whether touches should slip outside of the current foreground window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001433 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 &&
1434 mTempTouchState.isSlippery()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1436 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1437
1438 sp<InputWindowHandle> oldTouchedWindowHandle =
1439 mTempTouchState.getFirstForegroundWindowHandle();
1440 sp<InputWindowHandle> newTouchedWindowHandle =
1441 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001442 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1443 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001444 if (DEBUG_FOCUS) {
1445 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1446 oldTouchedWindowHandle->getName().c_str(),
1447 newTouchedWindowHandle->getName().c_str(), displayId);
1448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 // Make a slippery exit from the old window.
1450 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1452 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453
1454 // Make a slippery entrance into the new window.
1455 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1456 isSplit = true;
1457 }
1458
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001459 int32_t targetFlags =
1460 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 if (isSplit) {
1462 targetFlags |= InputTarget::FLAG_SPLIT;
1463 }
1464 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1465 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1466 }
1467
1468 BitSet32 pointerIds;
1469 if (isSplit) {
1470 pointerIds.markBit(entry->pointerProperties[0].id);
1471 }
1472 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1473 }
1474 }
1475 }
1476
1477 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1478 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001479 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480#if DEBUG_HOVER
1481 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483#endif
1484 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001485 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1486 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488
1489 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491#if DEBUG_HOVER
1492 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494#endif
1495 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1497 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 }
1499 }
1500
1501 // Check permission to inject into all touched foreground windows and ensure there
1502 // is at least one touched foreground window.
1503 {
1504 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001505 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1507 haveForegroundWindow = true;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001508 if (!checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1510 injectionPermission = INJECTION_PERMISSION_DENIED;
1511 goto Failed;
1512 }
1513 }
1514 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001515 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1516 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001517 if (DEBUG_FOCUS) {
1518 ALOGD("Dropping event because there is no touched foreground window in display "
1519 "%" PRId32 " or gesture monitor to receive it.",
1520 displayId);
1521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1523 goto Failed;
1524 }
1525
1526 // Permission granted to injection into all touched foreground windows.
1527 injectionPermission = INJECTION_PERMISSION_GRANTED;
1528 }
1529
1530 // Check whether windows listening for outside touches are owned by the same UID. If it is
1531 // set the policy flag that we will not reveal coordinate information to this window.
1532 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1533 sp<InputWindowHandle> foregroundWindowHandle =
1534 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001535 if (foregroundWindowHandle) {
1536 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1537 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1538 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1539 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1540 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1541 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001542 InputTarget::FLAG_ZERO_COORDS,
1543 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546 }
1547 }
1548 }
1549
1550 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001551 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001553 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001554 std::string reason =
1555 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1556 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001557 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1559 touchedWindow.windowHandle,
1560 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 goto Unresponsive;
1562 }
1563 }
1564 }
1565
1566 // If this is the first pointer going down and the touched window has a wallpaper
1567 // then also add the touched wallpaper windows so they are locked in for the duration
1568 // of the touch gesture.
1569 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1570 // engine only supports touch events. We would need to add a mechanism similar
1571 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1572 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1573 sp<InputWindowHandle> foregroundWindowHandle =
1574 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001575 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001576 const std::vector<sp<InputWindowHandle>> windowHandles =
1577 getWindowHandlesLocked(displayId);
1578 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001580 if (info->displayId == displayId &&
1581 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1582 mTempTouchState
1583 .addOrUpdateWindow(windowHandle,
1584 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1585 InputTarget::
1586 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1587 InputTarget::FLAG_DISPATCH_AS_IS,
1588 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 }
1590 }
1591 }
1592 }
1593
1594 // Success! Output targets.
1595 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1596
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001597 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001599 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 }
1601
Michael Wright3dd60e22019-03-27 22:06:44 +00001602 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1603 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001604 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001605 }
1606
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 // Drop the outside or hover touch windows since we will not care about them
1608 // in the next iteration.
1609 mTempTouchState.filterNonAsIsTouchWindows();
1610
1611Failed:
1612 // Check injection permission once and for all.
1613 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001614 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 injectionPermission = INJECTION_PERMISSION_GRANTED;
1616 } else {
1617 injectionPermission = INJECTION_PERMISSION_DENIED;
1618 }
1619 }
1620
1621 // Update final pieces of touch state if the injector had permission.
1622 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1623 if (!wrongDevice) {
1624 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001625 if (DEBUG_FOCUS) {
1626 ALOGD("Conflicting pointer actions: Switched to a different device.");
1627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 *outConflictingPointerActions = true;
1629 }
1630
1631 if (isHoverAction) {
1632 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001633 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001634 if (DEBUG_FOCUS) {
1635 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1636 "down.");
1637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 *outConflictingPointerActions = true;
1639 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001640 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001641 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1642 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001643 mTempTouchState.deviceId = entry->deviceId;
1644 mTempTouchState.source = entry->source;
1645 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1648 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001650 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1652 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001653 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001654 if (DEBUG_FOCUS) {
1655 ALOGD("Conflicting pointer actions: Down received while already down.");
1656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 *outConflictingPointerActions = true;
1658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1660 // One pointer went up.
1661 if (isSplit) {
1662 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1663 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1664
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001666 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1668 touchedWindow.pointerIds.clearBit(pointerId);
1669 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001670 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 continue;
1672 }
1673 }
1674 i += 1;
1675 }
1676 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001677 }
1678
1679 // Save changes unless the action was scroll in which case the temporary touch
1680 // state was only valid for this one action.
1681 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1682 if (mTempTouchState.displayId >= 0) {
1683 if (oldStateIndex >= 0) {
1684 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1685 } else {
1686 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1687 }
1688 } else if (oldStateIndex >= 0) {
1689 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 }
1692
1693 // Update hover state.
1694 mLastHoverWindowHandle = newHoverWindowHandle;
1695 }
1696 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001697 if (DEBUG_FOCUS) {
1698 ALOGD("Not updating touch focus because injection was denied.");
1699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701
1702Unresponsive:
1703 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1704 mTempTouchState.reset();
1705
1706 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001707 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001708 if (DEBUG_FOCUS) {
1709 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1710 "timeSpentWaitingForApplication=%0.1fms",
1711 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 return injectionResult;
1714}
1715
1716void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001717 int32_t targetFlags, BitSet32 pointerIds,
1718 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001719 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1720 if (inputChannel == nullptr) {
1721 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1722 return;
1723 }
1724
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001726 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001727 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001729 target.xOffset = -windowInfo->frameLeft;
1730 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001731 target.globalScaleFactor = windowInfo->globalScaleFactor;
1732 target.windowXScale = windowInfo->windowXScale;
1733 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001735 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736}
1737
Michael Wright3dd60e22019-03-27 22:06:44 +00001738void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001739 int32_t displayId, float xOffset,
1740 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001741 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1742 mGlobalMonitorsByDisplay.find(displayId);
1743
1744 if (it != mGlobalMonitorsByDisplay.end()) {
1745 const std::vector<Monitor>& monitors = it->second;
1746 for (const Monitor& monitor : monitors) {
1747 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 }
1750}
1751
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1753 float yOffset,
1754 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001755 InputTarget target;
1756 target.inputChannel = monitor.inputChannel;
1757 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1758 target.xOffset = xOffset;
1759 target.yOffset = yOffset;
1760 target.pointerIds.clear();
1761 target.globalScaleFactor = 1.0f;
1762 inputTargets.push_back(target);
1763}
1764
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001766 const InjectionState* injectionState) {
1767 if (injectionState &&
1768 (windowHandle == nullptr ||
1769 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1770 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001771 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001773 "owned by uid %d",
1774 injectionState->injectorPid, injectionState->injectorUid,
1775 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 } else {
1777 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 }
1780 return false;
1781 }
1782 return true;
1783}
1784
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001785bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1786 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001788 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1789 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 if (otherHandle == windowHandle) {
1791 break;
1792 }
1793
1794 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 if (otherInfo->displayId == displayId && otherInfo->visible &&
1796 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 return true;
1798 }
1799 }
1800 return false;
1801}
1802
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001803bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1804 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001805 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001806 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001807 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001808 if (otherHandle == windowHandle) {
1809 break;
1810 }
1811
1812 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001813 if (otherInfo->displayId == displayId && otherInfo->visible &&
1814 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001815 return true;
1816 }
1817 }
1818 return false;
1819}
1820
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1822 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
1823 const EventEntry* eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001824 // If the window is paused then keep waiting.
1825 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001826 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001827 }
1828
1829 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001830 sp<Connection> connection =
1831 getConnectionLocked(getInputChannelLocked(windowHandle->getToken()));
1832 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001833 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001834 "registered with the input dispatcher. The window may be in the "
1835 "process of being removed.",
1836 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001837 }
1838
1839 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001840 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 "The window may be in the process of being removed.",
1843 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001844 }
1845
1846 // If the connection is backed up then keep waiting.
1847 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001848 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001849 "Outbound queue length: %zu. Wait queue length: %zu.",
1850 targetType, connection->outboundQueue.size(),
1851 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001852 }
1853
1854 // Ensure that the dispatch queues aren't too far backed up for this event.
1855 if (eventEntry->type == EventEntry::TYPE_KEY) {
1856 // If the event is a key event, then we must wait for all previous events to
1857 // complete before delivering it because previous events may have the
1858 // side-effect of transferring focus to a different window and we want to
1859 // ensure that the following keys are sent to the new window.
1860 //
1861 // Suppose the user touches a button in a window then immediately presses "A".
1862 // If the button causes a pop-up window to appear then we want to ensure that
1863 // the "A" key is delivered to the new pop-up window. This is because users
1864 // often anticipate pending UI changes when typing on a keyboard.
1865 // To obtain this behavior, we must serialize key events with respect to all
1866 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001867 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001868 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001869 "finished processing all of the input events that were previously "
1870 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1871 "%zu.",
1872 targetType, connection->outboundQueue.size(),
1873 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 }
Jeff Brownffb49772014-10-10 19:01:34 -07001875 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 // Touch events can always be sent to a window immediately because the user intended
1877 // to touch whatever was visible at the time. Even if focus changes or a new
1878 // window appears moments later, the touch event was meant to be delivered to
1879 // whatever window happened to be on screen at the time.
1880 //
1881 // Generic motion events, such as trackball or joystick events are a little trickier.
1882 // Like key events, generic motion events are delivered to the focused window.
1883 // Unlike key events, generic motion events don't tend to transfer focus to other
1884 // windows and it is not important for them to be serialized. So we prefer to deliver
1885 // generic motion events as soon as possible to improve efficiency and reduce lag
1886 // through batching.
1887 //
1888 // The one case where we pause input event delivery is when the wait queue is piling
1889 // up with lots of events because the application is not responding.
1890 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001891 if (!connection->waitQueue.empty() &&
1892 currentTime >=
1893 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001894 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001895 "finished processing certain input events that were delivered to "
1896 "it over "
1897 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1898 "%0.1fms.",
1899 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1900 connection->waitQueue.size(),
1901 (currentTime - connection->waitQueue.front()->deliveryTime) *
1902 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001905 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906}
1907
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001908std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 const sp<InputApplicationHandle>& applicationHandle,
1910 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001911 if (applicationHandle != nullptr) {
1912 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001913 std::string label(applicationHandle->getName());
1914 label += " - ";
1915 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 return label;
1917 } else {
1918 return applicationHandle->getName();
1919 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001920 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 return windowHandle->getName();
1922 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001923 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 }
1925}
1926
1927void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001928 int32_t displayId = getTargetDisplayId(eventEntry);
1929 sp<InputWindowHandle> focusedWindowHandle =
1930 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1931 if (focusedWindowHandle != nullptr) {
1932 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1934#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001935 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936#endif
1937 return;
1938 }
1939 }
1940
1941 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1942 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 case EventEntry::TYPE_MOTION: {
1944 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1945 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1946 return;
1947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001949 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1950 eventType = USER_ACTIVITY_EVENT_TOUCH;
1951 }
1952 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 case EventEntry::TYPE_KEY: {
1955 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1956 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1957 return;
1958 }
1959 eventType = USER_ACTIVITY_EVENT_BUTTON;
1960 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 }
1963
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001964 std::unique_ptr<CommandEntry> commandEntry =
1965 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 commandEntry->eventTime = eventEntry->eventTime;
1967 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001968 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969}
1970
1971void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001972 const sp<Connection>& connection,
1973 EventEntry* eventEntry,
1974 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001975 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001976 std::string message =
1977 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1978 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001979 ATRACE_NAME(message.c_str());
1980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981#if DEBUG_DISPATCH_CYCLE
1982 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001983 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1984 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1985 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1986 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1987 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988#endif
1989
1990 // Skip this event if the connection status is not normal.
1991 // We don't want to enqueue additional outbound events if the connection is broken.
1992 if (connection->status != Connection::STATUS_NORMAL) {
1993#if DEBUG_DISPATCH_CYCLE
1994 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001995 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996#endif
1997 return;
1998 }
1999
2000 // Split a motion event if needed.
2001 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
2002 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
2003
2004 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
2005 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002006 MotionEntry* splitMotionEntry =
2007 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 if (!splitMotionEntry) {
2009 return; // split event was dropped
2010 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002011 if (DEBUG_FOCUS) {
2012 ALOGD("channel '%s' ~ Split motion event.",
2013 connection->getInputChannelName().c_str());
2014 logOutboundMotionDetails(" ", splitMotionEntry);
2015 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002016 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 splitMotionEntry->release();
2018 return;
2019 }
2020 }
2021
2022 // Not splitting. Enqueue dispatch entries for the event as is.
2023 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2024}
2025
2026void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002027 const sp<Connection>& connection,
2028 EventEntry* eventEntry,
2029 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002030 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002031 std::string message =
2032 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2033 ")",
2034 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002035 ATRACE_NAME(message.c_str());
2036 }
2037
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002038 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039
2040 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002041 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002042 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002043 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002045 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002047 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002048 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002049 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002050 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002051 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053
2054 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002055 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 startDispatchCycleLocked(currentTime, connection);
2057 }
2058}
2059
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002060void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2061 EventEntry* eventEntry,
2062 const InputTarget* inputTarget,
2063 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002064 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002065 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2066 connection->getInputChannelName().c_str(),
2067 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002068 ATRACE_NAME(message.c_str());
2069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 int32_t inputTargetFlags = inputTarget->flags;
2071 if (!(inputTargetFlags & dispatchMode)) {
2072 return;
2073 }
2074 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2075
2076 // This is a new event.
2077 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002078 DispatchEntry* dispatchEntry =
2079 new DispatchEntry(eventEntry, // increments ref
2080 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2081 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2082 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083
2084 // Apply target flags and update the connection's input state.
2085 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002086 case EventEntry::TYPE_KEY: {
2087 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2088 dispatchEntry->resolvedAction = keyEntry->action;
2089 dispatchEntry->resolvedFlags = keyEntry->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002091 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2092 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2095 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002097 delete dispatchEntry;
2098 return; // skip the inconsistent event
2099 }
2100 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002103 case EventEntry::TYPE_MOTION: {
2104 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2105 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2106 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2107 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2108 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2109 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2110 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2111 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2112 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2113 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2114 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2115 } else {
2116 dispatchEntry->resolvedAction = motionEntry->action;
2117 }
2118 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2119 !connection->inputState.isHovering(motionEntry->deviceId, motionEntry->source,
2120 motionEntry->displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002122 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2123 "event",
2124 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002126 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002129 dispatchEntry->resolvedFlags = motionEntry->flags;
2130 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2131 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2132 }
2133 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2134 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002137 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2138 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2141 "event",
2142 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002144 delete dispatchEntry;
2145 return; // skip the inconsistent event
2146 }
2147
2148 dispatchPointerDownOutsideFocus(motionEntry->source, dispatchEntry->resolvedAction,
2149 inputTarget->inputChannel->getToken());
2150
2151 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
2154
2155 // Remember that we are waiting for this dispatch to complete.
2156 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002157 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 }
2159
2160 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002161 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002162 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002163}
2164
chaviwfd6d3512019-03-25 13:23:49 -07002165void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002166 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002167 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002168 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2169 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002170 return;
2171 }
2172
2173 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2174 if (inputWindowHandle == nullptr) {
2175 return;
2176 }
2177
chaviw8c9cf542019-03-25 13:02:48 -07002178 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002179 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002180
2181 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2182
2183 if (!hasFocusChanged) {
2184 return;
2185 }
2186
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002187 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2188 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002189 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002190 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191}
2192
2193void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002194 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002195 if (ATRACE_ENABLED()) {
2196 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002198 ATRACE_NAME(message.c_str());
2199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002201 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202#endif
2203
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002204 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2205 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 dispatchEntry->deliveryTime = currentTime;
2207
2208 // Publish the event.
2209 status_t status;
2210 EventEntry* eventEntry = dispatchEntry->eventEntry;
2211 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002212 case EventEntry::TYPE_KEY: {
2213 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002215 // Publish the key event.
2216 status = connection->inputPublisher
2217 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2218 keyEntry->source, keyEntry->displayId,
2219 dispatchEntry->resolvedAction,
2220 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2221 keyEntry->scanCode, keyEntry->metaState,
2222 keyEntry->repeatCount, keyEntry->downTime,
2223 keyEntry->eventTime);
2224 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002227 case EventEntry::TYPE_MOTION: {
2228 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002230 PointerCoords scaledCoords[MAX_POINTERS];
2231 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2232
2233 // Set the X and Y offset depending on the input source.
2234 float xOffset, yOffset;
2235 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2236 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2237 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2238 float wxs = dispatchEntry->windowXScale;
2239 float wys = dispatchEntry->windowYScale;
2240 xOffset = dispatchEntry->xOffset * wxs;
2241 yOffset = dispatchEntry->yOffset * wys;
2242 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2243 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2244 scaledCoords[i] = motionEntry->pointerCoords[i];
2245 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2246 }
2247 usingCoords = scaledCoords;
2248 }
2249 } else {
2250 xOffset = 0.0f;
2251 yOffset = 0.0f;
2252
2253 // We don't want the dispatch target to know.
2254 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2255 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2256 scaledCoords[i].clear();
2257 }
2258 usingCoords = scaledCoords;
2259 }
2260 }
2261
2262 // Publish the motion event.
2263 status = connection->inputPublisher
2264 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2265 motionEntry->source, motionEntry->displayId,
2266 dispatchEntry->resolvedAction,
2267 motionEntry->actionButton,
2268 dispatchEntry->resolvedFlags,
2269 motionEntry->edgeFlags, motionEntry->metaState,
2270 motionEntry->buttonState,
2271 motionEntry->classification, xOffset, yOffset,
2272 motionEntry->xPrecision,
2273 motionEntry->yPrecision,
2274 motionEntry->xCursorPosition,
2275 motionEntry->yCursorPosition,
2276 motionEntry->downTime, motionEntry->eventTime,
2277 motionEntry->pointerCount,
2278 motionEntry->pointerProperties, usingCoords);
2279 break;
2280 }
2281
2282 default:
2283 ALOG_ASSERT(false);
2284 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
2287 // Check the result.
2288 if (status) {
2289 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002290 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002292 "This is unexpected because the wait queue is empty, so the pipe "
2293 "should be empty and we shouldn't have any problems writing an "
2294 "event to it, status=%d",
2295 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2297 } else {
2298 // Pipe is full and we are waiting for the app to finish process some events
2299 // before sending more events to it.
2300#if DEBUG_DISPATCH_CYCLE
2301 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 "waiting for the application to catch up",
2303 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304#endif
2305 connection->inputPublisherBlocked = true;
2306 }
2307 } else {
2308 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309 "status=%d",
2310 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2312 }
2313 return;
2314 }
2315
2316 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002317 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2318 connection->outboundQueue.end(),
2319 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002320 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002321 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002322 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 }
2324}
2325
2326void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327 const sp<Connection>& connection, uint32_t seq,
2328 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329#if DEBUG_DISPATCH_CYCLE
2330 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332#endif
2333
2334 connection->inputPublisherBlocked = false;
2335
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 if (connection->status == Connection::STATUS_BROKEN ||
2337 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 return;
2339 }
2340
2341 // Notify other system components and prepare to start the next dispatch cycle.
2342 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2343}
2344
2345void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346 const sp<Connection>& connection,
2347 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348#if DEBUG_DISPATCH_CYCLE
2349 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002350 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351#endif
2352
2353 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002354 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002355 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002356 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002357 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
2359 // The connection appears to be unrecoverably broken.
2360 // Ignore already broken or zombie connections.
2361 if (connection->status == Connection::STATUS_NORMAL) {
2362 connection->status = Connection::STATUS_BROKEN;
2363
2364 if (notify) {
2365 // Notify other system components.
2366 onDispatchCycleBrokenLocked(currentTime, connection);
2367 }
2368 }
2369}
2370
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002371void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2372 while (!queue.empty()) {
2373 DispatchEntry* dispatchEntry = queue.front();
2374 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002375 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 }
2377}
2378
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002379void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002381 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 }
2383 delete dispatchEntry;
2384}
2385
2386int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2387 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2388
2389 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002390 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002392 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002394 "fd=%d, events=0x%x",
2395 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 return 0; // remove the callback
2397 }
2398
2399 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002400 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2402 if (!(events & ALOOPER_EVENT_INPUT)) {
2403 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002404 "events=0x%x",
2405 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 return 1;
2407 }
2408
2409 nsecs_t currentTime = now();
2410 bool gotOne = false;
2411 status_t status;
2412 for (;;) {
2413 uint32_t seq;
2414 bool handled;
2415 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2416 if (status) {
2417 break;
2418 }
2419 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2420 gotOne = true;
2421 }
2422 if (gotOne) {
2423 d->runCommandsLockedInterruptible();
2424 if (status == WOULD_BLOCK) {
2425 return 1;
2426 }
2427 }
2428
2429 notify = status != DEAD_OBJECT || !connection->monitor;
2430 if (notify) {
2431 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002432 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
2434 } else {
2435 // Monitor channels are never explicitly unregistered.
2436 // We do it automatically when the remote endpoint is closed so don't warn
2437 // about them.
2438 notify = !connection->monitor;
2439 if (notify) {
2440 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002441 "events=0x%x",
2442 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 }
2444 }
2445
2446 // Unregister the channel.
2447 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2448 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002449 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450}
2451
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002452void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002454 for (const auto& pair : mConnectionsByFd) {
2455 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
2457}
2458
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002460 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002461 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2462 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2463}
2464
2465void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2466 const CancelationOptions& options,
2467 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2468 for (const auto& it : monitorsByDisplay) {
2469 const std::vector<Monitor>& monitors = it.second;
2470 for (const Monitor& monitor : monitors) {
2471 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002472 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002473 }
2474}
2475
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2477 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002478 sp<Connection> connection = getConnectionLocked(channel);
2479 if (connection == nullptr) {
2480 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002482
2483 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484}
2485
2486void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2487 const sp<Connection>& connection, const CancelationOptions& options) {
2488 if (connection->status == Connection::STATUS_BROKEN) {
2489 return;
2490 }
2491
2492 nsecs_t currentTime = now();
2493
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002494 std::vector<EventEntry*> cancelationEvents;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002495 connection->inputState.synthesizeCancelationEvents(currentTime, cancelationEvents, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002497 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002499 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002500 "with reality: %s, mode=%d.",
2501 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2502 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503#endif
2504 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002505 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 switch (cancelationEventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002507 case EventEntry::TYPE_KEY:
2508 logOutboundKeyDetails("cancel - ",
2509 static_cast<KeyEntry*>(cancelationEventEntry));
2510 break;
2511 case EventEntry::TYPE_MOTION:
2512 logOutboundMotionDetails("cancel - ",
2513 static_cast<MotionEntry*>(cancelationEventEntry));
2514 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 }
2516
2517 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518 sp<InputWindowHandle> windowHandle =
2519 getWindowHandleLocked(connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002520 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2522 target.xOffset = -windowInfo->frameLeft;
2523 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002524 target.globalScaleFactor = windowInfo->globalScaleFactor;
2525 target.windowXScale = windowInfo->windowXScale;
2526 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 } else {
2528 target.xOffset = 0;
2529 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002530 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 }
2532 target.inputChannel = connection->inputChannel;
2533 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2534
chaviw8c9cf542019-03-25 13:02:48 -07002535 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537
2538 cancelationEventEntry->release();
2539 }
2540
2541 startDispatchCycleLocked(currentTime, connection);
2542 }
2543}
2544
Garfield Tane84e6f92019-08-29 17:28:41 -07002545MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry,
2546 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 ALOG_ASSERT(pointerIds.value != 0);
2548
2549 uint32_t splitPointerIndexMap[MAX_POINTERS];
2550 PointerProperties splitPointerProperties[MAX_POINTERS];
2551 PointerCoords splitPointerCoords[MAX_POINTERS];
2552
2553 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2554 uint32_t splitPointerCount = 0;
2555
2556 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 const PointerProperties& pointerProperties =
2559 originalMotionEntry->pointerProperties[originalPointerIndex];
2560 uint32_t pointerId = uint32_t(pointerProperties.id);
2561 if (pointerIds.hasBit(pointerId)) {
2562 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2563 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2564 splitPointerCoords[splitPointerCount].copyFrom(
2565 originalMotionEntry->pointerCoords[originalPointerIndex]);
2566 splitPointerCount += 1;
2567 }
2568 }
2569
2570 if (splitPointerCount != pointerIds.count()) {
2571 // This is bad. We are missing some of the pointers that we expected to deliver.
2572 // Most likely this indicates that we received an ACTION_MOVE events that has
2573 // different pointer ids than we expected based on the previous ACTION_DOWN
2574 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2575 // in this way.
2576 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 "we expected there to be %d pointers. This probably means we received "
2578 "a broken sequence of pointer ids from the input device.",
2579 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002580 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
2583 int32_t action = originalMotionEntry->action;
2584 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2586 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2588 const PointerProperties& pointerProperties =
2589 originalMotionEntry->pointerProperties[originalPointerIndex];
2590 uint32_t pointerId = uint32_t(pointerProperties.id);
2591 if (pointerIds.hasBit(pointerId)) {
2592 if (pointerIds.count() == 1) {
2593 // The first/last pointer went down/up.
2594 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002595 ? AMOTION_EVENT_ACTION_DOWN
2596 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 } else {
2598 // A secondary pointer went down/up.
2599 uint32_t splitPointerIndex = 0;
2600 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2601 splitPointerIndex += 1;
2602 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002603 action = maskedAction |
2604 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 }
2606 } else {
2607 // An unrelated pointer changed.
2608 action = AMOTION_EVENT_ACTION_MOVE;
2609 }
2610 }
2611
Garfield Tan00f511d2019-06-12 16:55:40 -07002612 MotionEntry* splitMotionEntry =
2613 new MotionEntry(originalMotionEntry->sequenceNum, originalMotionEntry->eventTime,
2614 originalMotionEntry->deviceId, originalMotionEntry->source,
2615 originalMotionEntry->displayId, originalMotionEntry->policyFlags,
2616 action, originalMotionEntry->actionButton, originalMotionEntry->flags,
2617 originalMotionEntry->metaState, originalMotionEntry->buttonState,
2618 originalMotionEntry->classification, originalMotionEntry->edgeFlags,
2619 originalMotionEntry->xPrecision, originalMotionEntry->yPrecision,
2620 originalMotionEntry->xCursorPosition,
2621 originalMotionEntry->yCursorPosition, originalMotionEntry->downTime,
2622 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623
2624 if (originalMotionEntry->injectionState) {
2625 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2626 splitMotionEntry->injectionState->refCount += 1;
2627 }
2628
2629 return splitMotionEntry;
2630}
2631
2632void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2633#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002634 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635#endif
2636
2637 bool needWake;
2638 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002639 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640
Prabir Pradhan42611e02018-11-27 14:04:02 -08002641 ConfigurationChangedEntry* newEntry =
2642 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 needWake = enqueueInboundEventLocked(newEntry);
2644 } // release lock
2645
2646 if (needWake) {
2647 mLooper->wake();
2648 }
2649}
2650
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002651/**
2652 * If one of the meta shortcuts is detected, process them here:
2653 * Meta + Backspace -> generate BACK
2654 * Meta + Enter -> generate HOME
2655 * This will potentially overwrite keyCode and metaState.
2656 */
2657void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002659 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2660 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2661 if (keyCode == AKEYCODE_DEL) {
2662 newKeyCode = AKEYCODE_BACK;
2663 } else if (keyCode == AKEYCODE_ENTER) {
2664 newKeyCode = AKEYCODE_HOME;
2665 }
2666 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002667 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002668 struct KeyReplacement replacement = {keyCode, deviceId};
2669 mReplacedKeys.add(replacement, newKeyCode);
2670 keyCode = newKeyCode;
2671 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2672 }
2673 } else if (action == AKEY_EVENT_ACTION_UP) {
2674 // In order to maintain a consistent stream of up and down events, check to see if the key
2675 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2676 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002677 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002678 struct KeyReplacement replacement = {keyCode, deviceId};
2679 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2680 if (index >= 0) {
2681 keyCode = mReplacedKeys.valueAt(index);
2682 mReplacedKeys.removeItemsAt(index);
2683 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2684 }
2685 }
2686}
2687
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2689#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002690 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2691 "policyFlags=0x%x, action=0x%x, "
2692 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2693 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2694 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2695 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696#endif
2697 if (!validateKeyEvent(args->action)) {
2698 return;
2699 }
2700
2701 uint32_t policyFlags = args->policyFlags;
2702 int32_t flags = args->flags;
2703 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002704 // InputDispatcher tracks and generates key repeats on behalf of
2705 // whatever notifies it, so repeatCount should always be set to 0
2706 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2708 policyFlags |= POLICY_FLAG_VIRTUAL;
2709 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 if (policyFlags & POLICY_FLAG_FUNCTION) {
2712 metaState |= AMETA_FUNCTION_ON;
2713 }
2714
2715 policyFlags |= POLICY_FLAG_TRUSTED;
2716
Michael Wright78f24442014-08-06 15:55:28 -07002717 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002718 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002719
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2722 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723
Michael Wright2b3c3302018-03-02 17:19:13 +00002724 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002726 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2727 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731 bool needWake;
2732 { // acquire lock
2733 mLock.lock();
2734
2735 if (shouldSendKeyToInputFilterLocked(args)) {
2736 mLock.unlock();
2737
2738 policyFlags |= POLICY_FLAG_FILTERED;
2739 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2740 return; // event was consumed by the filter
2741 }
2742
2743 mLock.lock();
2744 }
2745
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002746 KeyEntry* newEntry =
2747 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2748 args->displayId, policyFlags, args->action, flags, keyCode,
2749 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750
2751 needWake = enqueueInboundEventLocked(newEntry);
2752 mLock.unlock();
2753 } // release lock
2754
2755 if (needWake) {
2756 mLooper->wake();
2757 }
2758}
2759
2760bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2761 return mInputFilterEnabled;
2762}
2763
2764void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2765#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002766 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002767 ", policyFlags=0x%x, "
2768 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2769 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002770 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002771 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2772 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
2773 args->edgeFlags, args->xPrecision, args->yPrecision, arg->xCursorPosition,
2774 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 for (uint32_t i = 0; i < args->pointerCount; i++) {
2776 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 "x=%f, y=%f, pressure=%f, size=%f, "
2778 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2779 "orientation=%f",
2780 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2781 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2782 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2783 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2784 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2785 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2786 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2787 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2788 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2789 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 }
2791#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002792 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2793 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 return;
2795 }
2796
2797 uint32_t policyFlags = args->policyFlags;
2798 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002799
2800 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002801 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002802 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2803 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002804 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806
2807 bool needWake;
2808 { // acquire lock
2809 mLock.lock();
2810
2811 if (shouldSendMotionToInputFilterLocked(args)) {
2812 mLock.unlock();
2813
2814 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002815 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2816 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2817 args->buttonState, args->classification, 0, 0, args->xPrecision,
2818 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2819 args->downTime, args->eventTime, args->pointerCount,
2820 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821
2822 policyFlags |= POLICY_FLAG_FILTERED;
2823 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2824 return; // event was consumed by the filter
2825 }
2826
2827 mLock.lock();
2828 }
2829
2830 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002831 MotionEntry* newEntry =
2832 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2833 args->displayId, policyFlags, args->action, args->actionButton,
2834 args->flags, args->metaState, args->buttonState,
2835 args->classification, args->edgeFlags, args->xPrecision,
2836 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2837 args->downTime, args->pointerCount, args->pointerProperties,
2838 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839
2840 needWake = enqueueInboundEventLocked(newEntry);
2841 mLock.unlock();
2842 } // release lock
2843
2844 if (needWake) {
2845 mLooper->wake();
2846 }
2847}
2848
2849bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002850 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851}
2852
2853void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2854#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002855 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002856 "switchMask=0x%08x",
2857 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858#endif
2859
2860 uint32_t policyFlags = args->policyFlags;
2861 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002862 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863}
2864
2865void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2866#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002867 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2868 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869#endif
2870
2871 bool needWake;
2872 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874
Prabir Pradhan42611e02018-11-27 14:04:02 -08002875 DeviceResetEntry* newEntry =
2876 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 needWake = enqueueInboundEventLocked(newEntry);
2878 } // release lock
2879
2880 if (needWake) {
2881 mLooper->wake();
2882 }
2883}
2884
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2886 int32_t injectorUid, int32_t syncMode,
2887 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888#if DEBUG_INBOUND_EVENT_DETAILS
2889 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2891 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892#endif
2893
2894 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2895
2896 policyFlags |= POLICY_FLAG_INJECTED;
2897 if (hasInjectionPermission(injectorPid, injectorUid)) {
2898 policyFlags |= POLICY_FLAG_TRUSTED;
2899 }
2900
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002901 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002903 case AINPUT_EVENT_TYPE_KEY: {
2904 KeyEvent keyEvent;
2905 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2906 int32_t action = keyEvent.getAction();
2907 if (!validateKeyEvent(action)) {
2908 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 int32_t flags = keyEvent.getFlags();
2912 int32_t keyCode = keyEvent.getKeyCode();
2913 int32_t metaState = keyEvent.getMetaState();
2914 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2915 /*byref*/ keyCode, /*byref*/ metaState);
2916 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2917 keyEvent.getDisplayId(), action, flags, keyCode,
2918 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2919 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2922 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002923 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924
2925 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2926 android::base::Timer t;
2927 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2928 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2929 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2930 std::to_string(t.duration().count()).c_str());
2931 }
2932 }
2933
2934 mLock.lock();
2935 KeyEntry* injectedEntry =
2936 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2937 keyEvent.getDeviceId(), keyEvent.getSource(),
2938 keyEvent.getDisplayId(), policyFlags, action, flags,
2939 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2940 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2941 keyEvent.getDownTime());
2942 injectedEntries.push(injectedEntry);
2943 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 }
2945
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 case AINPUT_EVENT_TYPE_MOTION: {
2947 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2948 int32_t action = motionEvent->getAction();
2949 size_t pointerCount = motionEvent->getPointerCount();
2950 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2951 int32_t actionButton = motionEvent->getActionButton();
2952 int32_t displayId = motionEvent->getDisplayId();
2953 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2954 return INPUT_EVENT_INJECTION_FAILED;
2955 }
2956
2957 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2958 nsecs_t eventTime = motionEvent->getEventTime();
2959 android::base::Timer t;
2960 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2961 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2962 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2963 std::to_string(t.duration().count()).c_str());
2964 }
2965 }
2966
2967 mLock.lock();
2968 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2969 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2970 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07002971 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2972 motionEvent->getDeviceId(), motionEvent->getSource(),
2973 motionEvent->getDisplayId(), policyFlags, action, actionButton,
2974 motionEvent->getFlags(), motionEvent->getMetaState(),
2975 motionEvent->getButtonState(), motionEvent->getClassification(),
2976 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2977 motionEvent->getYPrecision(),
2978 motionEvent->getRawXCursorPosition(),
2979 motionEvent->getRawYCursorPosition(),
2980 motionEvent->getDownTime(), uint32_t(pointerCount),
2981 pointerProperties, samplePointerCoords,
2982 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 injectedEntries.push(injectedEntry);
2984 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2985 sampleEventTimes += 1;
2986 samplePointerCoords += pointerCount;
2987 MotionEntry* nextInjectedEntry =
2988 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2989 motionEvent->getDeviceId(), motionEvent->getSource(),
2990 motionEvent->getDisplayId(), policyFlags, action,
2991 actionButton, motionEvent->getFlags(),
2992 motionEvent->getMetaState(), motionEvent->getButtonState(),
2993 motionEvent->getClassification(),
2994 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2995 motionEvent->getYPrecision(),
2996 motionEvent->getRawXCursorPosition(),
2997 motionEvent->getRawYCursorPosition(),
2998 motionEvent->getDownTime(), uint32_t(pointerCount),
2999 pointerProperties, samplePointerCoords,
3000 motionEvent->getXOffset(), motionEvent->getYOffset());
3001 injectedEntries.push(nextInjectedEntry);
3002 }
3003 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 default:
3007 ALOGW("Cannot inject event of type %d", event->getType());
3008 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
3010
3011 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3012 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3013 injectionState->injectionIsAsync = true;
3014 }
3015
3016 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003017 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018
3019 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003020 while (!injectedEntries.empty()) {
3021 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3022 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 }
3024
3025 mLock.unlock();
3026
3027 if (needWake) {
3028 mLooper->wake();
3029 }
3030
3031 int32_t injectionResult;
3032 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003033 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034
3035 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3036 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3037 } else {
3038 for (;;) {
3039 injectionResult = injectionState->injectionResult;
3040 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3041 break;
3042 }
3043
3044 nsecs_t remainingTimeout = endTime - now();
3045 if (remainingTimeout <= 0) {
3046#if DEBUG_INJECTION
3047 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049#endif
3050 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3051 break;
3052 }
3053
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003054 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
3056
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003057 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3058 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 while (injectionState->pendingForegroundDispatches != 0) {
3060#if DEBUG_INJECTION
3061 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063#endif
3064 nsecs_t remainingTimeout = endTime - now();
3065 if (remainingTimeout <= 0) {
3066#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003067 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3068 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069#endif
3070 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3071 break;
3072 }
3073
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003074 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 }
3076 }
3077 }
3078
3079 injectionState->release();
3080 } // release lock
3081
3082#if DEBUG_INJECTION
3083 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 "injectorPid=%d, injectorUid=%d",
3085 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086#endif
3087
3088 return injectionResult;
3089}
3090
3091bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 return injectorUid == 0 ||
3093 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094}
3095
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003096void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 InjectionState* injectionState = entry->injectionState;
3098 if (injectionState) {
3099#if DEBUG_INJECTION
3100 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 "injectorPid=%d, injectorUid=%d",
3102 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103#endif
3104
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003105 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 // Log the outcome since the injector did not wait for the injection result.
3107 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003108 case INPUT_EVENT_INJECTION_SUCCEEDED:
3109 ALOGV("Asynchronous input event injection succeeded.");
3110 break;
3111 case INPUT_EVENT_INJECTION_FAILED:
3112 ALOGW("Asynchronous input event injection failed.");
3113 break;
3114 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3115 ALOGW("Asynchronous input event injection permission denied.");
3116 break;
3117 case INPUT_EVENT_INJECTION_TIMED_OUT:
3118 ALOGW("Asynchronous input event injection timed out.");
3119 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 }
3121 }
3122
3123 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003124 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 }
3126}
3127
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003128void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 InjectionState* injectionState = entry->injectionState;
3130 if (injectionState) {
3131 injectionState->pendingForegroundDispatches += 1;
3132 }
3133}
3134
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003135void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 InjectionState* injectionState = entry->injectionState;
3137 if (injectionState) {
3138 injectionState->pendingForegroundDispatches -= 1;
3139
3140 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003141 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 }
3143 }
3144}
3145
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003146std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3147 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003148 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003149}
3150
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003152 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003153 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003154 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3155 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003156 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003157 return windowHandle;
3158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003161 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162}
3163
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003164bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003165 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003166 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3167 for (const sp<InputWindowHandle>& handle : windowHandles) {
3168 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003169 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003170 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 ", but it should belong to display %" PRId32,
3172 windowHandle->getName().c_str(), it.first,
3173 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003174 }
3175 return true;
3176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
3178 }
3179 return false;
3180}
3181
Robert Carr5c8a0262018-10-03 16:30:44 -07003182sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3183 size_t count = mInputChannelsByToken.count(token);
3184 if (count == 0) {
3185 return nullptr;
3186 }
3187 return mInputChannelsByToken.at(token);
3188}
3189
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003190void InputDispatcher::updateWindowHandlesForDisplayLocked(
3191 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3192 if (inputWindowHandles.empty()) {
3193 // Remove all handles on a display if there are no windows left.
3194 mWindowHandlesByDisplay.erase(displayId);
3195 return;
3196 }
3197
3198 // Since we compare the pointer of input window handles across window updates, we need
3199 // to make sure the handle object for the same window stays unchanged across updates.
3200 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3201 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3202 for (const sp<InputWindowHandle>& handle : oldHandles) {
3203 oldHandlesByTokens[handle->getToken()] = handle;
3204 }
3205
3206 std::vector<sp<InputWindowHandle>> newHandles;
3207 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3208 if (!handle->updateInfo()) {
3209 // handle no longer valid
3210 continue;
3211 }
3212
3213 const InputWindowInfo* info = handle->getInfo();
3214 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3215 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3216 const bool noInputChannel =
3217 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3218 const bool canReceiveInput =
3219 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3220 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3221 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003222 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003223 handle->getName().c_str());
3224 }
3225 continue;
3226 }
3227
3228 if (info->displayId != displayId) {
3229 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3230 handle->getName().c_str(), displayId, info->displayId);
3231 continue;
3232 }
3233
3234 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3235 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3236 oldHandle->updateFrom(handle);
3237 newHandles.push_back(oldHandle);
3238 } else {
3239 newHandles.push_back(handle);
3240 }
3241 }
3242
3243 // Insert or replace
3244 mWindowHandlesByDisplay[displayId] = newHandles;
3245}
3246
Arthur Hungb92218b2018-08-14 12:00:21 +08003247/**
3248 * Called from InputManagerService, update window handle list by displayId that can receive input.
3249 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3250 * If set an empty list, remove all handles from the specific display.
3251 * For focused handle, check if need to change and send a cancel event to previous one.
3252 * For removed handle, check if need to send a cancel event if already in touch.
3253 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003254void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255 int32_t displayId,
3256 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003257 if (DEBUG_FOCUS) {
3258 std::string windowList;
3259 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3260 windowList += iwh->getName() + " ";
3261 }
3262 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003265 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266
Arthur Hungb92218b2018-08-14 12:00:21 +08003267 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003268 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3269 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003271 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3272
Tiger Huang721e26f2018-07-24 22:26:19 +08003273 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003275 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3276 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3277 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3278 windowHandle->getInfo()->visible) {
3279 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003280 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003281 if (windowHandle == mLastHoverWindowHandle) {
3282 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 }
3285
3286 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003287 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 }
3289
Tiger Huang721e26f2018-07-24 22:26:19 +08003290 sp<InputWindowHandle> oldFocusedWindowHandle =
3291 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3292
3293 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3294 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003295 if (DEBUG_FOCUS) {
3296 ALOGD("Focus left window: %s in display %" PRId32,
3297 oldFocusedWindowHandle->getName().c_str(), displayId);
3298 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 sp<InputChannel> focusedInputChannel =
3300 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003301 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303 "focus left window");
3304 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003306 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003308 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003309 if (DEBUG_FOCUS) {
3310 ALOGD("Focus entered window: %s in display %" PRId32,
3311 newFocusedWindowHandle->getName().c_str(), displayId);
3312 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003313 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314 }
Robert Carrf759f162018-11-13 12:57:11 -08003315
3316 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003317 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 }
3320
Arthur Hungb92218b2018-08-14 12:00:21 +08003321 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3322 if (stateIndex >= 0) {
3323 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003325 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003326 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003327 if (DEBUG_FOCUS) {
3328 ALOGD("Touched window was removed: %s in display %" PRId32,
3329 touchedWindow.windowHandle->getName().c_str(), displayId);
3330 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003331 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003332 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003333 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003334 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 "touched window was removed");
3336 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3337 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003338 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003339 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003340 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
3344 }
3345
3346 // Release information for windows that are no longer present.
3347 // This ensures that unused input channels are released promptly.
3348 // Otherwise, they might stick around until the window handle is destroyed
3349 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003350 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003351 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003352 if (DEBUG_FOCUS) {
3353 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3354 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003355 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 }
3357 }
3358 } // release lock
3359
3360 // Wake up poll loop since it may need to make new input dispatching choices.
3361 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003362
3363 if (setInputWindowsListener) {
3364 setInputWindowsListener->onSetInputWindowsFinished();
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366}
3367
3368void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003369 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003370 if (DEBUG_FOCUS) {
3371 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3372 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003375 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
Tiger Huang721e26f2018-07-24 22:26:19 +08003377 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3378 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003379 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003380 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3381 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003384 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003386 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003388 oldFocusedApplicationHandle.clear();
3389 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 } // release lock
3392
3393 // Wake up poll loop since it may need to make new input dispatching choices.
3394 mLooper->wake();
3395}
3396
Tiger Huang721e26f2018-07-24 22:26:19 +08003397/**
3398 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3399 * the display not specified.
3400 *
3401 * We track any unreleased events for each window. If a window loses the ability to receive the
3402 * released event, we will send a cancel event to it. So when the focused display is changed, we
3403 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3404 * display. The display-specified events won't be affected.
3405 */
3406void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003407 if (DEBUG_FOCUS) {
3408 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3409 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003410 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003411 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003412
3413 if (mFocusedDisplayId != displayId) {
3414 sp<InputWindowHandle> oldFocusedWindowHandle =
3415 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3416 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003417 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003418 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003419 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003420 CancelationOptions
3421 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3422 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003423 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003424 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3425 }
3426 }
3427 mFocusedDisplayId = displayId;
3428
3429 // Sanity check
3430 sp<InputWindowHandle> newFocusedWindowHandle =
3431 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003432 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003433
Tiger Huang721e26f2018-07-24 22:26:19 +08003434 if (newFocusedWindowHandle == nullptr) {
3435 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3436 if (!mFocusedWindowHandlesByDisplay.empty()) {
3437 ALOGE("But another display has a focused window:");
3438 for (auto& it : mFocusedWindowHandlesByDisplay) {
3439 const int32_t displayId = it.first;
3440 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3442 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003443 }
3444 }
3445 }
3446 }
3447
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003448 if (DEBUG_FOCUS) {
3449 logDispatchStateLocked();
3450 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003451 } // release lock
3452
3453 // Wake up poll loop since it may need to make new input dispatching choices.
3454 mLooper->wake();
3455}
3456
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003458 if (DEBUG_FOCUS) {
3459 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461
3462 bool changed;
3463 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003464 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
3466 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3467 if (mDispatchFrozen && !frozen) {
3468 resetANRTimeoutsLocked();
3469 }
3470
3471 if (mDispatchEnabled && !enabled) {
3472 resetAndDropEverythingLocked("dispatcher is being disabled");
3473 }
3474
3475 mDispatchEnabled = enabled;
3476 mDispatchFrozen = frozen;
3477 changed = true;
3478 } else {
3479 changed = false;
3480 }
3481
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003482 if (DEBUG_FOCUS) {
3483 logDispatchStateLocked();
3484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 } // release lock
3486
3487 if (changed) {
3488 // Wake up poll loop since it may need to make new input dispatching choices.
3489 mLooper->wake();
3490 }
3491}
3492
3493void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003494 if (DEBUG_FOCUS) {
3495 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003499 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
3501 if (mInputFilterEnabled == enabled) {
3502 return;
3503 }
3504
3505 mInputFilterEnabled = enabled;
3506 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3507 } // release lock
3508
3509 // Wake up poll loop since there might be work to do to drop everything.
3510 mLooper->wake();
3511}
3512
chaviwfbe5d9c2018-12-26 12:23:37 -08003513bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3514 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003515 if (DEBUG_FOCUS) {
3516 ALOGD("Trivial transfer to same window.");
3517 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003518 return true;
3519 }
3520
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003522 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523
chaviwfbe5d9c2018-12-26 12:23:37 -08003524 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3525 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003526 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003527 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 return false;
3529 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003530 if (DEBUG_FOCUS) {
3531 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3532 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003535 if (DEBUG_FOCUS) {
3536 ALOGD("Cannot transfer focus because windows are on different displays.");
3537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 return false;
3539 }
3540
3541 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003542 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3543 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3544 for (size_t i = 0; i < state.windows.size(); i++) {
3545 const TouchedWindow& touchedWindow = state.windows[i];
3546 if (touchedWindow.windowHandle == fromWindowHandle) {
3547 int32_t oldTargetFlags = touchedWindow.targetFlags;
3548 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003550 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003552 int32_t newTargetFlags = oldTargetFlags &
3553 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3554 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003555 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556
Jeff Brownf086ddb2014-02-11 14:28:48 -08003557 found = true;
3558 goto Found;
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003562 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003564 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003565 if (DEBUG_FOCUS) {
3566 ALOGD("Focus transfer failed because from window did not have focus.");
3567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568 return false;
3569 }
3570
chaviwfbe5d9c2018-12-26 12:23:37 -08003571 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3572 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003573 sp<Connection> fromConnection = getConnectionLocked(fromChannel);
3574 sp<Connection> toConnection = getConnectionLocked(toChannel);
3575 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003577 CancelationOptions
3578 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3579 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3581 }
3582
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003583 if (DEBUG_FOCUS) {
3584 logDispatchStateLocked();
3585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 } // release lock
3587
3588 // Wake up poll loop since it may need to make new input dispatching choices.
3589 mLooper->wake();
3590 return true;
3591}
3592
3593void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003594 if (DEBUG_FOCUS) {
3595 ALOGD("Resetting and dropping all events (%s).", reason);
3596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597
3598 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3599 synthesizeCancelationEventsForAllConnectionsLocked(options);
3600
3601 resetKeyRepeatLocked();
3602 releasePendingEventLocked();
3603 drainInboundQueueLocked();
3604 resetANRTimeoutsLocked();
3605
Jeff Brownf086ddb2014-02-11 14:28:48 -08003606 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003608 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609}
3610
3611void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 dumpDispatchStateLocked(dump);
3614
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 std::istringstream stream(dump);
3616 std::string line;
3617
3618 while (std::getline(stream, line, '\n')) {
3619 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621}
3622
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003623void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003624 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3625 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3626 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003627 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628
Tiger Huang721e26f2018-07-24 22:26:19 +08003629 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3630 dump += StringPrintf(INDENT "FocusedApplications:\n");
3631 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3632 const int32_t displayId = it.first;
3633 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003634 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3635 ", name='%s', dispatchingTimeout=%0.3fms\n",
3636 displayId, applicationHandle->getName().c_str(),
3637 applicationHandle->getDispatchingTimeout(
3638 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3639 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003642 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003644
3645 if (!mFocusedWindowHandlesByDisplay.empty()) {
3646 dump += StringPrintf(INDENT "FocusedWindows:\n");
3647 for (auto& it : mFocusedWindowHandlesByDisplay) {
3648 const int32_t displayId = it.first;
3649 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003650 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3651 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003652 }
3653 } else {
3654 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656
Jeff Brownf086ddb2014-02-11 14:28:48 -08003657 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003658 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003659 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3660 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003661 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003662 state.displayId, toString(state.down), toString(state.split),
3663 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003664 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003665 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003666 for (size_t i = 0; i < state.windows.size(); i++) {
3667 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003668 dump += StringPrintf(INDENT4
3669 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3670 i, touchedWindow.windowHandle->getName().c_str(),
3671 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003672 }
3673 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003674 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003675 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003676 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003677 dump += INDENT3 "Portal windows:\n";
3678 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003679 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003680 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3681 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003682 }
3683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
3685 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003686 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
3688
Arthur Hungb92218b2018-08-14 12:00:21 +08003689 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003690 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003691 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003692 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003693 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003694 dump += INDENT2 "Windows:\n";
3695 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003696 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003697 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698
Arthur Hungb92218b2018-08-14 12:00:21 +08003699 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003700 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3701 "hasWallpaper=%s, "
3702 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3703 "type=0x%08x, layer=%d, "
3704 "frame=[%d,%d][%d,%d], globalScale=%f, "
3705 "windowScale=(%f,%f), "
3706 "touchableRegion=",
3707 i, windowInfo->name.c_str(), windowInfo->displayId,
3708 windowInfo->portalToDisplayId,
3709 toString(windowInfo->paused),
3710 toString(windowInfo->hasFocus),
3711 toString(windowInfo->hasWallpaper),
3712 toString(windowInfo->visible),
3713 toString(windowInfo->canReceiveKeys),
3714 windowInfo->layoutParamsFlags,
3715 windowInfo->layoutParamsType, windowInfo->layer,
3716 windowInfo->frameLeft, windowInfo->frameTop,
3717 windowInfo->frameRight, windowInfo->frameBottom,
3718 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3719 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003720 dumpRegion(dump, windowInfo->touchableRegion);
3721 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3722 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003723 windowInfo->ownerPid, windowInfo->ownerUid,
3724 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003725 }
3726 } else {
3727 dump += INDENT2 "Windows: <none>\n";
3728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
3730 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003731 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 }
3733
Michael Wright3dd60e22019-03-27 22:06:44 +00003734 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003736 const std::vector<Monitor>& monitors = it.second;
3737 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3738 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739 }
3740 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003741 const std::vector<Monitor>& monitors = it.second;
3742 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3743 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003746 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 }
3748
3749 nsecs_t currentTime = now();
3750
3751 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003752 if (!mRecentQueue.empty()) {
3753 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3754 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003755 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003757 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003760 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 }
3762
3763 // Dump event currently being dispatched.
3764 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003765 dump += INDENT "PendingEvent:\n";
3766 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003768 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003769 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003771 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 }
3773
3774 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003775 if (!mInboundQueue.empty()) {
3776 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3777 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003778 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003780 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 }
3782 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003783 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 }
3785
Michael Wright78f24442014-08-06 15:55:28 -07003786 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003787 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003788 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3789 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3790 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003791 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3792 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003793 }
3794 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003795 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003796 }
3797
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003798 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003799 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003800 for (const auto& pair : mConnectionsByFd) {
3801 const sp<Connection>& connection = pair.second;
3802 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3803 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3804 pair.first, connection->getInputChannelName().c_str(),
3805 connection->getWindowName().c_str(), connection->getStatusLabel(),
3806 toString(connection->monitor),
3807 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003809 if (!connection->outboundQueue.empty()) {
3810 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3811 connection->outboundQueue.size());
3812 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 dump.append(INDENT4);
3814 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003815 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003816 entry->targetFlags, entry->resolvedAction,
3817 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
3819 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003820 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
3822
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003823 if (!connection->waitQueue.empty()) {
3824 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3825 connection->waitQueue.size());
3826 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003827 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003829 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 "age=%0.1fms, wait=%0.1fms\n",
3831 entry->targetFlags, entry->resolvedAction,
3832 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3833 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003836 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 }
3838 }
3839 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003840 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 }
3842
3843 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003844 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003845 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003847 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003850 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003851 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003852 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003853 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854}
3855
Michael Wright3dd60e22019-03-27 22:06:44 +00003856void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3857 const size_t numMonitors = monitors.size();
3858 for (size_t i = 0; i < numMonitors; i++) {
3859 const Monitor& monitor = monitors[i];
3860 const sp<InputChannel>& channel = monitor.inputChannel;
3861 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3862 dump += "\n";
3863 }
3864}
3865
3866status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003867 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003869 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003870 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871#endif
3872
3873 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003874 std::scoped_lock _l(mLock);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003875 sp<Connection> existingConnection = getConnectionLocked(inputChannel);
3876 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003878 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 return BAD_VALUE;
3880 }
3881
Michael Wright3dd60e22019-03-27 22:06:44 +00003882 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883
3884 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003885 mConnectionsByFd[fd] = connection;
Robert Carr5c8a0262018-10-03 16:30:44 -07003886 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3889 } // release lock
3890
3891 // Wake the looper because some connections have changed.
3892 mLooper->wake();
3893 return OK;
3894}
3895
Michael Wright3dd60e22019-03-27 22:06:44 +00003896status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003897 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003898 { // acquire lock
3899 std::scoped_lock _l(mLock);
3900
3901 if (displayId < 0) {
3902 ALOGW("Attempted to register input monitor without a specified display.");
3903 return BAD_VALUE;
3904 }
3905
3906 if (inputChannel->getToken() == nullptr) {
3907 ALOGW("Attempted to register input monitor without an identifying token.");
3908 return BAD_VALUE;
3909 }
3910
3911 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3912
3913 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003914 mConnectionsByFd[fd] = connection;
Michael Wright3dd60e22019-03-27 22:06:44 +00003915 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3916
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003917 auto& monitorsByDisplay =
3918 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003919 monitorsByDisplay[displayId].emplace_back(inputChannel);
3920
3921 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003922 }
3923 // Wake the looper because some connections have changed.
3924 mLooper->wake();
3925 return OK;
3926}
3927
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3929#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003930 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931#endif
3932
3933 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003934 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935
3936 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3937 if (status) {
3938 return status;
3939 }
3940 } // release lock
3941
3942 // Wake the poll loop because removing the connection may have changed the current
3943 // synchronization state.
3944 mLooper->wake();
3945 return OK;
3946}
3947
3948status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949 bool notify) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003950 sp<Connection> connection = getConnectionLocked(inputChannel);
3951 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003953 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 return BAD_VALUE;
3955 }
3956
John Recke0710582019-09-26 13:46:12 -07003957 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003958 ALOG_ASSERT(removed);
Robert Carr5c8a0262018-10-03 16:30:44 -07003959 mInputChannelsByToken.erase(inputChannel->getToken());
3960
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 if (connection->monitor) {
3962 removeMonitorChannelLocked(inputChannel);
3963 }
3964
3965 mLooper->removeFd(inputChannel->getFd());
3966
3967 nsecs_t currentTime = now();
3968 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3969
3970 connection->status = Connection::STATUS_ZOMBIE;
3971 return OK;
3972}
3973
3974void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003975 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3976 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3977}
3978
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003979void InputDispatcher::removeMonitorChannelLocked(
3980 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00003981 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003983 std::vector<Monitor>& monitors = it->second;
3984 const size_t numMonitors = monitors.size();
3985 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003986 if (monitors[i].inputChannel == inputChannel) {
3987 monitors.erase(monitors.begin() + i);
3988 break;
3989 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003990 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003991 if (monitors.empty()) {
3992 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003993 } else {
3994 ++it;
3995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997}
3998
Michael Wright3dd60e22019-03-27 22:06:44 +00003999status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4000 { // acquire lock
4001 std::scoped_lock _l(mLock);
4002 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4003
4004 if (!foundDisplayId) {
4005 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4006 return BAD_VALUE;
4007 }
4008 int32_t displayId = foundDisplayId.value();
4009
4010 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4011 if (stateIndex < 0) {
4012 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4013 return BAD_VALUE;
4014 }
4015
4016 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4017 std::optional<int32_t> foundDeviceId;
4018 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
4019 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
4020 foundDeviceId = state.deviceId;
4021 }
4022 }
4023 if (!foundDeviceId || !state.down) {
4024 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004026 return BAD_VALUE;
4027 }
4028 int32_t deviceId = foundDeviceId.value();
4029
4030 // Send cancel events to all the input channels we're stealing from.
4031 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004032 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004033 options.deviceId = deviceId;
4034 options.displayId = displayId;
4035 for (const TouchedWindow& window : state.windows) {
4036 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4037 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4038 }
4039 // Then clear the current touch state so we stop dispatching to them as well.
4040 state.filterNonMonitors();
4041 }
4042 return OK;
4043}
4044
Michael Wright3dd60e22019-03-27 22:06:44 +00004045std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4046 const sp<IBinder>& token) {
4047 for (const auto& it : mGestureMonitorsByDisplay) {
4048 const std::vector<Monitor>& monitors = it.second;
4049 for (const Monitor& monitor : monitors) {
4050 if (monitor.inputChannel->getToken() == token) {
4051 return it.first;
4052 }
4053 }
4054 }
4055 return std::nullopt;
4056}
4057
Garfield Tane84e6f92019-08-29 17:28:41 -07004058sp<Connection> InputDispatcher::getConnectionLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004059 if (inputChannel == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004060 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004061 }
4062
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004063 for (const auto& pair : mConnectionsByFd) {
4064 sp<Connection> connection = pair.second;
Robert Carr4e670e52018-08-15 13:26:12 -07004065 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004066 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 }
4068 }
Robert Carr4e670e52018-08-15 13:26:12 -07004069
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004070 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071}
4072
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4074 const sp<Connection>& connection, uint32_t seq,
4075 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004076 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4077 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 commandEntry->connection = connection;
4079 commandEntry->eventTime = currentTime;
4080 commandEntry->seq = seq;
4081 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004082 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083}
4084
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4086 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004088 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004090 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4091 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004093 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094}
4095
chaviw0c06c6e2019-01-09 13:27:07 -08004096void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004098 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4099 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004100 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4101 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004102 commandEntry->oldToken = oldToken;
4103 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004104 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004105}
4106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004107void InputDispatcher::onANRLocked(nsecs_t currentTime,
4108 const sp<InputApplicationHandle>& applicationHandle,
4109 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4110 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4112 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4113 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004114 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4115 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4116 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
4118 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004119 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 struct tm tm;
4121 localtime_r(&t, &tm);
4122 char timestr[64];
4123 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4124 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004125 mLastANRState += INDENT "ANR:\n";
4126 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 mLastANRState +=
4128 StringPrintf(INDENT2 "Window: %s\n",
4129 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004130 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4131 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4132 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 dumpDispatchStateLocked(mLastANRState);
4134
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004135 std::unique_ptr<CommandEntry> commandEntry =
4136 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 commandEntry->inputChannel =
4139 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004141 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142}
4143
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 mLock.unlock();
4146
4147 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4148
4149 mLock.lock();
4150}
4151
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 sp<Connection> connection = commandEntry->connection;
4154
4155 if (connection->status != Connection::STATUS_ZOMBIE) {
4156 mLock.unlock();
4157
Robert Carr803535b2018-08-02 16:38:15 -07004158 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159
4160 mLock.lock();
4161 }
4162}
4163
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004164void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004165 sp<IBinder> oldToken = commandEntry->oldToken;
4166 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004167 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004168 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004169 mLock.lock();
4170}
4171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 mLock.unlock();
4174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 nsecs_t newTimeout =
4176 mPolicy->notifyANR(commandEntry->inputApplicationHandle,
4177 commandEntry->inputChannel ? commandEntry->inputChannel->getToken()
4178 : nullptr,
4179 commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
4181 mLock.lock();
4182
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184}
4185
4186void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4187 CommandEntry* commandEntry) {
4188 KeyEntry* entry = commandEntry->keyEntry;
4189
4190 KeyEvent event;
4191 initializeKeyEvent(&event, entry);
4192
4193 mLock.unlock();
4194
Michael Wright2b3c3302018-03-02 17:19:13 +00004195 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 sp<IBinder> token = commandEntry->inputChannel != nullptr
4197 ? commandEntry->inputChannel->getToken()
4198 : nullptr;
4199 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004200 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4201 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
4205 mLock.lock();
4206
4207 if (delay < 0) {
4208 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4209 } else if (!delay) {
4210 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4211 } else {
4212 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4213 entry->interceptKeyWakeupTime = now() + delay;
4214 }
4215 entry->release();
4216}
4217
chaviwfd6d3512019-03-25 13:23:49 -07004218void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4219 mLock.unlock();
4220 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4221 mLock.lock();
4222}
4223
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004226 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004228 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229
4230 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004231 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004232 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004233 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004235 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004236
4237 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4238 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4239 std::string msg =
4240 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4241 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4242 dispatchEntry->eventEntry->appendDescription(msg);
4243 ALOGI("%s", msg.c_str());
4244 }
4245
4246 bool restartEvent;
4247 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4248 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4249 restartEvent =
4250 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
4251 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4252 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4253 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4254 handled);
4255 } else {
4256 restartEvent = false;
4257 }
4258
4259 // Dequeue the event and start the next cycle.
4260 // Note that because the lock might have been released, it is possible that the
4261 // contents of the wait queue to have been drained, so we need to double-check
4262 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004263 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4264 if (dispatchEntryIt != connection->waitQueue.end()) {
4265 dispatchEntry = *dispatchEntryIt;
4266 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004267 traceWaitQueueLength(connection);
4268 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004269 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004270 traceOutboundQueueLength(connection);
4271 } else {
4272 releaseDispatchEntry(dispatchEntry);
4273 }
4274 }
4275
4276 // Start the next dispatch cycle for this connection.
4277 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278}
4279
4280bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 DispatchEntry* dispatchEntry,
4282 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004283 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004284 if (!handled) {
4285 // Report the key as unhandled, since the fallback was not handled.
4286 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4287 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004288 return false;
4289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004291 // Get the fallback key state.
4292 // Clear it out after dispatching the UP.
4293 int32_t originalKeyCode = keyEntry->keyCode;
4294 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4295 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4296 connection->inputState.removeFallbackKey(originalKeyCode);
4297 }
4298
4299 if (handled || !dispatchEntry->hasForegroundTarget()) {
4300 // If the application handles the original key for which we previously
4301 // generated a fallback or if the window is not a foreground window,
4302 // then cancel the associated fallback key, if any.
4303 if (fallbackKeyCode != -1) {
4304 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004306 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004307 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4308 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4309 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310#endif
4311 KeyEvent event;
4312 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004313 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314
4315 mLock.unlock();
4316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4318 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
4320 mLock.lock();
4321
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004322 // Cancel the fallback key.
4323 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004325 "application handled the original non-fallback key "
4326 "or is no longer a foreground target, "
4327 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 options.keyCode = fallbackKeyCode;
4329 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004331 connection->inputState.removeFallbackKey(originalKeyCode);
4332 }
4333 } else {
4334 // If the application did not handle a non-fallback key, first check
4335 // that we are in a good state to perform unhandled key event processing
4336 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004338 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004340 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004341 "since this is not an initial down. "
4342 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4343 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004345 return false;
4346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004348 // Dispatch the unhandled key to the policy.
4349#if DEBUG_OUTBOUND_EVENT_DETAILS
4350 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4352 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004353#endif
4354 KeyEvent event;
4355 initializeKeyEvent(&event, keyEntry);
4356
4357 mLock.unlock();
4358
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4360 keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004361
4362 mLock.lock();
4363
4364 if (connection->status != Connection::STATUS_NORMAL) {
4365 connection->inputState.removeFallbackKey(originalKeyCode);
4366 return false;
4367 }
4368
4369 // Latch the fallback keycode for this key on an initial down.
4370 // The fallback keycode cannot change at any other point in the lifecycle.
4371 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004373 fallbackKeyCode = event.getKeyCode();
4374 } else {
4375 fallbackKeyCode = AKEYCODE_UNKNOWN;
4376 }
4377 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4378 }
4379
4380 ALOG_ASSERT(fallbackKeyCode != -1);
4381
4382 // Cancel the fallback key if the policy decides not to send it anymore.
4383 // We will continue to dispatch the key to the policy but we will no
4384 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4386 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004387#if DEBUG_OUTBOUND_EVENT_DETAILS
4388 if (fallback) {
4389 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390 "as a fallback for %d, but on the DOWN it had requested "
4391 "to send %d instead. Fallback canceled.",
4392 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004393 } else {
4394 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004395 "but on the DOWN it had requested to send %d. "
4396 "Fallback canceled.",
4397 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004398 }
4399#endif
4400
4401 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4402 "canceling fallback, policy no longer desires it");
4403 options.keyCode = fallbackKeyCode;
4404 synthesizeCancelationEventsForConnectionLocked(connection, options);
4405
4406 fallback = false;
4407 fallbackKeyCode = AKEYCODE_UNKNOWN;
4408 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004410 }
4411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412
4413#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004414 {
4415 std::string msg;
4416 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4417 connection->inputState.getFallbackKeys();
4418 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004421 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004423 }
4424#endif
4425
4426 if (fallback) {
4427 // Restart the dispatch cycle using the fallback key.
4428 keyEntry->eventTime = event.getEventTime();
4429 keyEntry->deviceId = event.getDeviceId();
4430 keyEntry->source = event.getSource();
4431 keyEntry->displayId = event.getDisplayId();
4432 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4433 keyEntry->keyCode = fallbackKeyCode;
4434 keyEntry->scanCode = event.getScanCode();
4435 keyEntry->metaState = event.getMetaState();
4436 keyEntry->repeatCount = event.getRepeatCount();
4437 keyEntry->downTime = event.getDownTime();
4438 keyEntry->syntheticRepeat = false;
4439
4440#if DEBUG_OUTBOUND_EVENT_DETAILS
4441 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4443 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004444#endif
4445 return true; // restart the event
4446 } else {
4447#if DEBUG_OUTBOUND_EVENT_DETAILS
4448 ALOGD("Unhandled key event: No fallback key.");
4449#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004450
4451 // Report the key as unhandled, since there is no fallback key.
4452 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454 }
4455 return false;
4456}
4457
4458bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 DispatchEntry* dispatchEntry,
4460 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 return false;
4462}
4463
4464void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4465 mLock.unlock();
4466
4467 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4468
4469 mLock.lock();
4470}
4471
4472void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004473 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4475 entry->downTime, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476}
4477
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004478void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004479 int32_t injectionResult,
4480 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 // TODO Write some statistics about how long we spend waiting.
4482}
4483
4484void InputDispatcher::traceInboundQueueLengthLocked() {
4485 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004486 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
4488}
4489
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004490void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 if (ATRACE_ENABLED()) {
4492 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004493 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004494 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 }
4496}
4497
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004498void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 if (ATRACE_ENABLED()) {
4500 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004501 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004502 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 }
4504}
4505
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004506void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004507 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004509 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 dumpDispatchStateLocked(dump);
4511
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004512 if (!mLastANRState.empty()) {
4513 dump += "\nInput Dispatcher State at time of last ANR:\n";
4514 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516}
4517
4518void InputDispatcher::monitor() {
4519 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004520 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004522 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523}
4524
Garfield Tane84e6f92019-08-29 17:28:41 -07004525} // namespace android::inputdispatcher