blob: 2ffd0a800b25f342b607eebfa87274c41f4f320f [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
20//#define LOG_NDEBUG 0
21
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.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
49#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080050#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070051#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <unistd.h>
54
Michael Wright2b3c3302018-03-02 17:19:13 +000055#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <utils/Trace.h>
59#include <powermanager/PowerManager.h>
60#include <ui/Region.h>
Robert Carr4e670e52018-08-15 13:26:12 -070061#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66#define INDENT4 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// Default input dispatching timeout if there is no focused application or paused window
73// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000074constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Amount of time to allow for all pending events to be processed when an app switch
77// key is on the way. This is used to preempt input dispatch and drop input events
78// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000079constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Amount of time to allow for an event to be dispatched (measured since its eventTime)
82// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow touch events to be streamed out to a connection before requiring
86// that the first event be finished. This value extends the ANR timeout by the specified
87// amount. For example, if streaming is allowed to get ahead by one second relative to the
88// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// 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 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
99
Prabir Pradhan42611e02018-11-27 14:04:02 -0800100// Sequence number for synthesized or injected events.
101constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104static inline nsecs_t now() {
105 return systemTime(SYSTEM_TIME_MONOTONIC);
106}
107
108static inline const char* toString(bool value) {
109 return value ? "true" : "false";
110}
111
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800112static std::string motionActionToString(int32_t action) {
113 // Convert MotionEvent action to string
114 switch(action & AMOTION_EVENT_ACTION_MASK) {
115 case AMOTION_EVENT_ACTION_DOWN:
116 return "DOWN";
117 case AMOTION_EVENT_ACTION_MOVE:
118 return "MOVE";
119 case AMOTION_EVENT_ACTION_UP:
120 return "UP";
121 case AMOTION_EVENT_ACTION_POINTER_DOWN:
122 return "POINTER_DOWN";
123 case AMOTION_EVENT_ACTION_POINTER_UP:
124 return "POINTER_UP";
125 }
126 return StringPrintf("%" PRId32, action);
127}
128
129static std::string keyActionToString(int32_t action) {
130 // Convert KeyEvent action to string
131 switch(action) {
132 case AKEY_EVENT_ACTION_DOWN:
133 return "DOWN";
134 case AKEY_EVENT_ACTION_UP:
135 return "UP";
136 case AKEY_EVENT_ACTION_MULTIPLE:
137 return "MULTIPLE";
138 }
139 return StringPrintf("%" PRId32, action);
140}
141
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
143 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
144 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
145}
146
147static bool isValidKeyAction(int32_t action) {
148 switch (action) {
149 case AKEY_EVENT_ACTION_DOWN:
150 case AKEY_EVENT_ACTION_UP:
151 return true;
152 default:
153 return false;
154 }
155}
156
157static bool validateKeyEvent(int32_t action) {
158 if (! isValidKeyAction(action)) {
159 ALOGE("Key event has invalid action code 0x%x", action);
160 return false;
161 }
162 return true;
163}
164
Michael Wright7b159c92015-05-14 14:48:03 +0100165static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 switch (action & AMOTION_EVENT_ACTION_MASK) {
167 case AMOTION_EVENT_ACTION_DOWN:
168 case AMOTION_EVENT_ACTION_UP:
169 case AMOTION_EVENT_ACTION_CANCEL:
170 case AMOTION_EVENT_ACTION_MOVE:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
172 case AMOTION_EVENT_ACTION_HOVER_ENTER:
173 case AMOTION_EVENT_ACTION_HOVER_MOVE:
174 case AMOTION_EVENT_ACTION_HOVER_EXIT:
175 case AMOTION_EVENT_ACTION_SCROLL:
176 return true;
177 case AMOTION_EVENT_ACTION_POINTER_DOWN:
178 case AMOTION_EVENT_ACTION_POINTER_UP: {
179 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800180 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 }
Michael Wright7b159c92015-05-14 14:48:03 +0100182 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
183 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
184 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 default:
186 return false;
187 }
188}
189
Michael Wright7b159c92015-05-14 14:48:03 +0100190static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100192 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 ALOGE("Motion event has invalid action code 0x%x", action);
194 return false;
195 }
196 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000197 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 pointerCount, MAX_POINTERS);
199 return false;
200 }
201 BitSet32 pointerIdBits;
202 for (size_t i = 0; i < pointerCount; i++) {
203 int32_t id = pointerProperties[i].id;
204 if (id < 0 || id > MAX_POINTER_ID) {
205 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
206 id, MAX_POINTER_ID);
207 return false;
208 }
209 if (pointerIdBits.hasBit(id)) {
210 ALOGE("Motion event has duplicate pointer id %d", id);
211 return false;
212 }
213 pointerIdBits.markBit(id);
214 }
215 return true;
216}
217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return;
222 }
223
224 bool first = true;
225 Region::const_iterator cur = region.begin();
226 Region::const_iterator const tail = region.end();
227 while (cur != tail) {
228 if (first) {
229 first = false;
230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800231 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 cur++;
235 }
236}
237
Tiger Huang721e26f2018-07-24 22:26:19 +0800238template<typename T, typename U>
239static T getValueByKey(std::unordered_map<U, T>& map, U key) {
240 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
241 return it != map.end() ? it->second : T{};
242}
243
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
245// --- InputDispatcher ---
246
247InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
248 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700249 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100250 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700251 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800253 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
255 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800256 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257
Yi Kong9b14ac62018-07-17 13:48:38 -0700258 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
260 policy->getDispatcherConfiguration(&mConfig);
261}
262
263InputDispatcher::~InputDispatcher() {
264 { // acquire lock
265 AutoMutex _l(mLock);
266
267 resetKeyRepeatLocked();
268 releasePendingEventLocked();
269 drainInboundQueueLocked();
270 }
271
272 while (mConnectionsByFd.size() != 0) {
273 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
274 }
275}
276
277void InputDispatcher::dispatchOnce() {
278 nsecs_t nextWakeupTime = LONG_LONG_MAX;
279 { // acquire lock
280 AutoMutex _l(mLock);
281 mDispatcherIsAliveCondition.broadcast();
282
283 // Run a dispatch loop if there are no pending commands.
284 // The dispatch loop might enqueue commands to run afterwards.
285 if (!haveCommandsLocked()) {
286 dispatchOnceInnerLocked(&nextWakeupTime);
287 }
288
289 // Run all pending commands if there are any.
290 // If any commands were run then force the next poll to wake up immediately.
291 if (runCommandsLockedInterruptible()) {
292 nextWakeupTime = LONG_LONG_MIN;
293 }
294 } // release lock
295
296 // Wait for callback or timeout or wake. (make sure we round up, not down)
297 nsecs_t currentTime = now();
298 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
299 mLooper->pollOnce(timeoutMillis);
300}
301
302void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
303 nsecs_t currentTime = now();
304
Jeff Browndc5992e2014-04-11 01:27:26 -0700305 // Reset the key repeat timer whenever normal dispatch is suspended while the
306 // device is in a non-interactive state. This is to ensure that we abort a key
307 // repeat if the device is just coming out of sleep.
308 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 resetKeyRepeatLocked();
310 }
311
312 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
313 if (mDispatchFrozen) {
314#if DEBUG_FOCUS
315 ALOGD("Dispatch frozen. Waiting some more.");
316#endif
317 return;
318 }
319
320 // Optimize latency of app switches.
321 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
322 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
323 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
324 if (mAppSwitchDueTime < *nextWakeupTime) {
325 *nextWakeupTime = mAppSwitchDueTime;
326 }
327
328 // Ready to start a new event.
329 // If we don't already have a pending event, go grab one.
330 if (! mPendingEvent) {
331 if (mInboundQueue.isEmpty()) {
332 if (isAppSwitchDue) {
333 // The inbound queue is empty so the app switch key we were waiting
334 // for will never arrive. Stop waiting for it.
335 resetPendingAppSwitchLocked(false);
336 isAppSwitchDue = false;
337 }
338
339 // Synthesize a key repeat if appropriate.
340 if (mKeyRepeatState.lastKeyEntry) {
341 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
342 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
343 } else {
344 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
345 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
346 }
347 }
348 }
349
350 // Nothing to do if there is no pending event.
351 if (!mPendingEvent) {
352 return;
353 }
354 } else {
355 // Inbound queue has at least one entry.
356 mPendingEvent = mInboundQueue.dequeueAtHead();
357 traceInboundQueueLengthLocked();
358 }
359
360 // Poke user activity for this event.
361 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
362 pokeUserActivityLocked(mPendingEvent);
363 }
364
365 // Get ready to dispatch the event.
366 resetANRTimeoutsLocked();
367 }
368
369 // Now we have an event to dispatch.
370 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700371 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 bool done = false;
373 DropReason dropReason = DROP_REASON_NOT_DROPPED;
374 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
375 dropReason = DROP_REASON_POLICY;
376 } else if (!mDispatchEnabled) {
377 dropReason = DROP_REASON_DISABLED;
378 }
379
380 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700381 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
384 switch (mPendingEvent->type) {
385 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
386 ConfigurationChangedEntry* typedEntry =
387 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
388 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_DEVICE_RESET: {
394 DeviceResetEntry* typedEntry =
395 static_cast<DeviceResetEntry*>(mPendingEvent);
396 done = dispatchDeviceResetLocked(currentTime, typedEntry);
397 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
398 break;
399 }
400
401 case EventEntry::TYPE_KEY: {
402 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
403 if (isAppSwitchDue) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800404 if (isAppSwitchKeyEvent(typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 resetPendingAppSwitchLocked(true);
406 isAppSwitchDue = false;
407 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
408 dropReason = DROP_REASON_APP_SWITCH;
409 }
410 }
411 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800412 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 dropReason = DROP_REASON_STALE;
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
416 dropReason = DROP_REASON_BLOCKED;
417 }
418 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
419 break;
420 }
421
422 case EventEntry::TYPE_MOTION: {
423 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
424 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
425 dropReason = DROP_REASON_APP_SWITCH;
426 }
427 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800428 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry,
435 &dropReason, nextWakeupTime);
436 break;
437 }
438
439 default:
440 ALOG_ASSERT(false);
441 break;
442 }
443
444 if (done) {
445 if (dropReason != DROP_REASON_NOT_DROPPED) {
446 dropInboundEventLocked(mPendingEvent, dropReason);
447 }
Michael Wright3a981722015-06-10 15:26:13 +0100448 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 releasePendingEventLocked();
451 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
452 }
453}
454
455bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
456 bool needWake = mInboundQueue.isEmpty();
457 mInboundQueue.enqueueAtTail(entry);
458 traceInboundQueueLengthLocked();
459
460 switch (entry->type) {
461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
465 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800466 if (isAppSwitchKeyEvent(keyEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
468 mAppSwitchSawKeyDown = true;
469 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
470 if (mAppSwitchSawKeyDown) {
471#if DEBUG_APP_SWITCH
472 ALOGD("App switch is pending!");
473#endif
474 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
490 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
491 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700492 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 int32_t displayId = motionEntry->displayId;
494 int32_t x = int32_t(motionEntry->pointerCoords[0].
495 getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y = int32_t(motionEntry->pointerCoords[0].
497 getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700499 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700500 && touchedWindowHandle->getApplicationToken()
501 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 // 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;
505 needWake = true;
506 }
507 }
508 break;
509 }
510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
517 mRecentQueue.enqueueAtTail(entry);
518 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.dequeueAtHead()->release();
520 }
521}
522
523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800524 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800526 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
527 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800529 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
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)) {
536 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
537 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
538 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800539 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
540 if (portalToDisplayId != ADISPLAY_ID_NONE
541 && portalToDisplayId != displayId) {
542 if (addPortalWindows) {
543 // For the monitoring channels of the display.
544 mTempTouchState.addPortalWindow(windowHandle);
545 }
546 return findTouchedWindowAtLocked(
547 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 // Found window.
550 return windowHandle;
551 }
552 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800553
554 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
555 mTempTouchState.addOrUpdateWindow(
556 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 }
560 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700561 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562}
563
564void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
565 const char* reason;
566 switch (dropReason) {
567 case DROP_REASON_POLICY:
568#if DEBUG_INBOUND_EVENT_DETAILS
569 ALOGD("Dropped event because policy consumed it.");
570#endif
571 reason = "inbound event was dropped because the policy consumed it";
572 break;
573 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100574 if (mLastDropReason != DROP_REASON_DISABLED) {
575 ALOGI("Dropped event because input dispatch is disabled.");
576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 reason = "inbound event was dropped because input dispatch is disabled";
578 break;
579 case DROP_REASON_APP_SWITCH:
580 ALOGI("Dropped event because of pending overdue app switch.");
581 reason = "inbound event was dropped because of pending overdue app switch";
582 break;
583 case DROP_REASON_BLOCKED:
584 ALOGI("Dropped event because the current application is not responding and the user "
585 "has started interacting with a different application.");
586 reason = "inbound event was dropped because the current application is not responding "
587 "and the user has started interacting with a different application";
588 break;
589 case DROP_REASON_STALE:
590 ALOGI("Dropped event because it is stale.");
591 reason = "inbound event was dropped because it is stale";
592 break;
593 default:
594 ALOG_ASSERT(false);
595 return;
596 }
597
598 switch (entry->type) {
599 case EventEntry::TYPE_KEY: {
600 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
601 synthesizeCancelationEventsForAllConnectionsLocked(options);
602 break;
603 }
604 case EventEntry::TYPE_MOTION: {
605 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
606 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
607 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
608 synthesizeCancelationEventsForAllConnectionsLocked(options);
609 } else {
610 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
611 synthesizeCancelationEventsForAllConnectionsLocked(options);
612 }
613 break;
614 }
615 }
616}
617
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800618static bool isAppSwitchKeyCode(int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619 return keyCode == AKEYCODE_HOME
620 || keyCode == AKEYCODE_ENDCALL
621 || keyCode == AKEYCODE_APP_SWITCH;
622}
623
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800624bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
626 && isAppSwitchKeyCode(keyEntry->keyCode)
627 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
628 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
629}
630
631bool InputDispatcher::isAppSwitchPendingLocked() {
632 return mAppSwitchDueTime != LONG_LONG_MAX;
633}
634
635void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
636 mAppSwitchDueTime = LONG_LONG_MAX;
637
638#if DEBUG_APP_SWITCH
639 if (handled) {
640 ALOGD("App switch has arrived.");
641 } else {
642 ALOGD("App switch was abandoned.");
643 }
644#endif
645}
646
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800647bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
649}
650
651bool InputDispatcher::haveCommandsLocked() const {
652 return !mCommandQueue.isEmpty();
653}
654
655bool InputDispatcher::runCommandsLockedInterruptible() {
656 if (mCommandQueue.isEmpty()) {
657 return false;
658 }
659
660 do {
661 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
662
663 Command command = commandEntry->command;
664 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
665
666 commandEntry->connection.clear();
667 delete commandEntry;
668 } while (! mCommandQueue.isEmpty());
669 return true;
670}
671
672InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
673 CommandEntry* commandEntry = new CommandEntry(command);
674 mCommandQueue.enqueueAtTail(commandEntry);
675 return commandEntry;
676}
677
678void InputDispatcher::drainInboundQueueLocked() {
679 while (! mInboundQueue.isEmpty()) {
680 EventEntry* entry = mInboundQueue.dequeueAtHead();
681 releaseInboundEventLocked(entry);
682 }
683 traceInboundQueueLengthLocked();
684}
685
686void InputDispatcher::releasePendingEventLocked() {
687 if (mPendingEvent) {
688 resetANRTimeoutsLocked();
689 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700690 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 }
692}
693
694void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
695 InjectionState* injectionState = entry->injectionState;
696 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
697#if DEBUG_DISPATCH_CYCLE
698 ALOGD("Injected inbound event was dropped.");
699#endif
700 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
701 }
702 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700703 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
705 addRecentEventLocked(entry);
706 entry->release();
707}
708
709void InputDispatcher::resetKeyRepeatLocked() {
710 if (mKeyRepeatState.lastKeyEntry) {
711 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700712 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 }
714}
715
716InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
717 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
718
719 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700720 uint32_t policyFlags = entry->policyFlags &
721 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 if (entry->refCount == 1) {
723 entry->recycle();
724 entry->eventTime = currentTime;
725 entry->policyFlags = policyFlags;
726 entry->repeatCount += 1;
727 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800728 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100729 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 entry->action, entry->flags, entry->keyCode, entry->scanCode,
731 entry->metaState, entry->repeatCount + 1, entry->downTime);
732
733 mKeyRepeatState.lastKeyEntry = newEntry;
734 entry->release();
735
736 entry = newEntry;
737 }
738 entry->syntheticRepeat = true;
739
740 // Increment reference count since we keep a reference to the event in
741 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
742 entry->refCount += 1;
743
744 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
745 return entry;
746}
747
748bool InputDispatcher::dispatchConfigurationChangedLocked(
749 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
750#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700751 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752#endif
753
754 // Reset key repeating in case a keyboard device was added or removed or something.
755 resetKeyRepeatLocked();
756
757 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
758 CommandEntry* commandEntry = postCommandLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800759 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 commandEntry->eventTime = entry->eventTime;
761 return true;
762}
763
764bool InputDispatcher::dispatchDeviceResetLocked(
765 nsecs_t currentTime, DeviceResetEntry* entry) {
766#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700767 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
768 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769#endif
770
771 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
772 "device was reset");
773 options.deviceId = entry->deviceId;
774 synthesizeCancelationEventsForAllConnectionsLocked(options);
775 return true;
776}
777
778bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
779 DropReason* dropReason, nsecs_t* nextWakeupTime) {
780 // Preprocessing.
781 if (! entry->dispatchInProgress) {
782 if (entry->repeatCount == 0
783 && entry->action == AKEY_EVENT_ACTION_DOWN
784 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
785 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
786 if (mKeyRepeatState.lastKeyEntry
787 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
788 // We have seen two identical key downs in a row which indicates that the device
789 // driver is automatically generating key repeats itself. We take note of the
790 // repeat here, but we disable our own next key repeat timer since it is clear that
791 // we will not need to synthesize key repeats ourselves.
792 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
793 resetKeyRepeatLocked();
794 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
795 } else {
796 // Not a repeat. Save key down state in case we do see a repeat later.
797 resetKeyRepeatLocked();
798 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
799 }
800 mKeyRepeatState.lastKeyEntry = entry;
801 entry->refCount += 1;
802 } else if (! entry->syntheticRepeat) {
803 resetKeyRepeatLocked();
804 }
805
806 if (entry->repeatCount == 1) {
807 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
808 } else {
809 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
810 }
811
812 entry->dispatchInProgress = true;
813
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800814 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 }
816
817 // Handle case where the policy asked us to try again later last time.
818 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
819 if (currentTime < entry->interceptKeyWakeupTime) {
820 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
821 *nextWakeupTime = entry->interceptKeyWakeupTime;
822 }
823 return false; // wait until next wakeup
824 }
825 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
826 entry->interceptKeyWakeupTime = 0;
827 }
828
829 // Give the policy a chance to intercept the key.
830 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
831 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
832 CommandEntry* commandEntry = postCommandLocked(
833 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800834 sp<InputWindowHandle> focusedWindowHandle =
835 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
836 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700837 commandEntry->inputChannel =
838 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
840 commandEntry->keyEntry = entry;
841 entry->refCount += 1;
842 return false; // wait for the command to run
843 } else {
844 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
845 }
846 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
847 if (*dropReason == DROP_REASON_NOT_DROPPED) {
848 *dropReason = DROP_REASON_POLICY;
849 }
850 }
851
852 // Clean up if dropping the event.
853 if (*dropReason != DROP_REASON_NOT_DROPPED) {
854 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
855 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800856 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 return true;
858 }
859
860 // Identify targets.
861 Vector<InputTarget> inputTargets;
862 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
863 entry, inputTargets, nextWakeupTime);
864 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
865 return false;
866 }
867
868 setInjectionResultLocked(entry, injectionResult);
869 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
870 return true;
871 }
872
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800873 // Add monitor channels from event's or focused display.
874 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875
876 // Dispatch the key.
877 dispatchEventLocked(currentTime, entry, inputTargets);
878 return true;
879}
880
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800881void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100883 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
884 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800885 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100887 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800889 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890#endif
891}
892
893bool InputDispatcher::dispatchMotionLocked(
894 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
895 // Preprocessing.
896 if (! entry->dispatchInProgress) {
897 entry->dispatchInProgress = true;
898
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800899 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
901
902 // Clean up if dropping the event.
903 if (*dropReason != DROP_REASON_NOT_DROPPED) {
904 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
905 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
906 return true;
907 }
908
909 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
910
911 // Identify targets.
912 Vector<InputTarget> inputTargets;
913
914 bool conflictingPointerActions = false;
915 int32_t injectionResult;
916 if (isPointerEvent) {
917 // Pointer event. (eg. touchscreen)
918 injectionResult = findTouchedWindowTargetsLocked(currentTime,
919 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
920 } else {
921 // Non touch event. (eg. trackball)
922 injectionResult = findFocusedWindowTargetsLocked(currentTime,
923 entry, inputTargets, nextWakeupTime);
924 }
925 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
926 return false;
927 }
928
929 setInjectionResultLocked(entry, injectionResult);
930 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100931 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
932 CancelationOptions::Mode mode(isPointerEvent ?
933 CancelationOptions::CANCEL_POINTER_EVENTS :
934 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
935 CancelationOptions options(mode, "input event injection failed");
936 synthesizeCancelationEventsForMonitorsLocked(options);
937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 return true;
939 }
940
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800941 // Add monitor channels from event's or focused display.
942 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800944 if (isPointerEvent) {
945 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
946 if (stateIndex >= 0) {
947 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
948 if (!state.portalWindows.isEmpty()) {
949 // The event has gone through these portal windows, so we add monitoring targets of
950 // the corresponding displays as well.
951 for (size_t i = 0; i < state.portalWindows.size(); i++) {
952 const InputWindowInfo* windowInfo = state.portalWindows.itemAt(i)->getInfo();
953 addMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
954 -windowInfo->frameLeft, -windowInfo->frameTop);
955 }
956 }
957 }
958 }
959
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 // Dispatch the motion.
961 if (conflictingPointerActions) {
962 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
963 "conflicting pointer actions");
964 synthesizeCancelationEventsForAllConnectionsLocked(options);
965 }
966 dispatchEventLocked(currentTime, entry, inputTargets);
967 return true;
968}
969
970
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800971void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800973 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
974 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100975 "action=0x%x, actionButton=0x%x, flags=0x%x, "
976 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800977 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800979 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100980 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 entry->metaState, entry->buttonState,
982 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800983 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984
985 for (uint32_t i = 0; i < entry->pointerCount; i++) {
986 ALOGD(" Pointer %d: id=%d, toolType=%d, "
987 "x=%f, y=%f, pressure=%f, size=%f, "
988 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800989 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 i, entry->pointerProperties[i].id,
991 entry->pointerProperties[i].toolType,
992 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
993 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
994 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
995 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
996 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
997 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
998 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
999 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001000 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002#endif
1003}
1004
1005void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1006 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
1007#if DEBUG_DISPATCH_CYCLE
1008 ALOGD("dispatchEventToCurrentInputTargets");
1009#endif
1010
1011 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1012
1013 pokeUserActivityLocked(eventEntry);
1014
1015 for (size_t i = 0; i < inputTargets.size(); i++) {
1016 const InputTarget& inputTarget = inputTargets.itemAt(i);
1017
1018 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1019 if (connectionIndex >= 0) {
1020 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1021 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1022 } else {
1023#if DEBUG_FOCUS
1024 ALOGD("Dropping event delivery to target with channel '%s' because it "
1025 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001026 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027#endif
1028 }
1029 }
1030}
1031
1032int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1033 const EventEntry* entry,
1034 const sp<InputApplicationHandle>& applicationHandle,
1035 const sp<InputWindowHandle>& windowHandle,
1036 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001037 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1039#if DEBUG_FOCUS
1040 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1041#endif
1042 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1043 mInputTargetWaitStartTime = currentTime;
1044 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1045 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001046 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048 } else {
1049 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1050#if DEBUG_FOCUS
1051 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001052 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 reason);
1054#endif
1055 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001056 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001058 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 timeout = applicationHandle->getDispatchingTimeout(
1060 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1061 } else {
1062 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1063 }
1064
1065 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1066 mInputTargetWaitStartTime = currentTime;
1067 mInputTargetWaitTimeoutTime = currentTime + timeout;
1068 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001069 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070
Yi Kong9b14ac62018-07-17 13:48:38 -07001071 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001072 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
Robert Carr740167f2018-10-11 19:03:41 -07001074 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1075 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 }
1077 }
1078 }
1079
1080 if (mInputTargetWaitTimeoutExpired) {
1081 return INPUT_EVENT_INJECTION_TIMED_OUT;
1082 }
1083
1084 if (currentTime >= mInputTargetWaitTimeoutTime) {
1085 onANRLocked(currentTime, applicationHandle, windowHandle,
1086 entry->eventTime, mInputTargetWaitStartTime, reason);
1087
1088 // Force poll loop to wake up immediately on next iteration once we get the
1089 // ANR response back from the policy.
1090 *nextWakeupTime = LONG_LONG_MIN;
1091 return INPUT_EVENT_INJECTION_PENDING;
1092 } else {
1093 // Force poll loop to wake up when timeout is due.
1094 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1095 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1096 }
1097 return INPUT_EVENT_INJECTION_PENDING;
1098 }
1099}
1100
Robert Carr803535b2018-08-02 16:38:15 -07001101void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1102 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1103 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1104 state.removeWindowByToken(token);
1105 }
1106}
1107
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1109 const sp<InputChannel>& inputChannel) {
1110 if (newTimeout > 0) {
1111 // Extend the timeout.
1112 mInputTargetWaitTimeoutTime = now() + newTimeout;
1113 } else {
1114 // Give up.
1115 mInputTargetWaitTimeoutExpired = true;
1116
1117 // Input state will not be realistic. Mark it out of sync.
1118 if (inputChannel.get()) {
1119 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1120 if (connectionIndex >= 0) {
1121 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001122 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123
Robert Carr803535b2018-08-02 16:38:15 -07001124 if (token != nullptr) {
1125 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 }
1127
1128 if (connection->status == Connection::STATUS_NORMAL) {
1129 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1130 "application not responding");
1131 synthesizeCancelationEventsForConnectionLocked(connection, options);
1132 }
1133 }
1134 }
1135 }
1136}
1137
1138nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1139 nsecs_t currentTime) {
1140 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1141 return currentTime - mInputTargetWaitStartTime;
1142 }
1143 return 0;
1144}
1145
1146void InputDispatcher::resetANRTimeoutsLocked() {
1147#if DEBUG_FOCUS
1148 ALOGD("Resetting ANR timeouts.");
1149#endif
1150
1151 // Reset input target wait timeout.
1152 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001153 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154}
1155
Tiger Huang721e26f2018-07-24 22:26:19 +08001156/**
1157 * Get the display id that the given event should go to. If this event specifies a valid display id,
1158 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1159 * Focused display is the display that the user most recently interacted with.
1160 */
1161int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1162 int32_t displayId;
1163 switch (entry->type) {
1164 case EventEntry::TYPE_KEY: {
1165 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1166 displayId = typedEntry->displayId;
1167 break;
1168 }
1169 case EventEntry::TYPE_MOTION: {
1170 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1171 displayId = typedEntry->displayId;
1172 break;
1173 }
1174 default: {
1175 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1176 return ADISPLAY_ID_NONE;
1177 }
1178 }
1179 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1180}
1181
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1183 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1184 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001185 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186
Tiger Huang721e26f2018-07-24 22:26:19 +08001187 int32_t displayId = getTargetDisplayId(entry);
1188 sp<InputWindowHandle> focusedWindowHandle =
1189 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1190 sp<InputApplicationHandle> focusedApplicationHandle =
1191 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1192
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 // If there is no currently focused window and no focused application
1194 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001195 if (focusedWindowHandle == nullptr) {
1196 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001198 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 "Waiting because no window has focus but there is a "
1200 "focused application that may eventually add a window "
1201 "when it finishes starting up.");
1202 goto Unresponsive;
1203 }
1204
Arthur Hung3b413f22018-10-26 18:05:34 +08001205 ALOGI("Dropping event because there is no focused window or focused application in display "
1206 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1208 goto Failed;
1209 }
1210
1211 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001212 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1214 goto Failed;
1215 }
1216
Jeff Brownffb49772014-10-10 19:01:34 -07001217 // Check whether the window is ready for more input.
1218 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001219 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001220 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001222 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 goto Unresponsive;
1224 }
1225
1226 // Success! Output targets.
1227 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001228 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1230 inputTargets);
1231
1232 // Done.
1233Failed:
1234Unresponsive:
1235 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001236 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237#if DEBUG_FOCUS
1238 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1239 "timeSpentWaitingForApplication=%0.1fms",
1240 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1241#endif
1242 return injectionResult;
1243}
1244
1245int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1246 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1247 bool* outConflictingPointerActions) {
1248 enum InjectionPermission {
1249 INJECTION_PERMISSION_UNKNOWN,
1250 INJECTION_PERMISSION_GRANTED,
1251 INJECTION_PERMISSION_DENIED
1252 };
1253
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 // For security reasons, we defer updating the touch state until we are sure that
1255 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 int32_t displayId = entry->displayId;
1257 int32_t action = entry->action;
1258 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1259
1260 // Update the touch state as needed based on the properties of the touch event.
1261 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1262 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1263 sp<InputWindowHandle> newHoverWindowHandle;
1264
Jeff Brownf086ddb2014-02-11 14:28:48 -08001265 // Copy current touch state into mTempTouchState.
1266 // This state is always reset at the end of this function, so if we don't find state
1267 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001268 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001269 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1270 if (oldStateIndex >= 0) {
1271 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1272 mTempTouchState.copyFrom(*oldState);
1273 }
1274
1275 bool isSplit = mTempTouchState.split;
1276 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1277 && (mTempTouchState.deviceId != entry->deviceId
1278 || mTempTouchState.source != entry->source
1279 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1281 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1282 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1283 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1284 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1285 || isHoverAction);
1286 bool wrongDevice = false;
1287 if (newGesture) {
1288 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001289 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001291 ALOGD("Dropping event because a pointer for a different device is already down "
1292 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001294 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1296 switchedDevice = false;
1297 wrongDevice = true;
1298 goto Failed;
1299 }
1300 mTempTouchState.reset();
1301 mTempTouchState.down = down;
1302 mTempTouchState.deviceId = entry->deviceId;
1303 mTempTouchState.source = entry->source;
1304 mTempTouchState.displayId = displayId;
1305 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001306 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1307#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001308 ALOGI("Dropping move event because a pointer for a different device is already active "
1309 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001310#endif
1311 // TODO: test multiple simultaneous input streams.
1312 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1313 switchedDevice = false;
1314 wrongDevice = true;
1315 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 }
1317
1318 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1319 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1320
1321 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1322 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1323 getAxisValue(AMOTION_EVENT_AXIS_X));
1324 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1325 getAxisValue(AMOTION_EVENT_AXIS_Y));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001326 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
1327 displayId, x, y, maskedAction == AMOTION_EVENT_ACTION_DOWN, true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001330 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1332 // New window supports splitting.
1333 isSplit = true;
1334 } else if (isSplit) {
1335 // New window does not support splitting but we have already split events.
1336 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001337 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
1339
1340 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001341 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 // Try to assign the pointer to the first foreground window we find, if there is one.
1343 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001344 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001345 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1346 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1348 goto Failed;
1349 }
1350 }
1351
1352 // Set target flags.
1353 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1354 if (isSplit) {
1355 targetFlags |= InputTarget::FLAG_SPLIT;
1356 }
1357 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1358 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001359 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1360 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361 }
1362
1363 // Update hover state.
1364 if (isHoverAction) {
1365 newHoverWindowHandle = newTouchedWindowHandle;
1366 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1367 newHoverWindowHandle = mLastHoverWindowHandle;
1368 }
1369
1370 // Update the temporary touch state.
1371 BitSet32 pointerIds;
1372 if (isSplit) {
1373 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1374 pointerIds.markBit(pointerId);
1375 }
1376 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1377 } else {
1378 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1379
1380 // If the pointer is not currently down, then ignore the event.
1381 if (! mTempTouchState.down) {
1382#if DEBUG_FOCUS
1383 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001384 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385#endif
1386 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1387 goto Failed;
1388 }
1389
1390 // Check whether touches should slip outside of the current foreground window.
1391 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1392 && entry->pointerCount == 1
1393 && mTempTouchState.isSlippery()) {
1394 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1395 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1396
1397 sp<InputWindowHandle> oldTouchedWindowHandle =
1398 mTempTouchState.getFirstForegroundWindowHandle();
1399 sp<InputWindowHandle> newTouchedWindowHandle =
1400 findTouchedWindowAtLocked(displayId, x, y);
1401 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001402 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001404 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001405 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001406 newTouchedWindowHandle->getName().c_str(),
1407 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408#endif
1409 // Make a slippery exit from the old window.
1410 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1411 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1412
1413 // Make a slippery entrance into the new window.
1414 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1415 isSplit = true;
1416 }
1417
1418 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1419 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1420 if (isSplit) {
1421 targetFlags |= InputTarget::FLAG_SPLIT;
1422 }
1423 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1424 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1425 }
1426
1427 BitSet32 pointerIds;
1428 if (isSplit) {
1429 pointerIds.markBit(entry->pointerProperties[0].id);
1430 }
1431 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1432 }
1433 }
1434 }
1435
1436 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1437 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001438 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439#if DEBUG_HOVER
1440 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001441 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442#endif
1443 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1444 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1445 }
1446
1447 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001448 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449#if DEBUG_HOVER
1450 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001451 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452#endif
1453 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1454 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1455 }
1456 }
1457
1458 // Check permission to inject into all touched foreground windows and ensure there
1459 // is at least one touched foreground window.
1460 {
1461 bool haveForegroundWindow = false;
1462 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1463 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1464 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1465 haveForegroundWindow = true;
1466 if (! checkInjectionPermission(touchedWindow.windowHandle,
1467 entry->injectionState)) {
1468 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1469 injectionPermission = INJECTION_PERMISSION_DENIED;
1470 goto Failed;
1471 }
1472 }
1473 }
1474 if (! haveForegroundWindow) {
1475#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001476 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1477 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478#endif
1479 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1480 goto Failed;
1481 }
1482
1483 // Permission granted to injection into all touched foreground windows.
1484 injectionPermission = INJECTION_PERMISSION_GRANTED;
1485 }
1486
1487 // Check whether windows listening for outside touches are owned by the same UID. If it is
1488 // set the policy flag that we will not reveal coordinate information to this window.
1489 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1490 sp<InputWindowHandle> foregroundWindowHandle =
1491 mTempTouchState.getFirstForegroundWindowHandle();
1492 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1493 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1494 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1495 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1496 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1497 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1498 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1499 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1500 }
1501 }
1502 }
1503 }
1504
1505 // Ensure all touched foreground windows are ready for new input.
1506 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1507 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1508 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001509 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001510 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001511 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001512 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001514 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 goto Unresponsive;
1516 }
1517 }
1518 }
1519
1520 // If this is the first pointer going down and the touched window has a wallpaper
1521 // then also add the touched wallpaper windows so they are locked in for the duration
1522 // of the touch gesture.
1523 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1524 // engine only supports touch events. We would need to add a mechanism similar
1525 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1526 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1527 sp<InputWindowHandle> foregroundWindowHandle =
1528 mTempTouchState.getFirstForegroundWindowHandle();
1529 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001530 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1531 size_t numWindows = windowHandles.size();
1532 for (size_t i = 0; i < numWindows; i++) {
1533 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 const InputWindowInfo* info = windowHandle->getInfo();
1535 if (info->displayId == displayId
1536 && windowHandle->getInfo()->layoutParamsType
1537 == InputWindowInfo::TYPE_WALLPAPER) {
1538 mTempTouchState.addOrUpdateWindow(windowHandle,
1539 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001540 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 | InputTarget::FLAG_DISPATCH_AS_IS,
1542 BitSet32(0));
1543 }
1544 }
1545 }
1546 }
1547
1548 // Success! Output targets.
1549 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1550
1551 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1552 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1553 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1554 touchedWindow.pointerIds, inputTargets);
1555 }
1556
1557 // Drop the outside or hover touch windows since we will not care about them
1558 // in the next iteration.
1559 mTempTouchState.filterNonAsIsTouchWindows();
1560
1561Failed:
1562 // Check injection permission once and for all.
1563 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001564 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 injectionPermission = INJECTION_PERMISSION_GRANTED;
1566 } else {
1567 injectionPermission = INJECTION_PERMISSION_DENIED;
1568 }
1569 }
1570
1571 // Update final pieces of touch state if the injector had permission.
1572 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1573 if (!wrongDevice) {
1574 if (switchedDevice) {
1575#if DEBUG_FOCUS
1576 ALOGD("Conflicting pointer actions: Switched to a different device.");
1577#endif
1578 *outConflictingPointerActions = true;
1579 }
1580
1581 if (isHoverAction) {
1582 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001583 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584#if DEBUG_FOCUS
1585 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1586#endif
1587 *outConflictingPointerActions = true;
1588 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001589 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1591 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001592 mTempTouchState.deviceId = entry->deviceId;
1593 mTempTouchState.source = entry->source;
1594 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 }
1596 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1597 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1598 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001599 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1601 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001602 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603#if DEBUG_FOCUS
1604 ALOGD("Conflicting pointer actions: Down received while already down.");
1605#endif
1606 *outConflictingPointerActions = true;
1607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1609 // One pointer went up.
1610 if (isSplit) {
1611 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1612 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1613
1614 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1615 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1616 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1617 touchedWindow.pointerIds.clearBit(pointerId);
1618 if (touchedWindow.pointerIds.isEmpty()) {
1619 mTempTouchState.windows.removeAt(i);
1620 continue;
1621 }
1622 }
1623 i += 1;
1624 }
1625 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001626 }
1627
1628 // Save changes unless the action was scroll in which case the temporary touch
1629 // state was only valid for this one action.
1630 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1631 if (mTempTouchState.displayId >= 0) {
1632 if (oldStateIndex >= 0) {
1633 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1634 } else {
1635 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1636 }
1637 } else if (oldStateIndex >= 0) {
1638 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 }
1641
1642 // Update hover state.
1643 mLastHoverWindowHandle = newHoverWindowHandle;
1644 }
1645 } else {
1646#if DEBUG_FOCUS
1647 ALOGD("Not updating touch focus because injection was denied.");
1648#endif
1649 }
1650
1651Unresponsive:
1652 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1653 mTempTouchState.reset();
1654
1655 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001656 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657#if DEBUG_FOCUS
1658 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1659 "timeSpentWaitingForApplication=%0.1fms",
1660 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1661#endif
1662 return injectionResult;
1663}
1664
1665void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1666 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001667 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1668 if (inputChannel == nullptr) {
1669 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1670 return;
1671 }
1672
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 inputTargets.push();
1674
1675 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1676 InputTarget& target = inputTargets.editTop();
Arthur Hungceeb5d72018-12-05 16:14:18 +08001677 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 target.flags = targetFlags;
1679 target.xOffset = - windowInfo->frameLeft;
1680 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001681 target.globalScaleFactor = windowInfo->globalScaleFactor;
1682 target.windowXScale = windowInfo->windowXScale;
1683 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 target.pointerIds = pointerIds;
1685}
1686
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001687void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001688 int32_t displayId, float xOffset, float yOffset) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001689 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1690 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001692 if (it != mMonitoringChannelsByDisplay.end()) {
1693 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1694 const size_t numChannels = monitoringChannels.size();
1695 for (size_t i = 0; i < numChannels; i++) {
1696 inputTargets.push();
1697
1698 InputTarget& target = inputTargets.editTop();
1699 target.inputChannel = monitoringChannels[i];
1700 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001701 target.xOffset = xOffset;
1702 target.yOffset = yOffset;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001703 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001704 target.globalScaleFactor = 1.0f;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001705 }
1706 } else {
1707 // If there is no monitor channel registered or all monitor channel unregistered,
1708 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001709 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 }
1711}
1712
1713bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1714 const InjectionState* injectionState) {
1715 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001716 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1718 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001719 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1721 "owned by uid %d",
1722 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001723 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 windowHandle->getInfo()->ownerUid);
1725 } else {
1726 ALOGW("Permission denied: injecting event from pid %d uid %d",
1727 injectionState->injectorPid, injectionState->injectorUid);
1728 }
1729 return false;
1730 }
1731 return true;
1732}
1733
1734bool InputDispatcher::isWindowObscuredAtPointLocked(
1735 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1736 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001737 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1738 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001740 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 if (otherHandle == windowHandle) {
1742 break;
1743 }
1744
1745 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1746 if (otherInfo->displayId == displayId
1747 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1748 && otherInfo->frameContainsPoint(x, y)) {
1749 return true;
1750 }
1751 }
1752 return false;
1753}
1754
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001755
1756bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1757 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001758 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001759 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001760 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001761 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001762 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001763 if (otherHandle == windowHandle) {
1764 break;
1765 }
1766
1767 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1768 if (otherInfo->displayId == displayId
1769 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1770 && otherInfo->overlaps(windowInfo)) {
1771 return true;
1772 }
1773 }
1774 return false;
1775}
1776
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001777std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001778 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1779 const char* targetType) {
1780 // If the window is paused then keep waiting.
1781 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001782 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001783 }
1784
1785 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001786 ssize_t connectionIndex = getConnectionIndexLocked(
1787 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001788 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001789 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001790 "registered with the input dispatcher. The window may be in the process "
1791 "of being removed.", targetType);
1792 }
1793
1794 // If the connection is dead then keep waiting.
1795 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1796 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001797 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001798 "The window may be in the process of being removed.", targetType,
1799 connection->getStatusLabel());
1800 }
1801
1802 // If the connection is backed up then keep waiting.
1803 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001804 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001805 "Outbound queue length: %d. Wait queue length: %d.",
1806 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1807 }
1808
1809 // Ensure that the dispatch queues aren't too far backed up for this event.
1810 if (eventEntry->type == EventEntry::TYPE_KEY) {
1811 // If the event is a key event, then we must wait for all previous events to
1812 // complete before delivering it because previous events may have the
1813 // side-effect of transferring focus to a different window and we want to
1814 // ensure that the following keys are sent to the new window.
1815 //
1816 // Suppose the user touches a button in a window then immediately presses "A".
1817 // If the button causes a pop-up window to appear then we want to ensure that
1818 // the "A" key is delivered to the new pop-up window. This is because users
1819 // often anticipate pending UI changes when typing on a keyboard.
1820 // To obtain this behavior, we must serialize key events with respect to all
1821 // prior input events.
1822 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001823 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001824 "finished processing all of the input events that were previously "
1825 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1826 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
Jeff Brownffb49772014-10-10 19:01:34 -07001828 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 // Touch events can always be sent to a window immediately because the user intended
1830 // to touch whatever was visible at the time. Even if focus changes or a new
1831 // window appears moments later, the touch event was meant to be delivered to
1832 // whatever window happened to be on screen at the time.
1833 //
1834 // Generic motion events, such as trackball or joystick events are a little trickier.
1835 // Like key events, generic motion events are delivered to the focused window.
1836 // Unlike key events, generic motion events don't tend to transfer focus to other
1837 // windows and it is not important for them to be serialized. So we prefer to deliver
1838 // generic motion events as soon as possible to improve efficiency and reduce lag
1839 // through batching.
1840 //
1841 // The one case where we pause input event delivery is when the wait queue is piling
1842 // up with lots of events because the application is not responding.
1843 // This condition ensures that ANRs are detected reliably.
1844 if (!connection->waitQueue.isEmpty()
1845 && currentTime >= connection->waitQueue.head->deliveryTime
1846 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001847 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001848 "finished processing certain input events that were delivered to it over "
1849 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1850 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1851 connection->waitQueue.count(),
1852 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
1854 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001855 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856}
1857
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001858std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 const sp<InputApplicationHandle>& applicationHandle,
1860 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001861 if (applicationHandle != nullptr) {
1862 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001863 std::string label(applicationHandle->getName());
1864 label += " - ";
1865 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 return label;
1867 } else {
1868 return applicationHandle->getName();
1869 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001870 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 return windowHandle->getName();
1872 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001873 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 }
1875}
1876
1877void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001878 int32_t displayId = getTargetDisplayId(eventEntry);
1879 sp<InputWindowHandle> focusedWindowHandle =
1880 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1881 if (focusedWindowHandle != nullptr) {
1882 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1884#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001885 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886#endif
1887 return;
1888 }
1889 }
1890
1891 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1892 switch (eventEntry->type) {
1893 case EventEntry::TYPE_MOTION: {
1894 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1895 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1896 return;
1897 }
1898
1899 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1900 eventType = USER_ACTIVITY_EVENT_TOUCH;
1901 }
1902 break;
1903 }
1904 case EventEntry::TYPE_KEY: {
1905 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1906 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1907 return;
1908 }
1909 eventType = USER_ACTIVITY_EVENT_BUTTON;
1910 break;
1911 }
1912 }
1913
1914 CommandEntry* commandEntry = postCommandLocked(
1915 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1916 commandEntry->eventTime = eventEntry->eventTime;
1917 commandEntry->userActivityEventType = eventType;
1918}
1919
1920void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1921 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1922#if DEBUG_DISPATCH_CYCLE
1923 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001924 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1925 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001926 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001928 inputTarget->globalScaleFactor,
1929 inputTarget->windowXScale, inputTarget->windowYScale,
1930 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931#endif
1932
1933 // Skip this event if the connection status is not normal.
1934 // We don't want to enqueue additional outbound events if the connection is broken.
1935 if (connection->status != Connection::STATUS_NORMAL) {
1936#if DEBUG_DISPATCH_CYCLE
1937 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001938 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939#endif
1940 return;
1941 }
1942
1943 // Split a motion event if needed.
1944 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1945 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1946
1947 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1948 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1949 MotionEntry* splitMotionEntry = splitMotionEvent(
1950 originalMotionEntry, inputTarget->pointerIds);
1951 if (!splitMotionEntry) {
1952 return; // split event was dropped
1953 }
1954#if DEBUG_FOCUS
1955 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001956 connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001957 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958#endif
1959 enqueueDispatchEntriesLocked(currentTime, connection,
1960 splitMotionEntry, inputTarget);
1961 splitMotionEntry->release();
1962 return;
1963 }
1964 }
1965
1966 // Not splitting. Enqueue dispatch entries for the event as is.
1967 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1968}
1969
1970void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1971 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1972 bool wasEmpty = connection->outboundQueue.isEmpty();
1973
1974 // Enqueue dispatch entries for the requested modes.
1975 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1976 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1977 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1978 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1979 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1980 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1981 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1982 InputTarget::FLAG_DISPATCH_AS_IS);
1983 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1984 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1985 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1986 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1987
1988 // If the outbound queue was previously empty, start the dispatch cycle going.
1989 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1990 startDispatchCycleLocked(currentTime, connection);
1991 }
1992}
1993
1994void InputDispatcher::enqueueDispatchEntryLocked(
1995 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1996 int32_t dispatchMode) {
1997 int32_t inputTargetFlags = inputTarget->flags;
1998 if (!(inputTargetFlags & dispatchMode)) {
1999 return;
2000 }
2001 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2002
2003 // This is a new event.
2004 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2005 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2006 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002007 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2008 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009
2010 // Apply target flags and update the connection's input state.
2011 switch (eventEntry->type) {
2012 case EventEntry::TYPE_KEY: {
2013 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2014 dispatchEntry->resolvedAction = keyEntry->action;
2015 dispatchEntry->resolvedFlags = keyEntry->flags;
2016
2017 if (!connection->inputState.trackKey(keyEntry,
2018 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2019#if DEBUG_DISPATCH_CYCLE
2020 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002021 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022#endif
2023 delete dispatchEntry;
2024 return; // skip the inconsistent event
2025 }
2026 break;
2027 }
2028
2029 case EventEntry::TYPE_MOTION: {
2030 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2031 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2032 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2033 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2034 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2035 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2037 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2038 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2039 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2040 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2041 } else {
2042 dispatchEntry->resolvedAction = motionEntry->action;
2043 }
2044 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2045 && !connection->inputState.isHovering(
2046 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2047#if DEBUG_DISPATCH_CYCLE
2048 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002049 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050#endif
2051 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2052 }
2053
2054 dispatchEntry->resolvedFlags = motionEntry->flags;
2055 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2056 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2057 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002058 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2059 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061
2062 if (!connection->inputState.trackMotion(motionEntry,
2063 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2064#if DEBUG_DISPATCH_CYCLE
2065 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002066 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067#endif
2068 delete dispatchEntry;
2069 return; // skip the inconsistent event
2070 }
2071 break;
2072 }
2073 }
2074
2075 // Remember that we are waiting for this dispatch to complete.
2076 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002077 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 }
2079
2080 // Enqueue the dispatch entry.
2081 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002082 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083}
2084
2085void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2086 const sp<Connection>& connection) {
2087#if DEBUG_DISPATCH_CYCLE
2088 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002089 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090#endif
2091
2092 while (connection->status == Connection::STATUS_NORMAL
2093 && !connection->outboundQueue.isEmpty()) {
2094 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2095 dispatchEntry->deliveryTime = currentTime;
2096
2097 // Publish the event.
2098 status_t status;
2099 EventEntry* eventEntry = dispatchEntry->eventEntry;
2100 switch (eventEntry->type) {
2101 case EventEntry::TYPE_KEY: {
2102 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2103
2104 // Publish the key event.
2105 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002106 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2108 keyEntry->keyCode, keyEntry->scanCode,
2109 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2110 keyEntry->eventTime);
2111 break;
2112 }
2113
2114 case EventEntry::TYPE_MOTION: {
2115 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2116
2117 PointerCoords scaledCoords[MAX_POINTERS];
2118 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2119
2120 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002121 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2123 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002124 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2125 float wxs = dispatchEntry->windowXScale;
2126 float wys = dispatchEntry->windowYScale;
2127 xOffset = dispatchEntry->xOffset * wxs;
2128 yOffset = dispatchEntry->yOffset * wys;
2129 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002130 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002132 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 }
2134 usingCoords = scaledCoords;
2135 }
2136 } else {
2137 xOffset = 0.0f;
2138 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139
2140 // We don't want the dispatch target to know.
2141 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002142 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 scaledCoords[i].clear();
2144 }
2145 usingCoords = scaledCoords;
2146 }
2147 }
2148
2149 // Publish the motion event.
2150 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002151 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002152 dispatchEntry->resolvedAction, motionEntry->actionButton,
2153 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002154 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002155 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 motionEntry->downTime, motionEntry->eventTime,
2157 motionEntry->pointerCount, motionEntry->pointerProperties,
2158 usingCoords);
2159 break;
2160 }
2161
2162 default:
2163 ALOG_ASSERT(false);
2164 return;
2165 }
2166
2167 // Check the result.
2168 if (status) {
2169 if (status == WOULD_BLOCK) {
2170 if (connection->waitQueue.isEmpty()) {
2171 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2172 "This is unexpected because the wait queue is empty, so the pipe "
2173 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002174 "event to it, status=%d", connection->getInputChannelName().c_str(),
2175 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2177 } else {
2178 // Pipe is full and we are waiting for the app to finish process some events
2179 // before sending more events to it.
2180#if DEBUG_DISPATCH_CYCLE
2181 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2182 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002183 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184#endif
2185 connection->inputPublisherBlocked = true;
2186 }
2187 } else {
2188 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002189 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2191 }
2192 return;
2193 }
2194
2195 // Re-enqueue the event on the wait queue.
2196 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002197 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002199 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201}
2202
2203void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2204 const sp<Connection>& connection, uint32_t seq, bool handled) {
2205#if DEBUG_DISPATCH_CYCLE
2206 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002207 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208#endif
2209
2210 connection->inputPublisherBlocked = false;
2211
2212 if (connection->status == Connection::STATUS_BROKEN
2213 || connection->status == Connection::STATUS_ZOMBIE) {
2214 return;
2215 }
2216
2217 // Notify other system components and prepare to start the next dispatch cycle.
2218 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2219}
2220
2221void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2222 const sp<Connection>& connection, bool notify) {
2223#if DEBUG_DISPATCH_CYCLE
2224 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002225 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226#endif
2227
2228 // Clear the dispatch queues.
2229 drainDispatchQueueLocked(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002230 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 drainDispatchQueueLocked(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002232 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233
2234 // The connection appears to be unrecoverably broken.
2235 // Ignore already broken or zombie connections.
2236 if (connection->status == Connection::STATUS_NORMAL) {
2237 connection->status = Connection::STATUS_BROKEN;
2238
2239 if (notify) {
2240 // Notify other system components.
2241 onDispatchCycleBrokenLocked(currentTime, connection);
2242 }
2243 }
2244}
2245
2246void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2247 while (!queue->isEmpty()) {
2248 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2249 releaseDispatchEntryLocked(dispatchEntry);
2250 }
2251}
2252
2253void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2254 if (dispatchEntry->hasForegroundTarget()) {
2255 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2256 }
2257 delete dispatchEntry;
2258}
2259
2260int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2261 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2262
2263 { // acquire lock
2264 AutoMutex _l(d->mLock);
2265
2266 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2267 if (connectionIndex < 0) {
2268 ALOGE("Received spurious receive callback for unknown input channel. "
2269 "fd=%d, events=0x%x", fd, events);
2270 return 0; // remove the callback
2271 }
2272
2273 bool notify;
2274 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2275 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2276 if (!(events & ALOOPER_EVENT_INPUT)) {
2277 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002278 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 return 1;
2280 }
2281
2282 nsecs_t currentTime = now();
2283 bool gotOne = false;
2284 status_t status;
2285 for (;;) {
2286 uint32_t seq;
2287 bool handled;
2288 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2289 if (status) {
2290 break;
2291 }
2292 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2293 gotOne = true;
2294 }
2295 if (gotOne) {
2296 d->runCommandsLockedInterruptible();
2297 if (status == WOULD_BLOCK) {
2298 return 1;
2299 }
2300 }
2301
2302 notify = status != DEAD_OBJECT || !connection->monitor;
2303 if (notify) {
2304 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002305 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307 } else {
2308 // Monitor channels are never explicitly unregistered.
2309 // We do it automatically when the remote endpoint is closed so don't warn
2310 // about them.
2311 notify = !connection->monitor;
2312 if (notify) {
2313 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002314 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
2316 }
2317
2318 // Unregister the channel.
2319 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2320 return 0; // remove the callback
2321 } // release lock
2322}
2323
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002324void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 const CancelationOptions& options) {
2326 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2327 synthesizeCancelationEventsForConnectionLocked(
2328 mConnectionsByFd.valueAt(i), options);
2329 }
2330}
2331
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002332void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002333 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002334 for (auto& it : mMonitoringChannelsByDisplay) {
2335 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2336 const size_t numChannels = monitoringChannels.size();
2337 for (size_t i = 0; i < numChannels; i++) {
2338 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2339 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002340 }
2341}
2342
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2344 const sp<InputChannel>& channel, const CancelationOptions& options) {
2345 ssize_t index = getConnectionIndexLocked(channel);
2346 if (index >= 0) {
2347 synthesizeCancelationEventsForConnectionLocked(
2348 mConnectionsByFd.valueAt(index), options);
2349 }
2350}
2351
2352void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2353 const sp<Connection>& connection, const CancelationOptions& options) {
2354 if (connection->status == Connection::STATUS_BROKEN) {
2355 return;
2356 }
2357
2358 nsecs_t currentTime = now();
2359
2360 Vector<EventEntry*> cancelationEvents;
2361 connection->inputState.synthesizeCancelationEvents(currentTime,
2362 cancelationEvents, options);
2363
2364 if (!cancelationEvents.isEmpty()) {
2365#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002366 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002368 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 options.reason, options.mode);
2370#endif
2371 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2372 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2373 switch (cancelationEventEntry->type) {
2374 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002375 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 static_cast<KeyEntry*>(cancelationEventEntry));
2377 break;
2378 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002379 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 static_cast<MotionEntry*>(cancelationEventEntry));
2381 break;
2382 }
2383
2384 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002385 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2386 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002387 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2389 target.xOffset = -windowInfo->frameLeft;
2390 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002391 target.globalScaleFactor = windowInfo->globalScaleFactor;
2392 target.windowXScale = windowInfo->windowXScale;
2393 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 } else {
2395 target.xOffset = 0;
2396 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002397 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 }
2399 target.inputChannel = connection->inputChannel;
2400 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2401
2402 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2403 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2404
2405 cancelationEventEntry->release();
2406 }
2407
2408 startDispatchCycleLocked(currentTime, connection);
2409 }
2410}
2411
2412InputDispatcher::MotionEntry*
2413InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2414 ALOG_ASSERT(pointerIds.value != 0);
2415
2416 uint32_t splitPointerIndexMap[MAX_POINTERS];
2417 PointerProperties splitPointerProperties[MAX_POINTERS];
2418 PointerCoords splitPointerCoords[MAX_POINTERS];
2419
2420 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2421 uint32_t splitPointerCount = 0;
2422
2423 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2424 originalPointerIndex++) {
2425 const PointerProperties& pointerProperties =
2426 originalMotionEntry->pointerProperties[originalPointerIndex];
2427 uint32_t pointerId = uint32_t(pointerProperties.id);
2428 if (pointerIds.hasBit(pointerId)) {
2429 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2430 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2431 splitPointerCoords[splitPointerCount].copyFrom(
2432 originalMotionEntry->pointerCoords[originalPointerIndex]);
2433 splitPointerCount += 1;
2434 }
2435 }
2436
2437 if (splitPointerCount != pointerIds.count()) {
2438 // This is bad. We are missing some of the pointers that we expected to deliver.
2439 // Most likely this indicates that we received an ACTION_MOVE events that has
2440 // different pointer ids than we expected based on the previous ACTION_DOWN
2441 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2442 // in this way.
2443 ALOGW("Dropping split motion event because the pointer count is %d but "
2444 "we expected there to be %d pointers. This probably means we received "
2445 "a broken sequence of pointer ids from the input device.",
2446 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002447 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 }
2449
2450 int32_t action = originalMotionEntry->action;
2451 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2452 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2453 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2454 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2455 const PointerProperties& pointerProperties =
2456 originalMotionEntry->pointerProperties[originalPointerIndex];
2457 uint32_t pointerId = uint32_t(pointerProperties.id);
2458 if (pointerIds.hasBit(pointerId)) {
2459 if (pointerIds.count() == 1) {
2460 // The first/last pointer went down/up.
2461 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2462 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2463 } else {
2464 // A secondary pointer went down/up.
2465 uint32_t splitPointerIndex = 0;
2466 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2467 splitPointerIndex += 1;
2468 }
2469 action = maskedAction | (splitPointerIndex
2470 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2471 }
2472 } else {
2473 // An unrelated pointer changed.
2474 action = AMOTION_EVENT_ACTION_MOVE;
2475 }
2476 }
2477
2478 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002479 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 originalMotionEntry->eventTime,
2481 originalMotionEntry->deviceId,
2482 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002483 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 originalMotionEntry->policyFlags,
2485 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002486 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 originalMotionEntry->flags,
2488 originalMotionEntry->metaState,
2489 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002490 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 originalMotionEntry->edgeFlags,
2492 originalMotionEntry->xPrecision,
2493 originalMotionEntry->yPrecision,
2494 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002495 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496
2497 if (originalMotionEntry->injectionState) {
2498 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2499 splitMotionEntry->injectionState->refCount += 1;
2500 }
2501
2502 return splitMotionEntry;
2503}
2504
2505void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2506#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002507 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#endif
2509
2510 bool needWake;
2511 { // acquire lock
2512 AutoMutex _l(mLock);
2513
Prabir Pradhan42611e02018-11-27 14:04:02 -08002514 ConfigurationChangedEntry* newEntry =
2515 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 needWake = enqueueInboundEventLocked(newEntry);
2517 } // release lock
2518
2519 if (needWake) {
2520 mLooper->wake();
2521 }
2522}
2523
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002524/**
2525 * If one of the meta shortcuts is detected, process them here:
2526 * Meta + Backspace -> generate BACK
2527 * Meta + Enter -> generate HOME
2528 * This will potentially overwrite keyCode and metaState.
2529 */
2530void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2531 int32_t& keyCode, int32_t& metaState) {
2532 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2533 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2534 if (keyCode == AKEYCODE_DEL) {
2535 newKeyCode = AKEYCODE_BACK;
2536 } else if (keyCode == AKEYCODE_ENTER) {
2537 newKeyCode = AKEYCODE_HOME;
2538 }
2539 if (newKeyCode != AKEYCODE_UNKNOWN) {
2540 AutoMutex _l(mLock);
2541 struct KeyReplacement replacement = {keyCode, deviceId};
2542 mReplacedKeys.add(replacement, newKeyCode);
2543 keyCode = newKeyCode;
2544 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2545 }
2546 } else if (action == AKEY_EVENT_ACTION_UP) {
2547 // In order to maintain a consistent stream of up and down events, check to see if the key
2548 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2549 // even if the modifier was released between the down and the up events.
2550 AutoMutex _l(mLock);
2551 struct KeyReplacement replacement = {keyCode, deviceId};
2552 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2553 if (index >= 0) {
2554 keyCode = mReplacedKeys.valueAt(index);
2555 mReplacedKeys.removeItemsAt(index);
2556 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2557 }
2558 }
2559}
2560
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2562#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002563 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002564 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002565 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002566 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002568 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569#endif
2570 if (!validateKeyEvent(args->action)) {
2571 return;
2572 }
2573
2574 uint32_t policyFlags = args->policyFlags;
2575 int32_t flags = args->flags;
2576 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002577 // InputDispatcher tracks and generates key repeats on behalf of
2578 // whatever notifies it, so repeatCount should always be set to 0
2579 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2581 policyFlags |= POLICY_FLAG_VIRTUAL;
2582 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 if (policyFlags & POLICY_FLAG_FUNCTION) {
2585 metaState |= AMETA_FUNCTION_ON;
2586 }
2587
2588 policyFlags |= POLICY_FLAG_TRUSTED;
2589
Michael Wright78f24442014-08-06 15:55:28 -07002590 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002591 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002592
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002594 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002595 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 args->downTime, args->eventTime);
2597
Michael Wright2b3c3302018-03-02 17:19:13 +00002598 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002600 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2601 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2602 std::to_string(t.duration().count()).c_str());
2603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 bool needWake;
2606 { // acquire lock
2607 mLock.lock();
2608
2609 if (shouldSendKeyToInputFilterLocked(args)) {
2610 mLock.unlock();
2611
2612 policyFlags |= POLICY_FLAG_FILTERED;
2613 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2614 return; // event was consumed by the filter
2615 }
2616
2617 mLock.lock();
2618 }
2619
Prabir Pradhan42611e02018-11-27 14:04:02 -08002620 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002621 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002622 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 metaState, repeatCount, args->downTime);
2624
2625 needWake = enqueueInboundEventLocked(newEntry);
2626 mLock.unlock();
2627 } // release lock
2628
2629 if (needWake) {
2630 mLooper->wake();
2631 }
2632}
2633
2634bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2635 return mInputFilterEnabled;
2636}
2637
2638void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2639#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002640 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2641 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002642 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002643 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2644 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002645 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002646 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 for (uint32_t i = 0; i < args->pointerCount; i++) {
2648 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2649 "x=%f, y=%f, pressure=%f, size=%f, "
2650 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2651 "orientation=%f",
2652 i, args->pointerProperties[i].id,
2653 args->pointerProperties[i].toolType,
2654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2663 }
2664#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002665 if (!validateMotionEvent(args->action, args->actionButton,
2666 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 return;
2668 }
2669
2670 uint32_t policyFlags = args->policyFlags;
2671 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002672
2673 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002674 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002675 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2676 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2677 std::to_string(t.duration().count()).c_str());
2678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679
2680 bool needWake;
2681 { // acquire lock
2682 mLock.lock();
2683
2684 if (shouldSendMotionToInputFilterLocked(args)) {
2685 mLock.unlock();
2686
2687 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002688 event.initialize(args->deviceId, args->source, args->displayId,
2689 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002690 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002691 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 args->downTime, args->eventTime,
2693 args->pointerCount, args->pointerProperties, args->pointerCoords);
2694
2695 policyFlags |= POLICY_FLAG_FILTERED;
2696 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2697 return; // event was consumed by the filter
2698 }
2699
2700 mLock.lock();
2701 }
2702
2703 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002704 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002705 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002706 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002707 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002709 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
2711 needWake = enqueueInboundEventLocked(newEntry);
2712 mLock.unlock();
2713 } // release lock
2714
2715 if (needWake) {
2716 mLooper->wake();
2717 }
2718}
2719
2720bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002721 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722}
2723
2724void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2725#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002726 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2727 "switchMask=0x%08x",
2728 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729#endif
2730
2731 uint32_t policyFlags = args->policyFlags;
2732 policyFlags |= POLICY_FLAG_TRUSTED;
2733 mPolicy->notifySwitch(args->eventTime,
2734 args->switchValues, args->switchMask, policyFlags);
2735}
2736
2737void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2738#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002739 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 args->eventTime, args->deviceId);
2741#endif
2742
2743 bool needWake;
2744 { // acquire lock
2745 AutoMutex _l(mLock);
2746
Prabir Pradhan42611e02018-11-27 14:04:02 -08002747 DeviceResetEntry* newEntry =
2748 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 needWake = enqueueInboundEventLocked(newEntry);
2750 } // release lock
2751
2752 if (needWake) {
2753 mLooper->wake();
2754 }
2755}
2756
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002757int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2759 uint32_t policyFlags) {
2760#if DEBUG_INBOUND_EVENT_DETAILS
2761 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002762 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2763 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764#endif
2765
2766 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2767
2768 policyFlags |= POLICY_FLAG_INJECTED;
2769 if (hasInjectionPermission(injectorPid, injectorUid)) {
2770 policyFlags |= POLICY_FLAG_TRUSTED;
2771 }
2772
2773 EventEntry* firstInjectedEntry;
2774 EventEntry* lastInjectedEntry;
2775 switch (event->getType()) {
2776 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002777 KeyEvent keyEvent;
2778 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2779 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 if (! validateKeyEvent(action)) {
2781 return INPUT_EVENT_INJECTION_FAILED;
2782 }
2783
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002784 int32_t flags = keyEvent.getFlags();
2785 int32_t keyCode = keyEvent.getKeyCode();
2786 int32_t metaState = keyEvent.getMetaState();
2787 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2788 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002789 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002790 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002791 keyEvent.getDownTime(), keyEvent.getEventTime());
2792
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2794 policyFlags |= POLICY_FLAG_VIRTUAL;
2795 }
2796
2797 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002798 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002799 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002800 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2801 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2802 std::to_string(t.duration().count()).c_str());
2803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 }
2805
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002807 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002808 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002810 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2811 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 lastInjectedEntry = firstInjectedEntry;
2813 break;
2814 }
2815
2816 case AINPUT_EVENT_TYPE_MOTION: {
2817 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 int32_t action = motionEvent->getAction();
2819 size_t pointerCount = motionEvent->getPointerCount();
2820 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002821 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002822 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002823 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 return INPUT_EVENT_INJECTION_FAILED;
2825 }
2826
2827 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2828 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002829 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002830 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002831 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2832 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2833 std::to_string(t.duration().count()).c_str());
2834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 }
2836
2837 mLock.lock();
2838 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2839 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002840 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002841 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2842 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002843 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002845 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002847 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002848 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2849 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 lastInjectedEntry = firstInjectedEntry;
2851 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2852 sampleEventTimes += 1;
2853 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002854 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2855 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002856 motionEvent->getDeviceId(), motionEvent->getSource(),
2857 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002858 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002860 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002862 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002863 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2864 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 lastInjectedEntry->next = nextInjectedEntry;
2866 lastInjectedEntry = nextInjectedEntry;
2867 }
2868 break;
2869 }
2870
2871 default:
2872 ALOGW("Cannot inject event of type %d", event->getType());
2873 return INPUT_EVENT_INJECTION_FAILED;
2874 }
2875
2876 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2877 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2878 injectionState->injectionIsAsync = true;
2879 }
2880
2881 injectionState->refCount += 1;
2882 lastInjectedEntry->injectionState = injectionState;
2883
2884 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002885 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 EventEntry* nextEntry = entry->next;
2887 needWake |= enqueueInboundEventLocked(entry);
2888 entry = nextEntry;
2889 }
2890
2891 mLock.unlock();
2892
2893 if (needWake) {
2894 mLooper->wake();
2895 }
2896
2897 int32_t injectionResult;
2898 { // acquire lock
2899 AutoMutex _l(mLock);
2900
2901 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2902 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2903 } else {
2904 for (;;) {
2905 injectionResult = injectionState->injectionResult;
2906 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2907 break;
2908 }
2909
2910 nsecs_t remainingTimeout = endTime - now();
2911 if (remainingTimeout <= 0) {
2912#if DEBUG_INJECTION
2913 ALOGD("injectInputEvent - Timed out waiting for injection result "
2914 "to become available.");
2915#endif
2916 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2917 break;
2918 }
2919
2920 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2921 }
2922
2923 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2924 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2925 while (injectionState->pendingForegroundDispatches != 0) {
2926#if DEBUG_INJECTION
2927 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2928 injectionState->pendingForegroundDispatches);
2929#endif
2930 nsecs_t remainingTimeout = endTime - now();
2931 if (remainingTimeout <= 0) {
2932#if DEBUG_INJECTION
2933 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2934 "dispatches to finish.");
2935#endif
2936 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2937 break;
2938 }
2939
2940 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2941 }
2942 }
2943 }
2944
2945 injectionState->release();
2946 } // release lock
2947
2948#if DEBUG_INJECTION
2949 ALOGD("injectInputEvent - Finished with result %d. "
2950 "injectorPid=%d, injectorUid=%d",
2951 injectionResult, injectorPid, injectorUid);
2952#endif
2953
2954 return injectionResult;
2955}
2956
2957bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2958 return injectorUid == 0
2959 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2960}
2961
2962void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2963 InjectionState* injectionState = entry->injectionState;
2964 if (injectionState) {
2965#if DEBUG_INJECTION
2966 ALOGD("Setting input event injection result to %d. "
2967 "injectorPid=%d, injectorUid=%d",
2968 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2969#endif
2970
2971 if (injectionState->injectionIsAsync
2972 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2973 // Log the outcome since the injector did not wait for the injection result.
2974 switch (injectionResult) {
2975 case INPUT_EVENT_INJECTION_SUCCEEDED:
2976 ALOGV("Asynchronous input event injection succeeded.");
2977 break;
2978 case INPUT_EVENT_INJECTION_FAILED:
2979 ALOGW("Asynchronous input event injection failed.");
2980 break;
2981 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2982 ALOGW("Asynchronous input event injection permission denied.");
2983 break;
2984 case INPUT_EVENT_INJECTION_TIMED_OUT:
2985 ALOGW("Asynchronous input event injection timed out.");
2986 break;
2987 }
2988 }
2989
2990 injectionState->injectionResult = injectionResult;
2991 mInjectionResultAvailableCondition.broadcast();
2992 }
2993}
2994
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002995void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996 InjectionState* injectionState = entry->injectionState;
2997 if (injectionState) {
2998 injectionState->pendingForegroundDispatches += 1;
2999 }
3000}
3001
3002void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3003 InjectionState* injectionState = entry->injectionState;
3004 if (injectionState) {
3005 injectionState->pendingForegroundDispatches -= 1;
3006
3007 if (injectionState->pendingForegroundDispatches == 0) {
3008 mInjectionSyncFinishedCondition.broadcast();
3009 }
3010 }
3011}
3012
Arthur Hungb92218b2018-08-14 12:00:21 +08003013Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3014 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003015 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003016 if(it != mWindowHandlesByDisplay.end()) {
3017 return it->second;
3018 }
3019
3020 // Return an empty one if nothing found.
3021 return Vector<sp<InputWindowHandle>>();
3022}
3023
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003025 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003026 for (auto& it : mWindowHandlesByDisplay) {
3027 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3028 size_t numWindows = windowHandles.size();
3029 for (size_t i = 0; i < numWindows; i++) {
3030 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
chaviwfbe5d9c2018-12-26 12:23:37 -08003031 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003032 return windowHandle;
3033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 }
3035 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003036 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037}
3038
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003039bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003040 for (auto& it : mWindowHandlesByDisplay) {
3041 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3042 size_t numWindows = windowHandles.size();
3043 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003044 if (windowHandles.itemAt(i)->getToken()
3045 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003046 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003047 ALOGE("Found window %s in display %" PRId32
3048 ", but it should belong to display %" PRId32,
3049 windowHandle->getName().c_str(), it.first,
3050 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003051 }
3052 return true;
3053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 }
3055 }
3056 return false;
3057}
3058
Robert Carr5c8a0262018-10-03 16:30:44 -07003059sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3060 size_t count = mInputChannelsByToken.count(token);
3061 if (count == 0) {
3062 return nullptr;
3063 }
3064 return mInputChannelsByToken.at(token);
3065}
3066
Arthur Hungb92218b2018-08-14 12:00:21 +08003067/**
3068 * Called from InputManagerService, update window handle list by displayId that can receive input.
3069 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3070 * If set an empty list, remove all handles from the specific display.
3071 * For focused handle, check if need to change and send a cancel event to previous one.
3072 * For removed handle, check if need to send a cancel event if already in touch.
3073 */
3074void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3075 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003077 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078#endif
3079 { // acquire lock
3080 AutoMutex _l(mLock);
3081
Arthur Hungb92218b2018-08-14 12:00:21 +08003082 // Copy old handles for release if they are no longer present.
3083 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084
Tiger Huang721e26f2018-07-24 22:26:19 +08003085 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003087
3088 if (inputWindowHandles.isEmpty()) {
3089 // Remove all handles on a display if there are no windows left.
3090 mWindowHandlesByDisplay.erase(displayId);
3091 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003092 // Since we compare the pointer of input window handles across window updates, we need
3093 // to make sure the handle object for the same window stays unchanged across updates.
3094 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3095 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3096 for (size_t i = 0; i < oldHandles.size(); i++) {
3097 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3098 oldHandlesByTokens[handle->getToken()] = handle;
3099 }
3100
3101 const size_t numWindows = inputWindowHandles.size();
3102 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003103 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003104 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003105 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3106 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003107 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003108 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003109 continue;
3110 }
3111
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003112 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003113 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003114 handle->getName().c_str(), displayId,
3115 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003116 continue;
3117 }
3118
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003119 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3120 const sp<InputWindowHandle> oldHandle =
3121 oldHandlesByTokens.at(handle->getToken());
3122 oldHandle->updateFrom(handle);
3123 newHandles.push_back(oldHandle);
3124 } else {
3125 newHandles.push_back(handle);
3126 }
3127 }
3128
3129 for (size_t i = 0; i < newHandles.size(); i++) {
3130 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Arthur Hung7ab76b12019-01-09 19:17:20 +08003131 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3132 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3133 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003134 newFocusedWindowHandle = windowHandle;
3135 }
3136 if (windowHandle == mLastHoverWindowHandle) {
3137 foundHoveredWindow = true;
3138 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003139 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003140
3141 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003142 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 }
3144
3145 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003146 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
Tiger Huang721e26f2018-07-24 22:26:19 +08003149 sp<InputWindowHandle> oldFocusedWindowHandle =
3150 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3151
3152 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3153 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003155 ALOGD("Focus left window: %s in display %" PRId32,
3156 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003158 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3159 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003160 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3162 "focus left window");
3163 synthesizeCancelationEventsForInputChannelLocked(
3164 focusedInputChannel, options);
3165 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003166 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003168 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003170 ALOGD("Focus entered window: %s in display %" PRId32,
3171 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003173 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
Robert Carrf759f162018-11-13 12:57:11 -08003175
3176 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003177 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003178 }
3179
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181
Arthur Hungb92218b2018-08-14 12:00:21 +08003182 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3183 if (stateIndex >= 0) {
3184 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003185 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003186 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003187 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003189 ALOGD("Touched window was removed: %s in display %" PRId32,
3190 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003192 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003193 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003194 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003195 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3196 "touched window was removed");
3197 synthesizeCancelationEventsForInputChannelLocked(
3198 touchedInputChannel, options);
3199 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003200 state.windows.removeAt(i);
3201 } else {
3202 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205 }
3206
3207 // Release information for windows that are no longer present.
3208 // This ensures that unused input channels are released promptly.
3209 // Otherwise, they might stick around until the window handle is destroyed
3210 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003211 size_t numWindows = oldWindowHandles.size();
3212 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003214 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003216 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003218 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 }
3220 }
3221 } // release lock
3222
3223 // Wake up poll loop since it may need to make new input dispatching choices.
3224 mLooper->wake();
3225}
3226
3227void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003228 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003230 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231#endif
3232 { // acquire lock
3233 AutoMutex _l(mLock);
3234
Tiger Huang721e26f2018-07-24 22:26:19 +08003235 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3236 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003237 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003238 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3239 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003241 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003243 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003245 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003247 oldFocusedApplicationHandle->releaseInfo();
3248 oldFocusedApplicationHandle.clear();
3249 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 }
3251
3252#if DEBUG_FOCUS
3253 //logDispatchStateLocked();
3254#endif
3255 } // release lock
3256
3257 // Wake up poll loop since it may need to make new input dispatching choices.
3258 mLooper->wake();
3259}
3260
Tiger Huang721e26f2018-07-24 22:26:19 +08003261/**
3262 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3263 * the display not specified.
3264 *
3265 * We track any unreleased events for each window. If a window loses the ability to receive the
3266 * released event, we will send a cancel event to it. So when the focused display is changed, we
3267 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3268 * display. The display-specified events won't be affected.
3269 */
3270void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3271#if DEBUG_FOCUS
3272 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3273#endif
3274 { // acquire lock
3275 AutoMutex _l(mLock);
3276
3277 if (mFocusedDisplayId != displayId) {
3278 sp<InputWindowHandle> oldFocusedWindowHandle =
3279 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3280 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003281 sp<InputChannel> inputChannel =
3282 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003283 if (inputChannel != nullptr) {
3284 CancelationOptions options(
3285 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3286 "The display which contains this window no longer has focus.");
3287 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3288 }
3289 }
3290 mFocusedDisplayId = displayId;
3291
3292 // Sanity check
3293 sp<InputWindowHandle> newFocusedWindowHandle =
3294 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003295 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003296
Tiger Huang721e26f2018-07-24 22:26:19 +08003297 if (newFocusedWindowHandle == nullptr) {
3298 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3299 if (!mFocusedWindowHandlesByDisplay.empty()) {
3300 ALOGE("But another display has a focused window:");
3301 for (auto& it : mFocusedWindowHandlesByDisplay) {
3302 const int32_t displayId = it.first;
3303 const sp<InputWindowHandle>& windowHandle = it.second;
3304 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3305 displayId, windowHandle->getName().c_str());
3306 }
3307 }
3308 }
3309 }
3310
3311#if DEBUG_FOCUS
3312 logDispatchStateLocked();
3313#endif
3314 } // release lock
3315
3316 // Wake up poll loop since it may need to make new input dispatching choices.
3317 mLooper->wake();
3318}
3319
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3321#if DEBUG_FOCUS
3322 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3323#endif
3324
3325 bool changed;
3326 { // acquire lock
3327 AutoMutex _l(mLock);
3328
3329 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3330 if (mDispatchFrozen && !frozen) {
3331 resetANRTimeoutsLocked();
3332 }
3333
3334 if (mDispatchEnabled && !enabled) {
3335 resetAndDropEverythingLocked("dispatcher is being disabled");
3336 }
3337
3338 mDispatchEnabled = enabled;
3339 mDispatchFrozen = frozen;
3340 changed = true;
3341 } else {
3342 changed = false;
3343 }
3344
3345#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003346 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347#endif
3348 } // release lock
3349
3350 if (changed) {
3351 // Wake up poll loop since it may need to make new input dispatching choices.
3352 mLooper->wake();
3353 }
3354}
3355
3356void InputDispatcher::setInputFilterEnabled(bool enabled) {
3357#if DEBUG_FOCUS
3358 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3359#endif
3360
3361 { // acquire lock
3362 AutoMutex _l(mLock);
3363
3364 if (mInputFilterEnabled == enabled) {
3365 return;
3366 }
3367
3368 mInputFilterEnabled = enabled;
3369 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3370 } // release lock
3371
3372 // Wake up poll loop since there might be work to do to drop everything.
3373 mLooper->wake();
3374}
3375
chaviwfbe5d9c2018-12-26 12:23:37 -08003376bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3377 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003379 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003381 return true;
3382 }
3383
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 { // acquire lock
3385 AutoMutex _l(mLock);
3386
chaviwfbe5d9c2018-12-26 12:23:37 -08003387 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3388 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003389 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003390 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 return false;
3392 }
chaviw4f2dd402018-12-26 15:30:27 -08003393#if DEBUG_FOCUS
3394 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3395 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3396#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3398#if DEBUG_FOCUS
3399 ALOGD("Cannot transfer focus because windows are on different displays.");
3400#endif
3401 return false;
3402 }
3403
3404 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003405 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3406 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3407 for (size_t i = 0; i < state.windows.size(); i++) {
3408 const TouchedWindow& touchedWindow = state.windows[i];
3409 if (touchedWindow.windowHandle == fromWindowHandle) {
3410 int32_t oldTargetFlags = touchedWindow.targetFlags;
3411 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
Jeff Brownf086ddb2014-02-11 14:28:48 -08003413 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Jeff Brownf086ddb2014-02-11 14:28:48 -08003415 int32_t newTargetFlags = oldTargetFlags
3416 & (InputTarget::FLAG_FOREGROUND
3417 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3418 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
Jeff Brownf086ddb2014-02-11 14:28:48 -08003420 found = true;
3421 goto Found;
3422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003425Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426
3427 if (! found) {
3428#if DEBUG_FOCUS
3429 ALOGD("Focus transfer failed because from window did not have focus.");
3430#endif
3431 return false;
3432 }
3433
chaviwfbe5d9c2018-12-26 12:23:37 -08003434
3435 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3436 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3438 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3439 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3440 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3441 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3442
3443 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3444 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3445 "transferring touch focus from this window to another window");
3446 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3447 }
3448
3449#if DEBUG_FOCUS
3450 logDispatchStateLocked();
3451#endif
3452 } // release lock
3453
3454 // Wake up poll loop since it may need to make new input dispatching choices.
3455 mLooper->wake();
3456 return true;
3457}
3458
3459void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3460#if DEBUG_FOCUS
3461 ALOGD("Resetting and dropping all events (%s).", reason);
3462#endif
3463
3464 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3465 synthesizeCancelationEventsForAllConnectionsLocked(options);
3466
3467 resetKeyRepeatLocked();
3468 releasePendingEventLocked();
3469 drainInboundQueueLocked();
3470 resetANRTimeoutsLocked();
3471
Jeff Brownf086ddb2014-02-11 14:28:48 -08003472 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003474 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475}
3476
3477void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003478 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 dumpDispatchStateLocked(dump);
3480
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003481 std::istringstream stream(dump);
3482 std::string line;
3483
3484 while (std::getline(stream, line, '\n')) {
3485 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487}
3488
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003489void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3490 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3491 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003492 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493
Tiger Huang721e26f2018-07-24 22:26:19 +08003494 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3495 dump += StringPrintf(INDENT "FocusedApplications:\n");
3496 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3497 const int32_t displayId = it.first;
3498 const sp<InputApplicationHandle>& applicationHandle = it.second;
3499 dump += StringPrintf(
3500 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3501 displayId,
3502 applicationHandle->getName().c_str(),
3503 applicationHandle->getDispatchingTimeout(
3504 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003507 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003509
3510 if (!mFocusedWindowHandlesByDisplay.empty()) {
3511 dump += StringPrintf(INDENT "FocusedWindows:\n");
3512 for (auto& it : mFocusedWindowHandlesByDisplay) {
3513 const int32_t displayId = it.first;
3514 const sp<InputWindowHandle>& windowHandle = it.second;
3515 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3516 displayId, windowHandle->getName().c_str());
3517 }
3518 } else {
3519 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521
Jeff Brownf086ddb2014-02-11 14:28:48 -08003522 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003523 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003524 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3525 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003526 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003527 state.displayId, toString(state.down), toString(state.split),
3528 state.deviceId, state.source);
3529 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003530 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003531 for (size_t i = 0; i < state.windows.size(); i++) {
3532 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003533 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3534 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003535 touchedWindow.pointerIds.value,
3536 touchedWindow.targetFlags);
3537 }
3538 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003539 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003540 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003541 if (!state.portalWindows.isEmpty()) {
3542 dump += INDENT3 "Portal windows:\n";
3543 for (size_t i = 0; i < state.portalWindows.size(); i++) {
3544 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows.itemAt(i);
3545 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3546 i, portalWindowHandle->getName().c_str());
3547 }
3548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 }
3550 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003551 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 }
3553
Arthur Hungb92218b2018-08-14 12:00:21 +08003554 if (!mWindowHandlesByDisplay.empty()) {
3555 for (auto& it : mWindowHandlesByDisplay) {
3556 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003557 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003558 if (!windowHandles.isEmpty()) {
3559 dump += INDENT2 "Windows:\n";
3560 for (size_t i = 0; i < windowHandles.size(); i++) {
3561 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3562 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563
Arthur Hungb92218b2018-08-14 12:00:21 +08003564 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003565 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003566 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003567 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 "touchableRegion=",
3569 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003570 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003571 toString(windowInfo->paused),
3572 toString(windowInfo->hasFocus),
3573 toString(windowInfo->hasWallpaper),
3574 toString(windowInfo->visible),
3575 toString(windowInfo->canReceiveKeys),
3576 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3577 windowInfo->layer,
3578 windowInfo->frameLeft, windowInfo->frameTop,
3579 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003580 windowInfo->globalScaleFactor,
3581 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003582 dumpRegion(dump, windowInfo->touchableRegion);
3583 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3584 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3585 windowInfo->ownerPid, windowInfo->ownerUid,
3586 windowInfo->dispatchingTimeout / 1000000.0);
3587 }
3588 } else {
3589 dump += INDENT2 "Windows: <none>\n";
3590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003593 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003596 if (!mMonitoringChannelsByDisplay.empty()) {
3597 for (auto& it : mMonitoringChannelsByDisplay) {
3598 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003599 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003600 const size_t numChannels = monitoringChannels.size();
3601 for (size_t i = 0; i < numChannels; i++) {
3602 const sp<InputChannel>& channel = monitoringChannels[i];
3603 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3604 }
3605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003607 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609
3610 nsecs_t currentTime = now();
3611
3612 // Dump recently dispatched or dropped events from oldest to newest.
3613 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003614 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003616 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003618 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 (currentTime - entry->eventTime) * 0.000001f);
3620 }
3621 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003622 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624
3625 // Dump event currently being dispatched.
3626 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003627 dump += INDENT "PendingEvent:\n";
3628 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3632 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
3635
3636 // Dump inbound events from oldest to newest.
3637 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003638 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003640 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003642 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 (currentTime - entry->eventTime) * 0.000001f);
3644 }
3645 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003646 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 }
3648
Michael Wright78f24442014-08-06 15:55:28 -07003649 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003651 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3652 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3653 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003655 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3656 }
3657 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003658 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003659 }
3660
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003662 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3664 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003665 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003667 i, connection->getInputChannelName().c_str(),
3668 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 connection->getStatusLabel(), toString(connection->monitor),
3670 toString(connection->inputPublisherBlocked));
3671
3672 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003673 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 connection->outboundQueue.count());
3675 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3676 entry = entry->next) {
3677 dump.append(INDENT4);
3678 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003679 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 entry->targetFlags, entry->resolvedAction,
3681 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3682 }
3683 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 }
3686
3687 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003688 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 connection->waitQueue.count());
3690 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3691 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003692 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003694 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 "age=%0.1fms, wait=%0.1fms\n",
3696 entry->targetFlags, entry->resolvedAction,
3697 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3698 (currentTime - entry->deliveryTime) * 0.000001f);
3699 }
3700 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003701 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 }
3703 }
3704 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003705 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
3707
3708 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003709 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 (mAppSwitchDueTime - now()) / 1000000.0);
3711 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003712 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 }
3714
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003715 dump += INDENT "Configuration:\n";
3716 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003718 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 mConfig.keyRepeatTimeout * 0.000001f);
3720}
3721
Robert Carr803535b2018-08-02 16:38:15 -07003722status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003724 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3725 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726#endif
3727
3728 { // acquire lock
3729 AutoMutex _l(mLock);
3730
Robert Carr4e670e52018-08-15 13:26:12 -07003731 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3732 // treat inputChannel as monitor channel for displayId.
3733 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3734 if (monitor) {
3735 inputChannel->setToken(new BBinder());
3736 }
3737
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 if (getConnectionIndexLocked(inputChannel) >= 0) {
3739 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003740 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 return BAD_VALUE;
3742 }
3743
Robert Carr803535b2018-08-02 16:38:15 -07003744 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745
3746 int fd = inputChannel->getFd();
3747 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003748 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003750 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003752 Vector<sp<InputChannel>>& monitoringChannels =
3753 mMonitoringChannelsByDisplay[displayId];
3754 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
3756
3757 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3758 } // release lock
3759
3760 // Wake the looper because some connections have changed.
3761 mLooper->wake();
3762 return OK;
3763}
3764
3765status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3766#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003767 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768#endif
3769
3770 { // acquire lock
3771 AutoMutex _l(mLock);
3772
3773 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3774 if (status) {
3775 return status;
3776 }
3777 } // release lock
3778
3779 // Wake the poll loop because removing the connection may have changed the current
3780 // synchronization state.
3781 mLooper->wake();
3782 return OK;
3783}
3784
3785status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3786 bool notify) {
3787 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3788 if (connectionIndex < 0) {
3789 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003790 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 return BAD_VALUE;
3792 }
3793
3794 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3795 mConnectionsByFd.removeItemsAt(connectionIndex);
3796
Robert Carr5c8a0262018-10-03 16:30:44 -07003797 mInputChannelsByToken.erase(inputChannel->getToken());
3798
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 if (connection->monitor) {
3800 removeMonitorChannelLocked(inputChannel);
3801 }
3802
3803 mLooper->removeFd(inputChannel->getFd());
3804
3805 nsecs_t currentTime = now();
3806 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3807
3808 connection->status = Connection::STATUS_ZOMBIE;
3809 return OK;
3810}
3811
3812void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003813 for (auto it = mMonitoringChannelsByDisplay.begin();
3814 it != mMonitoringChannelsByDisplay.end(); ) {
3815 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3816 const size_t numChannels = monitoringChannels.size();
3817 for (size_t i = 0; i < numChannels; i++) {
3818 if (monitoringChannels[i] == inputChannel) {
3819 monitoringChannels.removeAt(i);
3820 break;
3821 }
3822 }
3823 if (monitoringChannels.empty()) {
3824 it = mMonitoringChannelsByDisplay.erase(it);
3825 } else {
3826 ++it;
3827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
3829}
3830
3831ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003832 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003833 return -1;
3834 }
3835
Robert Carr4e670e52018-08-15 13:26:12 -07003836 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3837 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3838 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3839 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 }
3841 }
Robert Carr4e670e52018-08-15 13:26:12 -07003842
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 return -1;
3844}
3845
3846void InputDispatcher::onDispatchCycleFinishedLocked(
3847 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3848 CommandEntry* commandEntry = postCommandLocked(
3849 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3850 commandEntry->connection = connection;
3851 commandEntry->eventTime = currentTime;
3852 commandEntry->seq = seq;
3853 commandEntry->handled = handled;
3854}
3855
3856void InputDispatcher::onDispatchCycleBrokenLocked(
3857 nsecs_t currentTime, const sp<Connection>& connection) {
3858 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003859 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860
3861 CommandEntry* commandEntry = postCommandLocked(
3862 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3863 commandEntry->connection = connection;
3864}
3865
chaviw0c06c6e2019-01-09 13:27:07 -08003866void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3867 const sp<InputWindowHandle>& newFocus) {
3868 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3869 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003870 CommandEntry* commandEntry = postCommandLocked(
3871 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003872 commandEntry->oldToken = oldToken;
3873 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003874}
3875
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876void InputDispatcher::onANRLocked(
3877 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3878 const sp<InputWindowHandle>& windowHandle,
3879 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3880 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3881 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3882 ALOGI("Application is not responding: %s. "
3883 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003884 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885 dispatchLatency, waitDuration, reason);
3886
3887 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003888 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 struct tm tm;
3890 localtime_r(&t, &tm);
3891 char timestr[64];
3892 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3893 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003894 mLastANRState += INDENT "ANR:\n";
3895 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3896 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003897 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003898 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3899 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3900 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 dumpDispatchStateLocked(mLastANRState);
3902
3903 CommandEntry* commandEntry = postCommandLocked(
3904 & InputDispatcher::doNotifyANRLockedInterruptible);
3905 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003906 commandEntry->inputChannel = windowHandle != nullptr ?
3907 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 commandEntry->reason = reason;
3909}
3910
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003911void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 CommandEntry* commandEntry) {
3913 mLock.unlock();
3914
3915 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3916
3917 mLock.lock();
3918}
3919
3920void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3921 CommandEntry* commandEntry) {
3922 sp<Connection> connection = commandEntry->connection;
3923
3924 if (connection->status != Connection::STATUS_ZOMBIE) {
3925 mLock.unlock();
3926
Robert Carr803535b2018-08-02 16:38:15 -07003927 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928
3929 mLock.lock();
3930 }
3931}
3932
Robert Carrf759f162018-11-13 12:57:11 -08003933void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3934 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003935 sp<IBinder> oldToken = commandEntry->oldToken;
3936 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003937 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003938 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003939 mLock.lock();
3940}
3941
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942void InputDispatcher::doNotifyANRLockedInterruptible(
3943 CommandEntry* commandEntry) {
3944 mLock.unlock();
3945
3946 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003947 commandEntry->inputApplicationHandle,
3948 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 commandEntry->reason);
3950
3951 mLock.lock();
3952
3953 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003954 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955}
3956
3957void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3958 CommandEntry* commandEntry) {
3959 KeyEntry* entry = commandEntry->keyEntry;
3960
3961 KeyEvent event;
3962 initializeKeyEvent(&event, entry);
3963
3964 mLock.unlock();
3965
Michael Wright2b3c3302018-03-02 17:19:13 +00003966 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003967 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3968 commandEntry->inputChannel->getToken() : nullptr;
3969 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003971 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3972 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3973 std::to_string(t.duration().count()).c_str());
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
3976 mLock.lock();
3977
3978 if (delay < 0) {
3979 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3980 } else if (!delay) {
3981 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3982 } else {
3983 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3984 entry->interceptKeyWakeupTime = now() + delay;
3985 }
3986 entry->release();
3987}
3988
3989void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3990 CommandEntry* commandEntry) {
3991 sp<Connection> connection = commandEntry->connection;
3992 nsecs_t finishTime = commandEntry->eventTime;
3993 uint32_t seq = commandEntry->seq;
3994 bool handled = commandEntry->handled;
3995
3996 // Handle post-event policy actions.
3997 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3998 if (dispatchEntry) {
3999 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4000 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004001 std::string msg =
4002 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004003 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004005 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 }
4007
4008 bool restartEvent;
4009 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4010 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4011 restartEvent = afterKeyEventLockedInterruptible(connection,
4012 dispatchEntry, keyEntry, handled);
4013 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4014 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4015 restartEvent = afterMotionEventLockedInterruptible(connection,
4016 dispatchEntry, motionEntry, handled);
4017 } else {
4018 restartEvent = false;
4019 }
4020
4021 // Dequeue the event and start the next cycle.
4022 // Note that because the lock might have been released, it is possible that the
4023 // contents of the wait queue to have been drained, so we need to double-check
4024 // a few things.
4025 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4026 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004027 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4029 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004030 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 } else {
4032 releaseDispatchEntryLocked(dispatchEntry);
4033 }
4034 }
4035
4036 // Start the next dispatch cycle for this connection.
4037 startDispatchCycleLocked(now(), connection);
4038 }
4039}
4040
4041bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4042 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004043 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004044 if (!handled) {
4045 // Report the key as unhandled, since the fallback was not handled.
4046 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4047 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004048 return false;
4049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004051 // Get the fallback key state.
4052 // Clear it out after dispatching the UP.
4053 int32_t originalKeyCode = keyEntry->keyCode;
4054 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4055 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4056 connection->inputState.removeFallbackKey(originalKeyCode);
4057 }
4058
4059 if (handled || !dispatchEntry->hasForegroundTarget()) {
4060 // If the application handles the original key for which we previously
4061 // generated a fallback or if the window is not a foreground window,
4062 // then cancel the associated fallback key, if any.
4063 if (fallbackKeyCode != -1) {
4064 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004066 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4068 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4069 keyEntry->policyFlags);
4070#endif
4071 KeyEvent event;
4072 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004073 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
4075 mLock.unlock();
4076
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004077 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4078 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
4080 mLock.lock();
4081
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004082 // Cancel the fallback key.
4083 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004085 "application handled the original non-fallback key "
4086 "or is no longer a foreground target, "
4087 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 options.keyCode = fallbackKeyCode;
4089 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004091 connection->inputState.removeFallbackKey(originalKeyCode);
4092 }
4093 } else {
4094 // If the application did not handle a non-fallback key, first check
4095 // that we are in a good state to perform unhandled key event processing
4096 // Then ask the policy what to do with it.
4097 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4098 && keyEntry->repeatCount == 0;
4099 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004101 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4102 "since this is not an initial down. "
4103 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4104 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4105 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004107 return false;
4108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004110 // Dispatch the unhandled key to the policy.
4111#if DEBUG_OUTBOUND_EVENT_DETAILS
4112 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4113 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4114 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4115 keyEntry->policyFlags);
4116#endif
4117 KeyEvent event;
4118 initializeKeyEvent(&event, keyEntry);
4119
4120 mLock.unlock();
4121
4122 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4123 &event, keyEntry->policyFlags, &event);
4124
4125 mLock.lock();
4126
4127 if (connection->status != Connection::STATUS_NORMAL) {
4128 connection->inputState.removeFallbackKey(originalKeyCode);
4129 return false;
4130 }
4131
4132 // Latch the fallback keycode for this key on an initial down.
4133 // The fallback keycode cannot change at any other point in the lifecycle.
4134 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004136 fallbackKeyCode = event.getKeyCode();
4137 } else {
4138 fallbackKeyCode = AKEYCODE_UNKNOWN;
4139 }
4140 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4141 }
4142
4143 ALOG_ASSERT(fallbackKeyCode != -1);
4144
4145 // Cancel the fallback key if the policy decides not to send it anymore.
4146 // We will continue to dispatch the key to the policy but we will no
4147 // longer dispatch a fallback key to the application.
4148 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4149 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4150#if DEBUG_OUTBOUND_EVENT_DETAILS
4151 if (fallback) {
4152 ALOGD("Unhandled key event: Policy requested to send key %d"
4153 "as a fallback for %d, but on the DOWN it had requested "
4154 "to send %d instead. Fallback canceled.",
4155 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4156 } else {
4157 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4158 "but on the DOWN it had requested to send %d. "
4159 "Fallback canceled.",
4160 originalKeyCode, fallbackKeyCode);
4161 }
4162#endif
4163
4164 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4165 "canceling fallback, policy no longer desires it");
4166 options.keyCode = fallbackKeyCode;
4167 synthesizeCancelationEventsForConnectionLocked(connection, options);
4168
4169 fallback = false;
4170 fallbackKeyCode = AKEYCODE_UNKNOWN;
4171 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4172 connection->inputState.setFallbackKey(originalKeyCode,
4173 fallbackKeyCode);
4174 }
4175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176
4177#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004178 {
4179 std::string msg;
4180 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4181 connection->inputState.getFallbackKeys();
4182 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4183 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4184 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004186 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4187 fallbackKeys.size(), msg.c_str());
4188 }
4189#endif
4190
4191 if (fallback) {
4192 // Restart the dispatch cycle using the fallback key.
4193 keyEntry->eventTime = event.getEventTime();
4194 keyEntry->deviceId = event.getDeviceId();
4195 keyEntry->source = event.getSource();
4196 keyEntry->displayId = event.getDisplayId();
4197 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4198 keyEntry->keyCode = fallbackKeyCode;
4199 keyEntry->scanCode = event.getScanCode();
4200 keyEntry->metaState = event.getMetaState();
4201 keyEntry->repeatCount = event.getRepeatCount();
4202 keyEntry->downTime = event.getDownTime();
4203 keyEntry->syntheticRepeat = false;
4204
4205#if DEBUG_OUTBOUND_EVENT_DETAILS
4206 ALOGD("Unhandled key event: Dispatching fallback key. "
4207 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4208 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4209#endif
4210 return true; // restart the event
4211 } else {
4212#if DEBUG_OUTBOUND_EVENT_DETAILS
4213 ALOGD("Unhandled key event: No fallback key.");
4214#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004215
4216 // Report the key as unhandled, since there is no fallback key.
4217 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 }
4219 }
4220 return false;
4221}
4222
4223bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4224 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4225 return false;
4226}
4227
4228void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4229 mLock.unlock();
4230
4231 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4232
4233 mLock.lock();
4234}
4235
4236void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004237 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4239 entry->downTime, entry->eventTime);
4240}
4241
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004242void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4244 // TODO Write some statistics about how long we spend waiting.
4245}
4246
4247void InputDispatcher::traceInboundQueueLengthLocked() {
4248 if (ATRACE_ENABLED()) {
4249 ATRACE_INT("iq", mInboundQueue.count());
4250 }
4251}
4252
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004253void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 if (ATRACE_ENABLED()) {
4255 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004256 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 ATRACE_INT(counterName, connection->outboundQueue.count());
4258 }
4259}
4260
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004261void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 if (ATRACE_ENABLED()) {
4263 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004264 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 ATRACE_INT(counterName, connection->waitQueue.count());
4266 }
4267}
4268
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004269void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 AutoMutex _l(mLock);
4271
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 dumpDispatchStateLocked(dump);
4274
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 if (!mLastANRState.empty()) {
4276 dump += "\nInput Dispatcher State at time of last ANR:\n";
4277 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279}
4280
4281void InputDispatcher::monitor() {
4282 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4283 mLock.lock();
4284 mLooper->wake();
4285 mDispatcherIsAliveCondition.wait(mLock);
4286 mLock.unlock();
4287}
4288
4289
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290// --- InputDispatcher::InjectionState ---
4291
4292InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4293 refCount(1),
4294 injectorPid(injectorPid), injectorUid(injectorUid),
4295 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4296 pendingForegroundDispatches(0) {
4297}
4298
4299InputDispatcher::InjectionState::~InjectionState() {
4300}
4301
4302void InputDispatcher::InjectionState::release() {
4303 refCount -= 1;
4304 if (refCount == 0) {
4305 delete this;
4306 } else {
4307 ALOG_ASSERT(refCount > 0);
4308 }
4309}
4310
4311
4312// --- InputDispatcher::EventEntry ---
4313
Prabir Pradhan42611e02018-11-27 14:04:02 -08004314InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4315 nsecs_t eventTime, uint32_t policyFlags) :
4316 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4317 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318}
4319
4320InputDispatcher::EventEntry::~EventEntry() {
4321 releaseInjectionState();
4322}
4323
4324void InputDispatcher::EventEntry::release() {
4325 refCount -= 1;
4326 if (refCount == 0) {
4327 delete this;
4328 } else {
4329 ALOG_ASSERT(refCount > 0);
4330 }
4331}
4332
4333void InputDispatcher::EventEntry::releaseInjectionState() {
4334 if (injectionState) {
4335 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004336 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 }
4338}
4339
4340
4341// --- InputDispatcher::ConfigurationChangedEntry ---
4342
Prabir Pradhan42611e02018-11-27 14:04:02 -08004343InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4344 uint32_t sequenceNum, nsecs_t eventTime) :
4345 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346}
4347
4348InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4349}
4350
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004351void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4352 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353}
4354
4355
4356// --- InputDispatcher::DeviceResetEntry ---
4357
Prabir Pradhan42611e02018-11-27 14:04:02 -08004358InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4359 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4360 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 deviceId(deviceId) {
4362}
4363
4364InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4365}
4366
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004367void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4368 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 deviceId, policyFlags);
4370}
4371
4372
4373// --- InputDispatcher::KeyEntry ---
4374
Prabir Pradhan42611e02018-11-27 14:04:02 -08004375InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004376 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4378 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004379 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004380 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4382 repeatCount(repeatCount), downTime(downTime),
4383 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4384 interceptKeyWakeupTime(0) {
4385}
4386
4387InputDispatcher::KeyEntry::~KeyEntry() {
4388}
4389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004390void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004391 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4393 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004394 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004395 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396}
4397
4398void InputDispatcher::KeyEntry::recycle() {
4399 releaseInjectionState();
4400
4401 dispatchInProgress = false;
4402 syntheticRepeat = false;
4403 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4404 interceptKeyWakeupTime = 0;
4405}
4406
4407
4408// --- InputDispatcher::MotionEntry ---
4409
Prabir Pradhan42611e02018-11-27 14:04:02 -08004410InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004411 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4412 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004413 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4414 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004415 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004416 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4417 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004418 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004420 deviceId(deviceId), source(source), displayId(displayId), action(action),
4421 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004422 classification(classification), edgeFlags(edgeFlags),
4423 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004424 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 for (uint32_t i = 0; i < pointerCount; i++) {
4426 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4427 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004428 if (xOffset || yOffset) {
4429 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 }
4432}
4433
4434InputDispatcher::MotionEntry::~MotionEntry() {
4435}
4436
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004437void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004438 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004439 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004440 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004441 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004442 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4443 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004444
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 for (uint32_t i = 0; i < pointerCount; i++) {
4446 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004447 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004449 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 pointerCoords[i].getX(), pointerCoords[i].getY());
4451 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004452 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453}
4454
4455
4456// --- InputDispatcher::DispatchEntry ---
4457
4458volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4459
4460InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004461 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4462 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 seq(nextSeq()),
4464 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004465 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4466 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4468 eventEntry->refCount += 1;
4469}
4470
4471InputDispatcher::DispatchEntry::~DispatchEntry() {
4472 eventEntry->release();
4473}
4474
4475uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4476 // Sequence number 0 is reserved and will never be returned.
4477 uint32_t seq;
4478 do {
4479 seq = android_atomic_inc(&sNextSeqAtomic);
4480 } while (!seq);
4481 return seq;
4482}
4483
4484
4485// --- InputDispatcher::InputState ---
4486
4487InputDispatcher::InputState::InputState() {
4488}
4489
4490InputDispatcher::InputState::~InputState() {
4491}
4492
4493bool InputDispatcher::InputState::isNeutral() const {
4494 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4495}
4496
4497bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4498 int32_t displayId) const {
4499 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4500 const MotionMemento& memento = mMotionMementos.itemAt(i);
4501 if (memento.deviceId == deviceId
4502 && memento.source == source
4503 && memento.displayId == displayId
4504 && memento.hovering) {
4505 return true;
4506 }
4507 }
4508 return false;
4509}
4510
4511bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4512 int32_t action, int32_t flags) {
4513 switch (action) {
4514 case AKEY_EVENT_ACTION_UP: {
4515 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4516 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4517 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4518 mFallbackKeys.removeItemsAt(i);
4519 } else {
4520 i += 1;
4521 }
4522 }
4523 }
4524 ssize_t index = findKeyMemento(entry);
4525 if (index >= 0) {
4526 mKeyMementos.removeAt(index);
4527 return true;
4528 }
4529 /* FIXME: We can't just drop the key up event because that prevents creating
4530 * popup windows that are automatically shown when a key is held and then
4531 * dismissed when the key is released. The problem is that the popup will
4532 * not have received the original key down, so the key up will be considered
4533 * to be inconsistent with its observed state. We could perhaps handle this
4534 * by synthesizing a key down but that will cause other problems.
4535 *
4536 * So for now, allow inconsistent key up events to be dispatched.
4537 *
4538#if DEBUG_OUTBOUND_EVENT_DETAILS
4539 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4540 "keyCode=%d, scanCode=%d",
4541 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4542#endif
4543 return false;
4544 */
4545 return true;
4546 }
4547
4548 case AKEY_EVENT_ACTION_DOWN: {
4549 ssize_t index = findKeyMemento(entry);
4550 if (index >= 0) {
4551 mKeyMementos.removeAt(index);
4552 }
4553 addKeyMemento(entry, flags);
4554 return true;
4555 }
4556
4557 default:
4558 return true;
4559 }
4560}
4561
4562bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4563 int32_t action, int32_t flags) {
4564 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4565 switch (actionMasked) {
4566 case AMOTION_EVENT_ACTION_UP:
4567 case AMOTION_EVENT_ACTION_CANCEL: {
4568 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4569 if (index >= 0) {
4570 mMotionMementos.removeAt(index);
4571 return true;
4572 }
4573#if DEBUG_OUTBOUND_EVENT_DETAILS
4574 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004575 "displayId=%" PRId32 ", actionMasked=%d",
4576 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577#endif
4578 return false;
4579 }
4580
4581 case AMOTION_EVENT_ACTION_DOWN: {
4582 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4583 if (index >= 0) {
4584 mMotionMementos.removeAt(index);
4585 }
4586 addMotionMemento(entry, flags, false /*hovering*/);
4587 return true;
4588 }
4589
4590 case AMOTION_EVENT_ACTION_POINTER_UP:
4591 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4592 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004593 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4594 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4595 // generate cancellation events for these since they're based in relative rather than
4596 // absolute units.
4597 return true;
4598 }
4599
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004601
4602 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4603 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4604 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4605 // other value and we need to track the motion so we can send cancellation events for
4606 // anything generating fallback events (e.g. DPad keys for joystick movements).
4607 if (index >= 0) {
4608 if (entry->pointerCoords[0].isEmpty()) {
4609 mMotionMementos.removeAt(index);
4610 } else {
4611 MotionMemento& memento = mMotionMementos.editItemAt(index);
4612 memento.setPointers(entry);
4613 }
4614 } else if (!entry->pointerCoords[0].isEmpty()) {
4615 addMotionMemento(entry, flags, false /*hovering*/);
4616 }
4617
4618 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4619 return true;
4620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621 if (index >= 0) {
4622 MotionMemento& memento = mMotionMementos.editItemAt(index);
4623 memento.setPointers(entry);
4624 return true;
4625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626#if DEBUG_OUTBOUND_EVENT_DETAILS
4627 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004628 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4629 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630#endif
4631 return false;
4632 }
4633
4634 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4635 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4636 if (index >= 0) {
4637 mMotionMementos.removeAt(index);
4638 return true;
4639 }
4640#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004641 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4642 "displayId=%" PRId32,
4643 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644#endif
4645 return false;
4646 }
4647
4648 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4649 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4650 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4651 if (index >= 0) {
4652 mMotionMementos.removeAt(index);
4653 }
4654 addMotionMemento(entry, flags, true /*hovering*/);
4655 return true;
4656 }
4657
4658 default:
4659 return true;
4660 }
4661}
4662
4663ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4664 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4665 const KeyMemento& memento = mKeyMementos.itemAt(i);
4666 if (memento.deviceId == entry->deviceId
4667 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004668 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 && memento.keyCode == entry->keyCode
4670 && memento.scanCode == entry->scanCode) {
4671 return i;
4672 }
4673 }
4674 return -1;
4675}
4676
4677ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4678 bool hovering) const {
4679 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4680 const MotionMemento& memento = mMotionMementos.itemAt(i);
4681 if (memento.deviceId == entry->deviceId
4682 && memento.source == entry->source
4683 && memento.displayId == entry->displayId
4684 && memento.hovering == hovering) {
4685 return i;
4686 }
4687 }
4688 return -1;
4689}
4690
4691void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4692 mKeyMementos.push();
4693 KeyMemento& memento = mKeyMementos.editTop();
4694 memento.deviceId = entry->deviceId;
4695 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004696 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 memento.keyCode = entry->keyCode;
4698 memento.scanCode = entry->scanCode;
4699 memento.metaState = entry->metaState;
4700 memento.flags = flags;
4701 memento.downTime = entry->downTime;
4702 memento.policyFlags = entry->policyFlags;
4703}
4704
4705void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4706 int32_t flags, bool hovering) {
4707 mMotionMementos.push();
4708 MotionMemento& memento = mMotionMementos.editTop();
4709 memento.deviceId = entry->deviceId;
4710 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004711 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 memento.flags = flags;
4713 memento.xPrecision = entry->xPrecision;
4714 memento.yPrecision = entry->yPrecision;
4715 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 memento.setPointers(entry);
4717 memento.hovering = hovering;
4718 memento.policyFlags = entry->policyFlags;
4719}
4720
4721void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4722 pointerCount = entry->pointerCount;
4723 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4724 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4725 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4726 }
4727}
4728
4729void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4730 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4731 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4732 const KeyMemento& memento = mKeyMementos.itemAt(i);
4733 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004734 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004735 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4737 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4738 }
4739 }
4740
4741 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4742 const MotionMemento& memento = mMotionMementos.itemAt(i);
4743 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004744 const int32_t action = memento.hovering ?
4745 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004746 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004747 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004748 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4749 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004751 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004752 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 }
4754 }
4755}
4756
4757void InputDispatcher::InputState::clear() {
4758 mKeyMementos.clear();
4759 mMotionMementos.clear();
4760 mFallbackKeys.clear();
4761}
4762
4763void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4764 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4765 const MotionMemento& memento = mMotionMementos.itemAt(i);
4766 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4767 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4768 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4769 if (memento.deviceId == otherMemento.deviceId
4770 && memento.source == otherMemento.source
4771 && memento.displayId == otherMemento.displayId) {
4772 other.mMotionMementos.removeAt(j);
4773 } else {
4774 j += 1;
4775 }
4776 }
4777 other.mMotionMementos.push(memento);
4778 }
4779 }
4780}
4781
4782int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4783 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4784 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4785}
4786
4787void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4788 int32_t fallbackKeyCode) {
4789 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4790 if (index >= 0) {
4791 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4792 } else {
4793 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4794 }
4795}
4796
4797void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4798 mFallbackKeys.removeItem(originalKeyCode);
4799}
4800
4801bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4802 const CancelationOptions& options) {
4803 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4804 return false;
4805 }
4806
4807 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4808 return false;
4809 }
4810
4811 switch (options.mode) {
4812 case CancelationOptions::CANCEL_ALL_EVENTS:
4813 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4814 return true;
4815 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4816 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004817 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4818 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 default:
4820 return false;
4821 }
4822}
4823
4824bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4825 const CancelationOptions& options) {
4826 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4827 return false;
4828 }
4829
4830 switch (options.mode) {
4831 case CancelationOptions::CANCEL_ALL_EVENTS:
4832 return true;
4833 case CancelationOptions::CANCEL_POINTER_EVENTS:
4834 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4835 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4836 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004837 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4838 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 default:
4840 return false;
4841 }
4842}
4843
4844
4845// --- InputDispatcher::Connection ---
4846
Robert Carr803535b2018-08-02 16:38:15 -07004847InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4848 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 monitor(monitor),
4850 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4851}
4852
4853InputDispatcher::Connection::~Connection() {
4854}
4855
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004856const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004857 if (inputChannel != nullptr) {
4858 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 }
4860 if (monitor) {
4861 return "monitor";
4862 }
4863 return "?";
4864}
4865
4866const char* InputDispatcher::Connection::getStatusLabel() const {
4867 switch (status) {
4868 case STATUS_NORMAL:
4869 return "NORMAL";
4870
4871 case STATUS_BROKEN:
4872 return "BROKEN";
4873
4874 case STATUS_ZOMBIE:
4875 return "ZOMBIE";
4876
4877 default:
4878 return "UNKNOWN";
4879 }
4880}
4881
4882InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004883 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 if (entry->seq == seq) {
4885 return entry;
4886 }
4887 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004888 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889}
4890
4891
4892// --- InputDispatcher::CommandEntry ---
4893
4894InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004895 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 seq(0), handled(false) {
4897}
4898
4899InputDispatcher::CommandEntry::~CommandEntry() {
4900}
4901
4902
4903// --- InputDispatcher::TouchState ---
4904
4905InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004906 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907}
4908
4909InputDispatcher::TouchState::~TouchState() {
4910}
4911
4912void InputDispatcher::TouchState::reset() {
4913 down = false;
4914 split = false;
4915 deviceId = -1;
4916 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004917 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004919 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920}
4921
4922void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4923 down = other.down;
4924 split = other.split;
4925 deviceId = other.deviceId;
4926 source = other.source;
4927 displayId = other.displayId;
4928 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004929 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930}
4931
4932void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4933 int32_t targetFlags, BitSet32 pointerIds) {
4934 if (targetFlags & InputTarget::FLAG_SPLIT) {
4935 split = true;
4936 }
4937
4938 for (size_t i = 0; i < windows.size(); i++) {
4939 TouchedWindow& touchedWindow = windows.editItemAt(i);
4940 if (touchedWindow.windowHandle == windowHandle) {
4941 touchedWindow.targetFlags |= targetFlags;
4942 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4943 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4944 }
4945 touchedWindow.pointerIds.value |= pointerIds.value;
4946 return;
4947 }
4948 }
4949
4950 windows.push();
4951
4952 TouchedWindow& touchedWindow = windows.editTop();
4953 touchedWindow.windowHandle = windowHandle;
4954 touchedWindow.targetFlags = targetFlags;
4955 touchedWindow.pointerIds = pointerIds;
4956}
4957
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004958void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4959 size_t numWindows = portalWindows.size();
4960 for (size_t i = 0; i < numWindows; i++) {
4961 sp<InputWindowHandle> portalWindowHandle = portalWindows.itemAt(i);
4962 if (portalWindowHandle == windowHandle) {
4963 return;
4964 }
4965 }
4966 portalWindows.push_back(windowHandle);
4967}
4968
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4970 for (size_t i = 0; i < windows.size(); i++) {
4971 if (windows.itemAt(i).windowHandle == windowHandle) {
4972 windows.removeAt(i);
4973 return;
4974 }
4975 }
4976}
4977
Robert Carr803535b2018-08-02 16:38:15 -07004978void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4979 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004980 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004981 windows.removeAt(i);
4982 return;
4983 }
4984 }
4985}
4986
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4988 for (size_t i = 0 ; i < windows.size(); ) {
4989 TouchedWindow& window = windows.editItemAt(i);
4990 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4991 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4992 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4993 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4994 i += 1;
4995 } else {
4996 windows.removeAt(i);
4997 }
4998 }
4999}
5000
5001sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5002 for (size_t i = 0; i < windows.size(); i++) {
5003 const TouchedWindow& window = windows.itemAt(i);
5004 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5005 return window.windowHandle;
5006 }
5007 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005008 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009}
5010
5011bool InputDispatcher::TouchState::isSlippery() const {
5012 // Must have exactly one foreground window.
5013 bool haveSlipperyForegroundWindow = false;
5014 for (size_t i = 0; i < windows.size(); i++) {
5015 const TouchedWindow& window = windows.itemAt(i);
5016 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5017 if (haveSlipperyForegroundWindow
5018 || !(window.windowHandle->getInfo()->layoutParamsFlags
5019 & InputWindowInfo::FLAG_SLIPPERY)) {
5020 return false;
5021 }
5022 haveSlipperyForegroundWindow = true;
5023 }
5024 }
5025 return haveSlipperyForegroundWindow;
5026}
5027
5028
5029// --- InputDispatcherThread ---
5030
5031InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5032 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5033}
5034
5035InputDispatcherThread::~InputDispatcherThread() {
5036}
5037
5038bool InputDispatcherThread::threadLoop() {
5039 mDispatcher->dispatchOnce();
5040 return true;
5041}
5042
5043} // namespace android