blob: d2887366138b6c149f24d600dd544b2dc88897e1 [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,
chaviw291d88a2019-02-14 10:33:58 -08003075 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
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();
chaviw291d88a2019-02-14 10:33:58 -08003225
3226 if (setInputWindowsListener) {
3227 setInputWindowsListener->onSetInputWindowsFinished();
3228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229}
3230
3231void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003232 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003234 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235#endif
3236 { // acquire lock
3237 AutoMutex _l(mLock);
3238
Tiger Huang721e26f2018-07-24 22:26:19 +08003239 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3240 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003241 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003242 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3243 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003245 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003247 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003249 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003251 oldFocusedApplicationHandle->releaseInfo();
3252 oldFocusedApplicationHandle.clear();
3253 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 }
3255
3256#if DEBUG_FOCUS
3257 //logDispatchStateLocked();
3258#endif
3259 } // release lock
3260
3261 // Wake up poll loop since it may need to make new input dispatching choices.
3262 mLooper->wake();
3263}
3264
Tiger Huang721e26f2018-07-24 22:26:19 +08003265/**
3266 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3267 * the display not specified.
3268 *
3269 * We track any unreleased events for each window. If a window loses the ability to receive the
3270 * released event, we will send a cancel event to it. So when the focused display is changed, we
3271 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3272 * display. The display-specified events won't be affected.
3273 */
3274void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3275#if DEBUG_FOCUS
3276 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3277#endif
3278 { // acquire lock
3279 AutoMutex _l(mLock);
3280
3281 if (mFocusedDisplayId != displayId) {
3282 sp<InputWindowHandle> oldFocusedWindowHandle =
3283 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3284 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003285 sp<InputChannel> inputChannel =
3286 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003287 if (inputChannel != nullptr) {
3288 CancelationOptions options(
3289 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3290 "The display which contains this window no longer has focus.");
3291 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3292 }
3293 }
3294 mFocusedDisplayId = displayId;
3295
3296 // Sanity check
3297 sp<InputWindowHandle> newFocusedWindowHandle =
3298 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003299 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003300
Tiger Huang721e26f2018-07-24 22:26:19 +08003301 if (newFocusedWindowHandle == nullptr) {
3302 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3303 if (!mFocusedWindowHandlesByDisplay.empty()) {
3304 ALOGE("But another display has a focused window:");
3305 for (auto& it : mFocusedWindowHandlesByDisplay) {
3306 const int32_t displayId = it.first;
3307 const sp<InputWindowHandle>& windowHandle = it.second;
3308 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3309 displayId, windowHandle->getName().c_str());
3310 }
3311 }
3312 }
3313 }
3314
3315#if DEBUG_FOCUS
3316 logDispatchStateLocked();
3317#endif
3318 } // release lock
3319
3320 // Wake up poll loop since it may need to make new input dispatching choices.
3321 mLooper->wake();
3322}
3323
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3325#if DEBUG_FOCUS
3326 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3327#endif
3328
3329 bool changed;
3330 { // acquire lock
3331 AutoMutex _l(mLock);
3332
3333 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3334 if (mDispatchFrozen && !frozen) {
3335 resetANRTimeoutsLocked();
3336 }
3337
3338 if (mDispatchEnabled && !enabled) {
3339 resetAndDropEverythingLocked("dispatcher is being disabled");
3340 }
3341
3342 mDispatchEnabled = enabled;
3343 mDispatchFrozen = frozen;
3344 changed = true;
3345 } else {
3346 changed = false;
3347 }
3348
3349#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003350 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351#endif
3352 } // release lock
3353
3354 if (changed) {
3355 // Wake up poll loop since it may need to make new input dispatching choices.
3356 mLooper->wake();
3357 }
3358}
3359
3360void InputDispatcher::setInputFilterEnabled(bool enabled) {
3361#if DEBUG_FOCUS
3362 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3363#endif
3364
3365 { // acquire lock
3366 AutoMutex _l(mLock);
3367
3368 if (mInputFilterEnabled == enabled) {
3369 return;
3370 }
3371
3372 mInputFilterEnabled = enabled;
3373 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3374 } // release lock
3375
3376 // Wake up poll loop since there might be work to do to drop everything.
3377 mLooper->wake();
3378}
3379
chaviwfbe5d9c2018-12-26 12:23:37 -08003380bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3381 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003383 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003385 return true;
3386 }
3387
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 { // acquire lock
3389 AutoMutex _l(mLock);
3390
chaviwfbe5d9c2018-12-26 12:23:37 -08003391 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3392 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003393 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003394 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 return false;
3396 }
chaviw4f2dd402018-12-26 15:30:27 -08003397#if DEBUG_FOCUS
3398 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3399 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3400#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3402#if DEBUG_FOCUS
3403 ALOGD("Cannot transfer focus because windows are on different displays.");
3404#endif
3405 return false;
3406 }
3407
3408 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003409 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3410 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3411 for (size_t i = 0; i < state.windows.size(); i++) {
3412 const TouchedWindow& touchedWindow = state.windows[i];
3413 if (touchedWindow.windowHandle == fromWindowHandle) {
3414 int32_t oldTargetFlags = touchedWindow.targetFlags;
3415 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
Jeff Brownf086ddb2014-02-11 14:28:48 -08003417 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418
Jeff Brownf086ddb2014-02-11 14:28:48 -08003419 int32_t newTargetFlags = oldTargetFlags
3420 & (InputTarget::FLAG_FOREGROUND
3421 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3422 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423
Jeff Brownf086ddb2014-02-11 14:28:48 -08003424 found = true;
3425 goto Found;
3426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
3428 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003429Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430
3431 if (! found) {
3432#if DEBUG_FOCUS
3433 ALOGD("Focus transfer failed because from window did not have focus.");
3434#endif
3435 return false;
3436 }
3437
chaviwfbe5d9c2018-12-26 12:23:37 -08003438
3439 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3440 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3442 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3443 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3444 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3445 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3446
3447 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3448 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3449 "transferring touch focus from this window to another window");
3450 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3451 }
3452
3453#if DEBUG_FOCUS
3454 logDispatchStateLocked();
3455#endif
3456 } // release lock
3457
3458 // Wake up poll loop since it may need to make new input dispatching choices.
3459 mLooper->wake();
3460 return true;
3461}
3462
3463void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3464#if DEBUG_FOCUS
3465 ALOGD("Resetting and dropping all events (%s).", reason);
3466#endif
3467
3468 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3469 synthesizeCancelationEventsForAllConnectionsLocked(options);
3470
3471 resetKeyRepeatLocked();
3472 releasePendingEventLocked();
3473 drainInboundQueueLocked();
3474 resetANRTimeoutsLocked();
3475
Jeff Brownf086ddb2014-02-11 14:28:48 -08003476 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003478 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479}
3480
3481void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003482 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 dumpDispatchStateLocked(dump);
3484
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003485 std::istringstream stream(dump);
3486 std::string line;
3487
3488 while (std::getline(stream, line, '\n')) {
3489 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 }
3491}
3492
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003493void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3494 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3495 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003496 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
Tiger Huang721e26f2018-07-24 22:26:19 +08003498 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3499 dump += StringPrintf(INDENT "FocusedApplications:\n");
3500 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3501 const int32_t displayId = it.first;
3502 const sp<InputApplicationHandle>& applicationHandle = it.second;
3503 dump += StringPrintf(
3504 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3505 displayId,
3506 applicationHandle->getName().c_str(),
3507 applicationHandle->getDispatchingTimeout(
3508 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003511 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003513
3514 if (!mFocusedWindowHandlesByDisplay.empty()) {
3515 dump += StringPrintf(INDENT "FocusedWindows:\n");
3516 for (auto& it : mFocusedWindowHandlesByDisplay) {
3517 const int32_t displayId = it.first;
3518 const sp<InputWindowHandle>& windowHandle = it.second;
3519 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3520 displayId, windowHandle->getName().c_str());
3521 }
3522 } else {
3523 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525
Jeff Brownf086ddb2014-02-11 14:28:48 -08003526 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003527 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003528 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3529 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003530 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003531 state.displayId, toString(state.down), toString(state.split),
3532 state.deviceId, state.source);
3533 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003534 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003535 for (size_t i = 0; i < state.windows.size(); i++) {
3536 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003537 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3538 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003539 touchedWindow.pointerIds.value,
3540 touchedWindow.targetFlags);
3541 }
3542 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003543 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003544 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003545 if (!state.portalWindows.isEmpty()) {
3546 dump += INDENT3 "Portal windows:\n";
3547 for (size_t i = 0; i < state.portalWindows.size(); i++) {
3548 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows.itemAt(i);
3549 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3550 i, portalWindowHandle->getName().c_str());
3551 }
3552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 }
3554 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003555 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 }
3557
Arthur Hungb92218b2018-08-14 12:00:21 +08003558 if (!mWindowHandlesByDisplay.empty()) {
3559 for (auto& it : mWindowHandlesByDisplay) {
3560 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003561 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003562 if (!windowHandles.isEmpty()) {
3563 dump += INDENT2 "Windows:\n";
3564 for (size_t i = 0; i < windowHandles.size(); i++) {
3565 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3566 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003569 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003570 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003571 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003572 "touchableRegion=",
3573 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003574 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003575 toString(windowInfo->paused),
3576 toString(windowInfo->hasFocus),
3577 toString(windowInfo->hasWallpaper),
3578 toString(windowInfo->visible),
3579 toString(windowInfo->canReceiveKeys),
3580 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3581 windowInfo->layer,
3582 windowInfo->frameLeft, windowInfo->frameTop,
3583 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003584 windowInfo->globalScaleFactor,
3585 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003586 dumpRegion(dump, windowInfo->touchableRegion);
3587 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3588 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3589 windowInfo->ownerPid, windowInfo->ownerUid,
3590 windowInfo->dispatchingTimeout / 1000000.0);
3591 }
3592 } else {
3593 dump += INDENT2 "Windows: <none>\n";
3594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
3596 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003597 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 }
3599
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003600 if (!mMonitoringChannelsByDisplay.empty()) {
3601 for (auto& it : mMonitoringChannelsByDisplay) {
3602 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003603 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003604 const size_t numChannels = monitoringChannels.size();
3605 for (size_t i = 0; i < numChannels; i++) {
3606 const sp<InputChannel>& channel = monitoringChannels[i];
3607 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3608 }
3609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003611 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
3613
3614 nsecs_t currentTime = now();
3615
3616 // Dump recently dispatched or dropped events from oldest to newest.
3617 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003618 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003622 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 (currentTime - entry->eventTime) * 0.000001f);
3624 }
3625 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003626 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 }
3628
3629 // Dump event currently being dispatched.
3630 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003631 dump += INDENT "PendingEvent:\n";
3632 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003634 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3636 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
3639
3640 // Dump inbound events from oldest to newest.
3641 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003642 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003644 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003646 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 (currentTime - entry->eventTime) * 0.000001f);
3648 }
3649 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 }
3652
Michael Wright78f24442014-08-06 15:55:28 -07003653 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003655 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3656 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3657 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003658 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003659 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3660 }
3661 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003662 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003663 }
3664
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003666 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3668 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003669 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003671 i, connection->getInputChannelName().c_str(),
3672 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 connection->getStatusLabel(), toString(connection->monitor),
3674 toString(connection->inputPublisherBlocked));
3675
3676 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003677 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 connection->outboundQueue.count());
3679 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3680 entry = entry->next) {
3681 dump.append(INDENT4);
3682 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003683 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 entry->targetFlags, entry->resolvedAction,
3685 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3686 }
3687 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003688 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
3690
3691 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003692 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 connection->waitQueue.count());
3694 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3695 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003698 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 "age=%0.1fms, wait=%0.1fms\n",
3700 entry->targetFlags, entry->resolvedAction,
3701 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3702 (currentTime - entry->deliveryTime) * 0.000001f);
3703 }
3704 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003705 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
3707 }
3708 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003709 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
3711
3712 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003713 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 (mAppSwitchDueTime - now()) / 1000000.0);
3715 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003716 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 }
3718
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003719 dump += INDENT "Configuration:\n";
3720 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003722 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 mConfig.keyRepeatTimeout * 0.000001f);
3724}
3725
Robert Carr803535b2018-08-02 16:38:15 -07003726status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003728 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3729 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730#endif
3731
3732 { // acquire lock
3733 AutoMutex _l(mLock);
3734
Robert Carr4e670e52018-08-15 13:26:12 -07003735 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3736 // treat inputChannel as monitor channel for displayId.
3737 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3738 if (monitor) {
3739 inputChannel->setToken(new BBinder());
3740 }
3741
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 if (getConnectionIndexLocked(inputChannel) >= 0) {
3743 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003744 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 return BAD_VALUE;
3746 }
3747
Robert Carr803535b2018-08-02 16:38:15 -07003748 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749
3750 int fd = inputChannel->getFd();
3751 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003752 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003754 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003756 Vector<sp<InputChannel>>& monitoringChannels =
3757 mMonitoringChannelsByDisplay[displayId];
3758 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 }
3760
3761 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3762 } // release lock
3763
3764 // Wake the looper because some connections have changed.
3765 mLooper->wake();
3766 return OK;
3767}
3768
3769status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3770#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003771 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772#endif
3773
3774 { // acquire lock
3775 AutoMutex _l(mLock);
3776
3777 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3778 if (status) {
3779 return status;
3780 }
3781 } // release lock
3782
3783 // Wake the poll loop because removing the connection may have changed the current
3784 // synchronization state.
3785 mLooper->wake();
3786 return OK;
3787}
3788
3789status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3790 bool notify) {
3791 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3792 if (connectionIndex < 0) {
3793 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003794 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 return BAD_VALUE;
3796 }
3797
3798 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3799 mConnectionsByFd.removeItemsAt(connectionIndex);
3800
Robert Carr5c8a0262018-10-03 16:30:44 -07003801 mInputChannelsByToken.erase(inputChannel->getToken());
3802
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 if (connection->monitor) {
3804 removeMonitorChannelLocked(inputChannel);
3805 }
3806
3807 mLooper->removeFd(inputChannel->getFd());
3808
3809 nsecs_t currentTime = now();
3810 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3811
3812 connection->status = Connection::STATUS_ZOMBIE;
3813 return OK;
3814}
3815
3816void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003817 for (auto it = mMonitoringChannelsByDisplay.begin();
3818 it != mMonitoringChannelsByDisplay.end(); ) {
3819 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3820 const size_t numChannels = monitoringChannels.size();
3821 for (size_t i = 0; i < numChannels; i++) {
3822 if (monitoringChannels[i] == inputChannel) {
3823 monitoringChannels.removeAt(i);
3824 break;
3825 }
3826 }
3827 if (monitoringChannels.empty()) {
3828 it = mMonitoringChannelsByDisplay.erase(it);
3829 } else {
3830 ++it;
3831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 }
3833}
3834
3835ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003836 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003837 return -1;
3838 }
3839
Robert Carr4e670e52018-08-15 13:26:12 -07003840 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3841 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3842 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3843 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 }
3845 }
Robert Carr4e670e52018-08-15 13:26:12 -07003846
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 return -1;
3848}
3849
3850void InputDispatcher::onDispatchCycleFinishedLocked(
3851 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3852 CommandEntry* commandEntry = postCommandLocked(
3853 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3854 commandEntry->connection = connection;
3855 commandEntry->eventTime = currentTime;
3856 commandEntry->seq = seq;
3857 commandEntry->handled = handled;
3858}
3859
3860void InputDispatcher::onDispatchCycleBrokenLocked(
3861 nsecs_t currentTime, const sp<Connection>& connection) {
3862 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003863 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864
3865 CommandEntry* commandEntry = postCommandLocked(
3866 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3867 commandEntry->connection = connection;
3868}
3869
chaviw0c06c6e2019-01-09 13:27:07 -08003870void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3871 const sp<InputWindowHandle>& newFocus) {
3872 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3873 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003874 CommandEntry* commandEntry = postCommandLocked(
3875 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003876 commandEntry->oldToken = oldToken;
3877 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003878}
3879
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880void InputDispatcher::onANRLocked(
3881 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3882 const sp<InputWindowHandle>& windowHandle,
3883 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3884 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3885 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3886 ALOGI("Application is not responding: %s. "
3887 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003888 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 dispatchLatency, waitDuration, reason);
3890
3891 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003892 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 struct tm tm;
3894 localtime_r(&t, &tm);
3895 char timestr[64];
3896 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3897 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003898 mLastANRState += INDENT "ANR:\n";
3899 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3900 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003901 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003902 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3903 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3904 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 dumpDispatchStateLocked(mLastANRState);
3906
3907 CommandEntry* commandEntry = postCommandLocked(
3908 & InputDispatcher::doNotifyANRLockedInterruptible);
3909 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003910 commandEntry->inputChannel = windowHandle != nullptr ?
3911 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 commandEntry->reason = reason;
3913}
3914
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003915void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 CommandEntry* commandEntry) {
3917 mLock.unlock();
3918
3919 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3920
3921 mLock.lock();
3922}
3923
3924void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3925 CommandEntry* commandEntry) {
3926 sp<Connection> connection = commandEntry->connection;
3927
3928 if (connection->status != Connection::STATUS_ZOMBIE) {
3929 mLock.unlock();
3930
Robert Carr803535b2018-08-02 16:38:15 -07003931 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
3933 mLock.lock();
3934 }
3935}
3936
Robert Carrf759f162018-11-13 12:57:11 -08003937void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3938 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003939 sp<IBinder> oldToken = commandEntry->oldToken;
3940 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003941 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003942 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003943 mLock.lock();
3944}
3945
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946void InputDispatcher::doNotifyANRLockedInterruptible(
3947 CommandEntry* commandEntry) {
3948 mLock.unlock();
3949
3950 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003951 commandEntry->inputApplicationHandle,
3952 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 commandEntry->reason);
3954
3955 mLock.lock();
3956
3957 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003958 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959}
3960
3961void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3962 CommandEntry* commandEntry) {
3963 KeyEntry* entry = commandEntry->keyEntry;
3964
3965 KeyEvent event;
3966 initializeKeyEvent(&event, entry);
3967
3968 mLock.unlock();
3969
Michael Wright2b3c3302018-03-02 17:19:13 +00003970 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003971 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3972 commandEntry->inputChannel->getToken() : nullptr;
3973 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003975 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3976 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3977 std::to_string(t.duration().count()).c_str());
3978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
3980 mLock.lock();
3981
3982 if (delay < 0) {
3983 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3984 } else if (!delay) {
3985 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3986 } else {
3987 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3988 entry->interceptKeyWakeupTime = now() + delay;
3989 }
3990 entry->release();
3991}
3992
3993void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3994 CommandEntry* commandEntry) {
3995 sp<Connection> connection = commandEntry->connection;
3996 nsecs_t finishTime = commandEntry->eventTime;
3997 uint32_t seq = commandEntry->seq;
3998 bool handled = commandEntry->handled;
3999
4000 // Handle post-event policy actions.
4001 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4002 if (dispatchEntry) {
4003 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4004 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004005 std::string msg =
4006 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004007 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004009 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 }
4011
4012 bool restartEvent;
4013 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4014 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4015 restartEvent = afterKeyEventLockedInterruptible(connection,
4016 dispatchEntry, keyEntry, handled);
4017 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4018 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4019 restartEvent = afterMotionEventLockedInterruptible(connection,
4020 dispatchEntry, motionEntry, handled);
4021 } else {
4022 restartEvent = false;
4023 }
4024
4025 // Dequeue the event and start the next cycle.
4026 // Note that because the lock might have been released, it is possible that the
4027 // contents of the wait queue to have been drained, so we need to double-check
4028 // a few things.
4029 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4030 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004031 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4033 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004034 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 } else {
4036 releaseDispatchEntryLocked(dispatchEntry);
4037 }
4038 }
4039
4040 // Start the next dispatch cycle for this connection.
4041 startDispatchCycleLocked(now(), connection);
4042 }
4043}
4044
4045bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4046 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004047 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004048 if (!handled) {
4049 // Report the key as unhandled, since the fallback was not handled.
4050 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4051 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004052 return false;
4053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004055 // Get the fallback key state.
4056 // Clear it out after dispatching the UP.
4057 int32_t originalKeyCode = keyEntry->keyCode;
4058 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4059 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4060 connection->inputState.removeFallbackKey(originalKeyCode);
4061 }
4062
4063 if (handled || !dispatchEntry->hasForegroundTarget()) {
4064 // If the application handles the original key for which we previously
4065 // generated a fallback or if the window is not a foreground window,
4066 // then cancel the associated fallback key, if any.
4067 if (fallbackKeyCode != -1) {
4068 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004070 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4072 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4073 keyEntry->policyFlags);
4074#endif
4075 KeyEvent event;
4076 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004077 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078
4079 mLock.unlock();
4080
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004081 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4082 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083
4084 mLock.lock();
4085
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004086 // Cancel the fallback key.
4087 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004089 "application handled the original non-fallback key "
4090 "or is no longer a foreground target, "
4091 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 options.keyCode = fallbackKeyCode;
4093 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004095 connection->inputState.removeFallbackKey(originalKeyCode);
4096 }
4097 } else {
4098 // If the application did not handle a non-fallback key, first check
4099 // that we are in a good state to perform unhandled key event processing
4100 // Then ask the policy what to do with it.
4101 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4102 && keyEntry->repeatCount == 0;
4103 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004105 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4106 "since this is not an initial down. "
4107 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4108 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4109 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004111 return false;
4112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004114 // Dispatch the unhandled key to the policy.
4115#if DEBUG_OUTBOUND_EVENT_DETAILS
4116 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4117 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4118 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4119 keyEntry->policyFlags);
4120#endif
4121 KeyEvent event;
4122 initializeKeyEvent(&event, keyEntry);
4123
4124 mLock.unlock();
4125
4126 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4127 &event, keyEntry->policyFlags, &event);
4128
4129 mLock.lock();
4130
4131 if (connection->status != Connection::STATUS_NORMAL) {
4132 connection->inputState.removeFallbackKey(originalKeyCode);
4133 return false;
4134 }
4135
4136 // Latch the fallback keycode for this key on an initial down.
4137 // The fallback keycode cannot change at any other point in the lifecycle.
4138 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004140 fallbackKeyCode = event.getKeyCode();
4141 } else {
4142 fallbackKeyCode = AKEYCODE_UNKNOWN;
4143 }
4144 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4145 }
4146
4147 ALOG_ASSERT(fallbackKeyCode != -1);
4148
4149 // Cancel the fallback key if the policy decides not to send it anymore.
4150 // We will continue to dispatch the key to the policy but we will no
4151 // longer dispatch a fallback key to the application.
4152 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4153 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4154#if DEBUG_OUTBOUND_EVENT_DETAILS
4155 if (fallback) {
4156 ALOGD("Unhandled key event: Policy requested to send key %d"
4157 "as a fallback for %d, but on the DOWN it had requested "
4158 "to send %d instead. Fallback canceled.",
4159 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4160 } else {
4161 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4162 "but on the DOWN it had requested to send %d. "
4163 "Fallback canceled.",
4164 originalKeyCode, fallbackKeyCode);
4165 }
4166#endif
4167
4168 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4169 "canceling fallback, policy no longer desires it");
4170 options.keyCode = fallbackKeyCode;
4171 synthesizeCancelationEventsForConnectionLocked(connection, options);
4172
4173 fallback = false;
4174 fallbackKeyCode = AKEYCODE_UNKNOWN;
4175 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4176 connection->inputState.setFallbackKey(originalKeyCode,
4177 fallbackKeyCode);
4178 }
4179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
4181#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004182 {
4183 std::string msg;
4184 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4185 connection->inputState.getFallbackKeys();
4186 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4187 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4188 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004190 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4191 fallbackKeys.size(), msg.c_str());
4192 }
4193#endif
4194
4195 if (fallback) {
4196 // Restart the dispatch cycle using the fallback key.
4197 keyEntry->eventTime = event.getEventTime();
4198 keyEntry->deviceId = event.getDeviceId();
4199 keyEntry->source = event.getSource();
4200 keyEntry->displayId = event.getDisplayId();
4201 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4202 keyEntry->keyCode = fallbackKeyCode;
4203 keyEntry->scanCode = event.getScanCode();
4204 keyEntry->metaState = event.getMetaState();
4205 keyEntry->repeatCount = event.getRepeatCount();
4206 keyEntry->downTime = event.getDownTime();
4207 keyEntry->syntheticRepeat = false;
4208
4209#if DEBUG_OUTBOUND_EVENT_DETAILS
4210 ALOGD("Unhandled key event: Dispatching fallback key. "
4211 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4212 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4213#endif
4214 return true; // restart the event
4215 } else {
4216#if DEBUG_OUTBOUND_EVENT_DETAILS
4217 ALOGD("Unhandled key event: No fallback key.");
4218#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004219
4220 // Report the key as unhandled, since there is no fallback key.
4221 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 }
4223 }
4224 return false;
4225}
4226
4227bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4228 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4229 return false;
4230}
4231
4232void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4233 mLock.unlock();
4234
4235 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4236
4237 mLock.lock();
4238}
4239
4240void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004241 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4243 entry->downTime, entry->eventTime);
4244}
4245
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004246void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4248 // TODO Write some statistics about how long we spend waiting.
4249}
4250
4251void InputDispatcher::traceInboundQueueLengthLocked() {
4252 if (ATRACE_ENABLED()) {
4253 ATRACE_INT("iq", mInboundQueue.count());
4254 }
4255}
4256
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004257void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 if (ATRACE_ENABLED()) {
4259 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004260 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 ATRACE_INT(counterName, connection->outboundQueue.count());
4262 }
4263}
4264
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004265void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 if (ATRACE_ENABLED()) {
4267 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004268 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 ATRACE_INT(counterName, connection->waitQueue.count());
4270 }
4271}
4272
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004273void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 AutoMutex _l(mLock);
4275
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004276 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 dumpDispatchStateLocked(dump);
4278
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004279 if (!mLastANRState.empty()) {
4280 dump += "\nInput Dispatcher State at time of last ANR:\n";
4281 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283}
4284
4285void InputDispatcher::monitor() {
4286 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4287 mLock.lock();
4288 mLooper->wake();
4289 mDispatcherIsAliveCondition.wait(mLock);
4290 mLock.unlock();
4291}
4292
4293
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294// --- InputDispatcher::InjectionState ---
4295
4296InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4297 refCount(1),
4298 injectorPid(injectorPid), injectorUid(injectorUid),
4299 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4300 pendingForegroundDispatches(0) {
4301}
4302
4303InputDispatcher::InjectionState::~InjectionState() {
4304}
4305
4306void InputDispatcher::InjectionState::release() {
4307 refCount -= 1;
4308 if (refCount == 0) {
4309 delete this;
4310 } else {
4311 ALOG_ASSERT(refCount > 0);
4312 }
4313}
4314
4315
4316// --- InputDispatcher::EventEntry ---
4317
Prabir Pradhan42611e02018-11-27 14:04:02 -08004318InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4319 nsecs_t eventTime, uint32_t policyFlags) :
4320 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4321 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322}
4323
4324InputDispatcher::EventEntry::~EventEntry() {
4325 releaseInjectionState();
4326}
4327
4328void InputDispatcher::EventEntry::release() {
4329 refCount -= 1;
4330 if (refCount == 0) {
4331 delete this;
4332 } else {
4333 ALOG_ASSERT(refCount > 0);
4334 }
4335}
4336
4337void InputDispatcher::EventEntry::releaseInjectionState() {
4338 if (injectionState) {
4339 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004340 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
4342}
4343
4344
4345// --- InputDispatcher::ConfigurationChangedEntry ---
4346
Prabir Pradhan42611e02018-11-27 14:04:02 -08004347InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4348 uint32_t sequenceNum, nsecs_t eventTime) :
4349 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350}
4351
4352InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4353}
4354
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004355void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4356 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357}
4358
4359
4360// --- InputDispatcher::DeviceResetEntry ---
4361
Prabir Pradhan42611e02018-11-27 14:04:02 -08004362InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4363 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4364 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 deviceId(deviceId) {
4366}
4367
4368InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4369}
4370
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004371void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4372 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 deviceId, policyFlags);
4374}
4375
4376
4377// --- InputDispatcher::KeyEntry ---
4378
Prabir Pradhan42611e02018-11-27 14:04:02 -08004379InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004380 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4382 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004383 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004384 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4386 repeatCount(repeatCount), downTime(downTime),
4387 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4388 interceptKeyWakeupTime(0) {
4389}
4390
4391InputDispatcher::KeyEntry::~KeyEntry() {
4392}
4393
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004394void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004395 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4397 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004398 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004399 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400}
4401
4402void InputDispatcher::KeyEntry::recycle() {
4403 releaseInjectionState();
4404
4405 dispatchInProgress = false;
4406 syntheticRepeat = false;
4407 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4408 interceptKeyWakeupTime = 0;
4409}
4410
4411
4412// --- InputDispatcher::MotionEntry ---
4413
Prabir Pradhan42611e02018-11-27 14:04:02 -08004414InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004415 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4416 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004417 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4418 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004419 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004420 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4421 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004422 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004424 deviceId(deviceId), source(source), displayId(displayId), action(action),
4425 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004426 classification(classification), edgeFlags(edgeFlags),
4427 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004428 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 for (uint32_t i = 0; i < pointerCount; i++) {
4430 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4431 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004432 if (xOffset || yOffset) {
4433 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 }
4436}
4437
4438InputDispatcher::MotionEntry::~MotionEntry() {
4439}
4440
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004441void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004442 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004443 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004444 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004445 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004446 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4447 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004448
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 for (uint32_t i = 0; i < pointerCount; i++) {
4450 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004451 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004453 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 pointerCoords[i].getX(), pointerCoords[i].getY());
4455 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004456 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457}
4458
4459
4460// --- InputDispatcher::DispatchEntry ---
4461
4462volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4463
4464InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004465 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4466 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 seq(nextSeq()),
4468 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004469 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4470 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4472 eventEntry->refCount += 1;
4473}
4474
4475InputDispatcher::DispatchEntry::~DispatchEntry() {
4476 eventEntry->release();
4477}
4478
4479uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4480 // Sequence number 0 is reserved and will never be returned.
4481 uint32_t seq;
4482 do {
4483 seq = android_atomic_inc(&sNextSeqAtomic);
4484 } while (!seq);
4485 return seq;
4486}
4487
4488
4489// --- InputDispatcher::InputState ---
4490
4491InputDispatcher::InputState::InputState() {
4492}
4493
4494InputDispatcher::InputState::~InputState() {
4495}
4496
4497bool InputDispatcher::InputState::isNeutral() const {
4498 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4499}
4500
4501bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4502 int32_t displayId) const {
4503 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4504 const MotionMemento& memento = mMotionMementos.itemAt(i);
4505 if (memento.deviceId == deviceId
4506 && memento.source == source
4507 && memento.displayId == displayId
4508 && memento.hovering) {
4509 return true;
4510 }
4511 }
4512 return false;
4513}
4514
4515bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4516 int32_t action, int32_t flags) {
4517 switch (action) {
4518 case AKEY_EVENT_ACTION_UP: {
4519 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4520 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4521 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4522 mFallbackKeys.removeItemsAt(i);
4523 } else {
4524 i += 1;
4525 }
4526 }
4527 }
4528 ssize_t index = findKeyMemento(entry);
4529 if (index >= 0) {
4530 mKeyMementos.removeAt(index);
4531 return true;
4532 }
4533 /* FIXME: We can't just drop the key up event because that prevents creating
4534 * popup windows that are automatically shown when a key is held and then
4535 * dismissed when the key is released. The problem is that the popup will
4536 * not have received the original key down, so the key up will be considered
4537 * to be inconsistent with its observed state. We could perhaps handle this
4538 * by synthesizing a key down but that will cause other problems.
4539 *
4540 * So for now, allow inconsistent key up events to be dispatched.
4541 *
4542#if DEBUG_OUTBOUND_EVENT_DETAILS
4543 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4544 "keyCode=%d, scanCode=%d",
4545 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4546#endif
4547 return false;
4548 */
4549 return true;
4550 }
4551
4552 case AKEY_EVENT_ACTION_DOWN: {
4553 ssize_t index = findKeyMemento(entry);
4554 if (index >= 0) {
4555 mKeyMementos.removeAt(index);
4556 }
4557 addKeyMemento(entry, flags);
4558 return true;
4559 }
4560
4561 default:
4562 return true;
4563 }
4564}
4565
4566bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4567 int32_t action, int32_t flags) {
4568 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4569 switch (actionMasked) {
4570 case AMOTION_EVENT_ACTION_UP:
4571 case AMOTION_EVENT_ACTION_CANCEL: {
4572 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4573 if (index >= 0) {
4574 mMotionMementos.removeAt(index);
4575 return true;
4576 }
4577#if DEBUG_OUTBOUND_EVENT_DETAILS
4578 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004579 "displayId=%" PRId32 ", actionMasked=%d",
4580 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581#endif
4582 return false;
4583 }
4584
4585 case AMOTION_EVENT_ACTION_DOWN: {
4586 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4587 if (index >= 0) {
4588 mMotionMementos.removeAt(index);
4589 }
4590 addMotionMemento(entry, flags, false /*hovering*/);
4591 return true;
4592 }
4593
4594 case AMOTION_EVENT_ACTION_POINTER_UP:
4595 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4596 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004597 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4598 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4599 // generate cancellation events for these since they're based in relative rather than
4600 // absolute units.
4601 return true;
4602 }
4603
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004605
4606 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4607 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4608 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4609 // other value and we need to track the motion so we can send cancellation events for
4610 // anything generating fallback events (e.g. DPad keys for joystick movements).
4611 if (index >= 0) {
4612 if (entry->pointerCoords[0].isEmpty()) {
4613 mMotionMementos.removeAt(index);
4614 } else {
4615 MotionMemento& memento = mMotionMementos.editItemAt(index);
4616 memento.setPointers(entry);
4617 }
4618 } else if (!entry->pointerCoords[0].isEmpty()) {
4619 addMotionMemento(entry, flags, false /*hovering*/);
4620 }
4621
4622 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4623 return true;
4624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 if (index >= 0) {
4626 MotionMemento& memento = mMotionMementos.editItemAt(index);
4627 memento.setPointers(entry);
4628 return true;
4629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630#if DEBUG_OUTBOUND_EVENT_DETAILS
4631 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004632 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4633 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634#endif
4635 return false;
4636 }
4637
4638 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4639 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4640 if (index >= 0) {
4641 mMotionMementos.removeAt(index);
4642 return true;
4643 }
4644#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004645 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4646 "displayId=%" PRId32,
4647 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648#endif
4649 return false;
4650 }
4651
4652 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4653 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4654 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4655 if (index >= 0) {
4656 mMotionMementos.removeAt(index);
4657 }
4658 addMotionMemento(entry, flags, true /*hovering*/);
4659 return true;
4660 }
4661
4662 default:
4663 return true;
4664 }
4665}
4666
4667ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4668 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4669 const KeyMemento& memento = mKeyMementos.itemAt(i);
4670 if (memento.deviceId == entry->deviceId
4671 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004672 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 && memento.keyCode == entry->keyCode
4674 && memento.scanCode == entry->scanCode) {
4675 return i;
4676 }
4677 }
4678 return -1;
4679}
4680
4681ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4682 bool hovering) const {
4683 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4684 const MotionMemento& memento = mMotionMementos.itemAt(i);
4685 if (memento.deviceId == entry->deviceId
4686 && memento.source == entry->source
4687 && memento.displayId == entry->displayId
4688 && memento.hovering == hovering) {
4689 return i;
4690 }
4691 }
4692 return -1;
4693}
4694
4695void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4696 mKeyMementos.push();
4697 KeyMemento& memento = mKeyMementos.editTop();
4698 memento.deviceId = entry->deviceId;
4699 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004700 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 memento.keyCode = entry->keyCode;
4702 memento.scanCode = entry->scanCode;
4703 memento.metaState = entry->metaState;
4704 memento.flags = flags;
4705 memento.downTime = entry->downTime;
4706 memento.policyFlags = entry->policyFlags;
4707}
4708
4709void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4710 int32_t flags, bool hovering) {
4711 mMotionMementos.push();
4712 MotionMemento& memento = mMotionMementos.editTop();
4713 memento.deviceId = entry->deviceId;
4714 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004715 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 memento.flags = flags;
4717 memento.xPrecision = entry->xPrecision;
4718 memento.yPrecision = entry->yPrecision;
4719 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 memento.setPointers(entry);
4721 memento.hovering = hovering;
4722 memento.policyFlags = entry->policyFlags;
4723}
4724
4725void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4726 pointerCount = entry->pointerCount;
4727 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4728 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4729 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4730 }
4731}
4732
4733void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4734 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4735 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4736 const KeyMemento& memento = mKeyMementos.itemAt(i);
4737 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004738 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004739 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4741 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4742 }
4743 }
4744
4745 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4746 const MotionMemento& memento = mMotionMementos.itemAt(i);
4747 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004748 const int32_t action = memento.hovering ?
4749 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004750 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004751 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004752 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4753 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004755 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004756 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 }
4758 }
4759}
4760
4761void InputDispatcher::InputState::clear() {
4762 mKeyMementos.clear();
4763 mMotionMementos.clear();
4764 mFallbackKeys.clear();
4765}
4766
4767void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4768 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4769 const MotionMemento& memento = mMotionMementos.itemAt(i);
4770 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4771 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4772 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4773 if (memento.deviceId == otherMemento.deviceId
4774 && memento.source == otherMemento.source
4775 && memento.displayId == otherMemento.displayId) {
4776 other.mMotionMementos.removeAt(j);
4777 } else {
4778 j += 1;
4779 }
4780 }
4781 other.mMotionMementos.push(memento);
4782 }
4783 }
4784}
4785
4786int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4787 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4788 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4789}
4790
4791void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4792 int32_t fallbackKeyCode) {
4793 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4794 if (index >= 0) {
4795 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4796 } else {
4797 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4798 }
4799}
4800
4801void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4802 mFallbackKeys.removeItem(originalKeyCode);
4803}
4804
4805bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4806 const CancelationOptions& options) {
4807 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4808 return false;
4809 }
4810
4811 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4812 return false;
4813 }
4814
4815 switch (options.mode) {
4816 case CancelationOptions::CANCEL_ALL_EVENTS:
4817 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4818 return true;
4819 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4820 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004821 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4822 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 default:
4824 return false;
4825 }
4826}
4827
4828bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4829 const CancelationOptions& options) {
4830 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4831 return false;
4832 }
4833
4834 switch (options.mode) {
4835 case CancelationOptions::CANCEL_ALL_EVENTS:
4836 return true;
4837 case CancelationOptions::CANCEL_POINTER_EVENTS:
4838 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4839 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4840 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004841 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4842 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 default:
4844 return false;
4845 }
4846}
4847
4848
4849// --- InputDispatcher::Connection ---
4850
Robert Carr803535b2018-08-02 16:38:15 -07004851InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4852 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 monitor(monitor),
4854 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4855}
4856
4857InputDispatcher::Connection::~Connection() {
4858}
4859
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004860const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004861 if (inputChannel != nullptr) {
4862 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 }
4864 if (monitor) {
4865 return "monitor";
4866 }
4867 return "?";
4868}
4869
4870const char* InputDispatcher::Connection::getStatusLabel() const {
4871 switch (status) {
4872 case STATUS_NORMAL:
4873 return "NORMAL";
4874
4875 case STATUS_BROKEN:
4876 return "BROKEN";
4877
4878 case STATUS_ZOMBIE:
4879 return "ZOMBIE";
4880
4881 default:
4882 return "UNKNOWN";
4883 }
4884}
4885
4886InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004887 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 if (entry->seq == seq) {
4889 return entry;
4890 }
4891 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004892 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
4895
4896// --- InputDispatcher::CommandEntry ---
4897
4898InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004899 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 seq(0), handled(false) {
4901}
4902
4903InputDispatcher::CommandEntry::~CommandEntry() {
4904}
4905
4906
4907// --- InputDispatcher::TouchState ---
4908
4909InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004910 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911}
4912
4913InputDispatcher::TouchState::~TouchState() {
4914}
4915
4916void InputDispatcher::TouchState::reset() {
4917 down = false;
4918 split = false;
4919 deviceId = -1;
4920 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004921 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004923 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924}
4925
4926void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4927 down = other.down;
4928 split = other.split;
4929 deviceId = other.deviceId;
4930 source = other.source;
4931 displayId = other.displayId;
4932 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004933 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934}
4935
4936void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4937 int32_t targetFlags, BitSet32 pointerIds) {
4938 if (targetFlags & InputTarget::FLAG_SPLIT) {
4939 split = true;
4940 }
4941
4942 for (size_t i = 0; i < windows.size(); i++) {
4943 TouchedWindow& touchedWindow = windows.editItemAt(i);
4944 if (touchedWindow.windowHandle == windowHandle) {
4945 touchedWindow.targetFlags |= targetFlags;
4946 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4947 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4948 }
4949 touchedWindow.pointerIds.value |= pointerIds.value;
4950 return;
4951 }
4952 }
4953
4954 windows.push();
4955
4956 TouchedWindow& touchedWindow = windows.editTop();
4957 touchedWindow.windowHandle = windowHandle;
4958 touchedWindow.targetFlags = targetFlags;
4959 touchedWindow.pointerIds = pointerIds;
4960}
4961
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004962void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4963 size_t numWindows = portalWindows.size();
4964 for (size_t i = 0; i < numWindows; i++) {
4965 sp<InputWindowHandle> portalWindowHandle = portalWindows.itemAt(i);
4966 if (portalWindowHandle == windowHandle) {
4967 return;
4968 }
4969 }
4970 portalWindows.push_back(windowHandle);
4971}
4972
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4974 for (size_t i = 0; i < windows.size(); i++) {
4975 if (windows.itemAt(i).windowHandle == windowHandle) {
4976 windows.removeAt(i);
4977 return;
4978 }
4979 }
4980}
4981
Robert Carr803535b2018-08-02 16:38:15 -07004982void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4983 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004984 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004985 windows.removeAt(i);
4986 return;
4987 }
4988 }
4989}
4990
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4992 for (size_t i = 0 ; i < windows.size(); ) {
4993 TouchedWindow& window = windows.editItemAt(i);
4994 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4995 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4996 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4997 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4998 i += 1;
4999 } else {
5000 windows.removeAt(i);
5001 }
5002 }
5003}
5004
5005sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5006 for (size_t i = 0; i < windows.size(); i++) {
5007 const TouchedWindow& window = windows.itemAt(i);
5008 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5009 return window.windowHandle;
5010 }
5011 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005012 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013}
5014
5015bool InputDispatcher::TouchState::isSlippery() const {
5016 // Must have exactly one foreground window.
5017 bool haveSlipperyForegroundWindow = false;
5018 for (size_t i = 0; i < windows.size(); i++) {
5019 const TouchedWindow& window = windows.itemAt(i);
5020 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5021 if (haveSlipperyForegroundWindow
5022 || !(window.windowHandle->getInfo()->layoutParamsFlags
5023 & InputWindowInfo::FLAG_SLIPPERY)) {
5024 return false;
5025 }
5026 haveSlipperyForegroundWindow = true;
5027 }
5028 }
5029 return haveSlipperyForegroundWindow;
5030}
5031
5032
5033// --- InputDispatcherThread ---
5034
5035InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5036 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5037}
5038
5039InputDispatcherThread::~InputDispatcherThread() {
5040}
5041
5042bool InputDispatcherThread::threadLoop() {
5043 mDispatcher->dispatchOnce();
5044 return true;
5045}
5046
5047} // namespace android