blob: 1ec736baf9945b0db1812e5782b1ecfb813de333 [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) {
404 if (isAppSwitchKeyEventLocked(typedEntry)) {
405 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
412 && isStaleEventLocked(currentTime, typedEntry)) {
413 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
428 && isStaleEventLocked(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry,
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);
466 if (isAppSwitchKeyEventLocked(keyEntry)) {
467 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,
524 int32_t x, int32_t y) {
525 // 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)) {
539 // Found window.
540 return windowHandle;
541 }
542 }
543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 }
545 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700546 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547}
548
549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
553#if DEBUG_INBOUND_EVENT_DETAILS
554 ALOGD("Dropped event because policy consumed it.");
555#endif
556 reason = "inbound event was dropped because the policy consumed it";
557 break;
558 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100559 if (mLastDropReason != DROP_REASON_DISABLED) {
560 ALOGI("Dropped event because input dispatch is disabled.");
561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 reason = "inbound event was dropped because input dispatch is disabled";
563 break;
564 case DROP_REASON_APP_SWITCH:
565 ALOGI("Dropped event because of pending overdue app switch.");
566 reason = "inbound event was dropped because of pending overdue app switch";
567 break;
568 case DROP_REASON_BLOCKED:
569 ALOGI("Dropped event because the current application is not responding and the user "
570 "has started interacting with a different application.");
571 reason = "inbound event was dropped because the current application is not responding "
572 "and the user has started interacting with a different application";
573 break;
574 case DROP_REASON_STALE:
575 ALOGI("Dropped event because it is stale.");
576 reason = "inbound event was dropped because it is stale";
577 break;
578 default:
579 ALOG_ASSERT(false);
580 return;
581 }
582
583 switch (entry->type) {
584 case EventEntry::TYPE_KEY: {
585 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
586 synthesizeCancelationEventsForAllConnectionsLocked(options);
587 break;
588 }
589 case EventEntry::TYPE_MOTION: {
590 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
591 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
593 synthesizeCancelationEventsForAllConnectionsLocked(options);
594 } else {
595 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
596 synthesizeCancelationEventsForAllConnectionsLocked(options);
597 }
598 break;
599 }
600 }
601}
602
603bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
604 return keyCode == AKEYCODE_HOME
605 || keyCode == AKEYCODE_ENDCALL
606 || keyCode == AKEYCODE_APP_SWITCH;
607}
608
609bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
610 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
611 && isAppSwitchKeyCode(keyEntry->keyCode)
612 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
613 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
614}
615
616bool InputDispatcher::isAppSwitchPendingLocked() {
617 return mAppSwitchDueTime != LONG_LONG_MAX;
618}
619
620void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
621 mAppSwitchDueTime = LONG_LONG_MAX;
622
623#if DEBUG_APP_SWITCH
624 if (handled) {
625 ALOGD("App switch has arrived.");
626 } else {
627 ALOGD("App switch was abandoned.");
628 }
629#endif
630}
631
632bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
633 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
634}
635
636bool InputDispatcher::haveCommandsLocked() const {
637 return !mCommandQueue.isEmpty();
638}
639
640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
644
645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
651 commandEntry->connection.clear();
652 delete commandEntry;
653 } while (! mCommandQueue.isEmpty());
654 return true;
655}
656
657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
658 CommandEntry* commandEntry = new CommandEntry(command);
659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
666 releaseInboundEventLocked(entry);
667 }
668 traceInboundQueueLengthLocked();
669}
670
671void InputDispatcher::releasePendingEventLocked() {
672 if (mPendingEvent) {
673 resetANRTimeoutsLocked();
674 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700675 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677}
678
679void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
680 InjectionState* injectionState = entry->injectionState;
681 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
682#if DEBUG_DISPATCH_CYCLE
683 ALOGD("Injected inbound event was dropped.");
684#endif
685 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
686 }
687 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690 addRecentEventLocked(entry);
691 entry->release();
692}
693
694void InputDispatcher::resetKeyRepeatLocked() {
695 if (mKeyRepeatState.lastKeyEntry) {
696 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699}
700
701InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
702 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
703
704 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700705 uint32_t policyFlags = entry->policyFlags &
706 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 if (entry->refCount == 1) {
708 entry->recycle();
709 entry->eventTime = currentTime;
710 entry->policyFlags = policyFlags;
711 entry->repeatCount += 1;
712 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800713 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100714 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 entry->action, entry->flags, entry->keyCode, entry->scanCode,
716 entry->metaState, entry->repeatCount + 1, entry->downTime);
717
718 mKeyRepeatState.lastKeyEntry = newEntry;
719 entry->release();
720
721 entry = newEntry;
722 }
723 entry->syntheticRepeat = true;
724
725 // Increment reference count since we keep a reference to the event in
726 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
727 entry->refCount += 1;
728
729 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
730 return entry;
731}
732
733bool InputDispatcher::dispatchConfigurationChangedLocked(
734 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
735#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700736 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737#endif
738
739 // Reset key repeating in case a keyboard device was added or removed or something.
740 resetKeyRepeatLocked();
741
742 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
743 CommandEntry* commandEntry = postCommandLocked(
744 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
745 commandEntry->eventTime = entry->eventTime;
746 return true;
747}
748
749bool InputDispatcher::dispatchDeviceResetLocked(
750 nsecs_t currentTime, DeviceResetEntry* entry) {
751#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700752 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
753 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754#endif
755
756 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
757 "device was reset");
758 options.deviceId = entry->deviceId;
759 synthesizeCancelationEventsForAllConnectionsLocked(options);
760 return true;
761}
762
763bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
764 DropReason* dropReason, nsecs_t* nextWakeupTime) {
765 // Preprocessing.
766 if (! entry->dispatchInProgress) {
767 if (entry->repeatCount == 0
768 && entry->action == AKEY_EVENT_ACTION_DOWN
769 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
770 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
771 if (mKeyRepeatState.lastKeyEntry
772 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
773 // We have seen two identical key downs in a row which indicates that the device
774 // driver is automatically generating key repeats itself. We take note of the
775 // repeat here, but we disable our own next key repeat timer since it is clear that
776 // we will not need to synthesize key repeats ourselves.
777 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
778 resetKeyRepeatLocked();
779 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
780 } else {
781 // Not a repeat. Save key down state in case we do see a repeat later.
782 resetKeyRepeatLocked();
783 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
784 }
785 mKeyRepeatState.lastKeyEntry = entry;
786 entry->refCount += 1;
787 } else if (! entry->syntheticRepeat) {
788 resetKeyRepeatLocked();
789 }
790
791 if (entry->repeatCount == 1) {
792 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
793 } else {
794 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
795 }
796
797 entry->dispatchInProgress = true;
798
799 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
800 }
801
802 // Handle case where the policy asked us to try again later last time.
803 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
804 if (currentTime < entry->interceptKeyWakeupTime) {
805 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
806 *nextWakeupTime = entry->interceptKeyWakeupTime;
807 }
808 return false; // wait until next wakeup
809 }
810 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
811 entry->interceptKeyWakeupTime = 0;
812 }
813
814 // Give the policy a chance to intercept the key.
815 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
816 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
817 CommandEntry* commandEntry = postCommandLocked(
818 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800819 sp<InputWindowHandle> focusedWindowHandle =
820 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
821 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700822 commandEntry->inputChannel =
823 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
825 commandEntry->keyEntry = entry;
826 entry->refCount += 1;
827 return false; // wait for the command to run
828 } else {
829 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
830 }
831 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
832 if (*dropReason == DROP_REASON_NOT_DROPPED) {
833 *dropReason = DROP_REASON_POLICY;
834 }
835 }
836
837 // Clean up if dropping the event.
838 if (*dropReason != DROP_REASON_NOT_DROPPED) {
839 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
840 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800841 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 return true;
843 }
844
845 // Identify targets.
846 Vector<InputTarget> inputTargets;
847 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
848 entry, inputTargets, nextWakeupTime);
849 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
850 return false;
851 }
852
853 setInjectionResultLocked(entry, injectionResult);
854 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
855 return true;
856 }
857
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800858 // Add monitor channels from event's or focused display.
859 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860
861 // Dispatch the key.
862 dispatchEventLocked(currentTime, entry, inputTargets);
863 return true;
864}
865
866void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
867#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100868 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
869 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800870 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100872 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800874 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875#endif
876}
877
878bool InputDispatcher::dispatchMotionLocked(
879 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
880 // Preprocessing.
881 if (! entry->dispatchInProgress) {
882 entry->dispatchInProgress = true;
883
884 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
885 }
886
887 // Clean up if dropping the event.
888 if (*dropReason != DROP_REASON_NOT_DROPPED) {
889 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
890 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
891 return true;
892 }
893
894 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
895
896 // Identify targets.
897 Vector<InputTarget> inputTargets;
898
899 bool conflictingPointerActions = false;
900 int32_t injectionResult;
901 if (isPointerEvent) {
902 // Pointer event. (eg. touchscreen)
903 injectionResult = findTouchedWindowTargetsLocked(currentTime,
904 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
905 } else {
906 // Non touch event. (eg. trackball)
907 injectionResult = findFocusedWindowTargetsLocked(currentTime,
908 entry, inputTargets, nextWakeupTime);
909 }
910 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
911 return false;
912 }
913
914 setInjectionResultLocked(entry, injectionResult);
915 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100916 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
917 CancelationOptions::Mode mode(isPointerEvent ?
918 CancelationOptions::CANCEL_POINTER_EVENTS :
919 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
920 CancelationOptions options(mode, "input event injection failed");
921 synthesizeCancelationEventsForMonitorsLocked(options);
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 return true;
924 }
925
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800926 // Add monitor channels from event's or focused display.
927 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928
929 // Dispatch the motion.
930 if (conflictingPointerActions) {
931 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
932 "conflicting pointer actions");
933 synthesizeCancelationEventsForAllConnectionsLocked(options);
934 }
935 dispatchEventLocked(currentTime, entry, inputTargets);
936 return true;
937}
938
939
940void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
941#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800942 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
943 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100944 "action=0x%x, actionButton=0x%x, flags=0x%x, "
945 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800946 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800948 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100949 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 entry->metaState, entry->buttonState,
951 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800952 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953
954 for (uint32_t i = 0; i < entry->pointerCount; i++) {
955 ALOGD(" Pointer %d: id=%d, toolType=%d, "
956 "x=%f, y=%f, pressure=%f, size=%f, "
957 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800958 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 i, entry->pointerProperties[i].id,
960 entry->pointerProperties[i].toolType,
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
968 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800969 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
971#endif
972}
973
974void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
975 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
976#if DEBUG_DISPATCH_CYCLE
977 ALOGD("dispatchEventToCurrentInputTargets");
978#endif
979
980 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
981
982 pokeUserActivityLocked(eventEntry);
983
984 for (size_t i = 0; i < inputTargets.size(); i++) {
985 const InputTarget& inputTarget = inputTargets.itemAt(i);
986
987 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
988 if (connectionIndex >= 0) {
989 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
990 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
991 } else {
992#if DEBUG_FOCUS
993 ALOGD("Dropping event delivery to target with channel '%s' because it "
994 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800995 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996#endif
997 }
998 }
999}
1000
1001int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1002 const EventEntry* entry,
1003 const sp<InputApplicationHandle>& applicationHandle,
1004 const sp<InputWindowHandle>& windowHandle,
1005 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001006 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1008#if DEBUG_FOCUS
1009 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1010#endif
1011 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1012 mInputTargetWaitStartTime = currentTime;
1013 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1014 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001015 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017 } else {
1018 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1019#if DEBUG_FOCUS
1020 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001021 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 reason);
1023#endif
1024 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001025 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001027 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 timeout = applicationHandle->getDispatchingTimeout(
1029 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1030 } else {
1031 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1032 }
1033
1034 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1035 mInputTargetWaitStartTime = currentTime;
1036 mInputTargetWaitTimeoutTime = currentTime + timeout;
1037 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001038 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001041 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
Robert Carr740167f2018-10-11 19:03:41 -07001043 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1044 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 }
1046 }
1047 }
1048
1049 if (mInputTargetWaitTimeoutExpired) {
1050 return INPUT_EVENT_INJECTION_TIMED_OUT;
1051 }
1052
1053 if (currentTime >= mInputTargetWaitTimeoutTime) {
1054 onANRLocked(currentTime, applicationHandle, windowHandle,
1055 entry->eventTime, mInputTargetWaitStartTime, reason);
1056
1057 // Force poll loop to wake up immediately on next iteration once we get the
1058 // ANR response back from the policy.
1059 *nextWakeupTime = LONG_LONG_MIN;
1060 return INPUT_EVENT_INJECTION_PENDING;
1061 } else {
1062 // Force poll loop to wake up when timeout is due.
1063 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1064 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1065 }
1066 return INPUT_EVENT_INJECTION_PENDING;
1067 }
1068}
1069
Robert Carr803535b2018-08-02 16:38:15 -07001070void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1071 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1072 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1073 state.removeWindowByToken(token);
1074 }
1075}
1076
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1078 const sp<InputChannel>& inputChannel) {
1079 if (newTimeout > 0) {
1080 // Extend the timeout.
1081 mInputTargetWaitTimeoutTime = now() + newTimeout;
1082 } else {
1083 // Give up.
1084 mInputTargetWaitTimeoutExpired = true;
1085
1086 // Input state will not be realistic. Mark it out of sync.
1087 if (inputChannel.get()) {
1088 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1089 if (connectionIndex >= 0) {
1090 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001091 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092
Robert Carr803535b2018-08-02 16:38:15 -07001093 if (token != nullptr) {
1094 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096
1097 if (connection->status == Connection::STATUS_NORMAL) {
1098 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1099 "application not responding");
1100 synthesizeCancelationEventsForConnectionLocked(connection, options);
1101 }
1102 }
1103 }
1104 }
1105}
1106
1107nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1108 nsecs_t currentTime) {
1109 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1110 return currentTime - mInputTargetWaitStartTime;
1111 }
1112 return 0;
1113}
1114
1115void InputDispatcher::resetANRTimeoutsLocked() {
1116#if DEBUG_FOCUS
1117 ALOGD("Resetting ANR timeouts.");
1118#endif
1119
1120 // Reset input target wait timeout.
1121 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001122 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123}
1124
Tiger Huang721e26f2018-07-24 22:26:19 +08001125/**
1126 * Get the display id that the given event should go to. If this event specifies a valid display id,
1127 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1128 * Focused display is the display that the user most recently interacted with.
1129 */
1130int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1131 int32_t displayId;
1132 switch (entry->type) {
1133 case EventEntry::TYPE_KEY: {
1134 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1135 displayId = typedEntry->displayId;
1136 break;
1137 }
1138 case EventEntry::TYPE_MOTION: {
1139 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1140 displayId = typedEntry->displayId;
1141 break;
1142 }
1143 default: {
1144 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1145 return ADISPLAY_ID_NONE;
1146 }
1147 }
1148 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1149}
1150
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1152 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1153 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001154 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155
Tiger Huang721e26f2018-07-24 22:26:19 +08001156 int32_t displayId = getTargetDisplayId(entry);
1157 sp<InputWindowHandle> focusedWindowHandle =
1158 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1159 sp<InputApplicationHandle> focusedApplicationHandle =
1160 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1161
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 // If there is no currently focused window and no focused application
1163 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001164 if (focusedWindowHandle == nullptr) {
1165 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001167 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 "Waiting because no window has focus but there is a "
1169 "focused application that may eventually add a window "
1170 "when it finishes starting up.");
1171 goto Unresponsive;
1172 }
1173
Arthur Hung3b413f22018-10-26 18:05:34 +08001174 ALOGI("Dropping event because there is no focused window or focused application in display "
1175 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1177 goto Failed;
1178 }
1179
1180 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001181 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1183 goto Failed;
1184 }
1185
Jeff Brownffb49772014-10-10 19:01:34 -07001186 // Check whether the window is ready for more input.
1187 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001188 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001189 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001191 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 goto Unresponsive;
1193 }
1194
1195 // Success! Output targets.
1196 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001197 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1199 inputTargets);
1200
1201 // Done.
1202Failed:
1203Unresponsive:
1204 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1205 updateDispatchStatisticsLocked(currentTime, entry,
1206 injectionResult, timeSpentWaitingForApplication);
1207#if DEBUG_FOCUS
1208 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1209 "timeSpentWaitingForApplication=%0.1fms",
1210 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1211#endif
1212 return injectionResult;
1213}
1214
1215int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1216 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1217 bool* outConflictingPointerActions) {
1218 enum InjectionPermission {
1219 INJECTION_PERMISSION_UNKNOWN,
1220 INJECTION_PERMISSION_GRANTED,
1221 INJECTION_PERMISSION_DENIED
1222 };
1223
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 // For security reasons, we defer updating the touch state until we are sure that
1225 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 int32_t displayId = entry->displayId;
1227 int32_t action = entry->action;
1228 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1229
1230 // Update the touch state as needed based on the properties of the touch event.
1231 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1232 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1233 sp<InputWindowHandle> newHoverWindowHandle;
1234
Jeff Brownf086ddb2014-02-11 14:28:48 -08001235 // Copy current touch state into mTempTouchState.
1236 // This state is always reset at the end of this function, so if we don't find state
1237 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001238 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001239 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1240 if (oldStateIndex >= 0) {
1241 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1242 mTempTouchState.copyFrom(*oldState);
1243 }
1244
1245 bool isSplit = mTempTouchState.split;
1246 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1247 && (mTempTouchState.deviceId != entry->deviceId
1248 || mTempTouchState.source != entry->source
1249 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1251 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1252 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1253 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1254 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1255 || isHoverAction);
1256 bool wrongDevice = false;
1257 if (newGesture) {
1258 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001259 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001261 ALOGD("Dropping event because a pointer for a different device is already down "
1262 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001264 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1266 switchedDevice = false;
1267 wrongDevice = true;
1268 goto Failed;
1269 }
1270 mTempTouchState.reset();
1271 mTempTouchState.down = down;
1272 mTempTouchState.deviceId = entry->deviceId;
1273 mTempTouchState.source = entry->source;
1274 mTempTouchState.displayId = displayId;
1275 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001276 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1277#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001278 ALOGI("Dropping move event because a pointer for a different device is already active "
1279 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001280#endif
1281 // TODO: test multiple simultaneous input streams.
1282 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1283 switchedDevice = false;
1284 wrongDevice = true;
1285 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
1287
1288 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1289 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1290
1291 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1292 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1293 getAxisValue(AMOTION_EVENT_AXIS_X));
1294 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1295 getAxisValue(AMOTION_EVENT_AXIS_Y));
1296 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 bool isTouchModal = false;
1298
1299 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001300 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1301 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001303 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1305 if (windowInfo->displayId != displayId) {
1306 continue; // wrong display
1307 }
1308
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 int32_t flags = windowInfo->layoutParamsFlags;
1310 if (windowInfo->visible) {
1311 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1312 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1313 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1314 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001315 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 break; // found touched window, exit window loop
1317 }
1318 }
1319
1320 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1321 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001323 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 }
1325 }
1326 }
1327
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001329 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1331 // New window supports splitting.
1332 isSplit = true;
1333 } else if (isSplit) {
1334 // New window does not support splitting but we have already split events.
1335 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001336 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
1338
1339 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001340 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 // Try to assign the pointer to the first foreground window we find, if there is one.
1342 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001343 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001344 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1345 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1347 goto Failed;
1348 }
1349 }
1350
1351 // Set target flags.
1352 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1353 if (isSplit) {
1354 targetFlags |= InputTarget::FLAG_SPLIT;
1355 }
1356 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1357 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001358 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1359 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 }
1361
1362 // Update hover state.
1363 if (isHoverAction) {
1364 newHoverWindowHandle = newTouchedWindowHandle;
1365 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1366 newHoverWindowHandle = mLastHoverWindowHandle;
1367 }
1368
1369 // Update the temporary touch state.
1370 BitSet32 pointerIds;
1371 if (isSplit) {
1372 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1373 pointerIds.markBit(pointerId);
1374 }
1375 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1376 } else {
1377 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1378
1379 // If the pointer is not currently down, then ignore the event.
1380 if (! mTempTouchState.down) {
1381#if DEBUG_FOCUS
1382 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001383 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384#endif
1385 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1386 goto Failed;
1387 }
1388
1389 // Check whether touches should slip outside of the current foreground window.
1390 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1391 && entry->pointerCount == 1
1392 && mTempTouchState.isSlippery()) {
1393 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1394 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1395
1396 sp<InputWindowHandle> oldTouchedWindowHandle =
1397 mTempTouchState.getFirstForegroundWindowHandle();
1398 sp<InputWindowHandle> newTouchedWindowHandle =
1399 findTouchedWindowAtLocked(displayId, x, y);
1400 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001401 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001403 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001404 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001405 newTouchedWindowHandle->getName().c_str(),
1406 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407#endif
1408 // Make a slippery exit from the old window.
1409 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1410 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1411
1412 // Make a slippery entrance into the new window.
1413 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1414 isSplit = true;
1415 }
1416
1417 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1418 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1419 if (isSplit) {
1420 targetFlags |= InputTarget::FLAG_SPLIT;
1421 }
1422 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1423 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1424 }
1425
1426 BitSet32 pointerIds;
1427 if (isSplit) {
1428 pointerIds.markBit(entry->pointerProperties[0].id);
1429 }
1430 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1431 }
1432 }
1433 }
1434
1435 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1436 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001437 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438#if DEBUG_HOVER
1439 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001440 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441#endif
1442 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1443 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1444 }
1445
1446 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001447 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448#if DEBUG_HOVER
1449 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001450 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451#endif
1452 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1453 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1454 }
1455 }
1456
1457 // Check permission to inject into all touched foreground windows and ensure there
1458 // is at least one touched foreground window.
1459 {
1460 bool haveForegroundWindow = false;
1461 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1462 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1463 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1464 haveForegroundWindow = true;
1465 if (! checkInjectionPermission(touchedWindow.windowHandle,
1466 entry->injectionState)) {
1467 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1468 injectionPermission = INJECTION_PERMISSION_DENIED;
1469 goto Failed;
1470 }
1471 }
1472 }
1473 if (! haveForegroundWindow) {
1474#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001475 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1476 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477#endif
1478 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1479 goto Failed;
1480 }
1481
1482 // Permission granted to injection into all touched foreground windows.
1483 injectionPermission = INJECTION_PERMISSION_GRANTED;
1484 }
1485
1486 // Check whether windows listening for outside touches are owned by the same UID. If it is
1487 // set the policy flag that we will not reveal coordinate information to this window.
1488 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1489 sp<InputWindowHandle> foregroundWindowHandle =
1490 mTempTouchState.getFirstForegroundWindowHandle();
1491 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1492 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1493 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1494 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1495 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1496 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1497 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1498 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1499 }
1500 }
1501 }
1502 }
1503
1504 // Ensure all touched foreground windows are ready for new input.
1505 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1506 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1507 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001508 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001509 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001510 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001511 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001513 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 goto Unresponsive;
1515 }
1516 }
1517 }
1518
1519 // If this is the first pointer going down and the touched window has a wallpaper
1520 // then also add the touched wallpaper windows so they are locked in for the duration
1521 // of the touch gesture.
1522 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1523 // engine only supports touch events. We would need to add a mechanism similar
1524 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1525 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1526 sp<InputWindowHandle> foregroundWindowHandle =
1527 mTempTouchState.getFirstForegroundWindowHandle();
1528 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001529 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1530 size_t numWindows = windowHandles.size();
1531 for (size_t i = 0; i < numWindows; i++) {
1532 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 const InputWindowInfo* info = windowHandle->getInfo();
1534 if (info->displayId == displayId
1535 && windowHandle->getInfo()->layoutParamsType
1536 == InputWindowInfo::TYPE_WALLPAPER) {
1537 mTempTouchState.addOrUpdateWindow(windowHandle,
1538 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001539 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 | InputTarget::FLAG_DISPATCH_AS_IS,
1541 BitSet32(0));
1542 }
1543 }
1544 }
1545 }
1546
1547 // Success! Output targets.
1548 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1549
1550 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1551 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1552 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1553 touchedWindow.pointerIds, inputTargets);
1554 }
1555
1556 // Drop the outside or hover touch windows since we will not care about them
1557 // in the next iteration.
1558 mTempTouchState.filterNonAsIsTouchWindows();
1559
1560Failed:
1561 // Check injection permission once and for all.
1562 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001563 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 injectionPermission = INJECTION_PERMISSION_GRANTED;
1565 } else {
1566 injectionPermission = INJECTION_PERMISSION_DENIED;
1567 }
1568 }
1569
1570 // Update final pieces of touch state if the injector had permission.
1571 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1572 if (!wrongDevice) {
1573 if (switchedDevice) {
1574#if DEBUG_FOCUS
1575 ALOGD("Conflicting pointer actions: Switched to a different device.");
1576#endif
1577 *outConflictingPointerActions = true;
1578 }
1579
1580 if (isHoverAction) {
1581 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001582 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583#if DEBUG_FOCUS
1584 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1585#endif
1586 *outConflictingPointerActions = true;
1587 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001588 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1590 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001591 mTempTouchState.deviceId = entry->deviceId;
1592 mTempTouchState.source = entry->source;
1593 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 }
1595 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1596 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1597 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001598 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1600 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001601 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602#if DEBUG_FOCUS
1603 ALOGD("Conflicting pointer actions: Down received while already down.");
1604#endif
1605 *outConflictingPointerActions = true;
1606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1608 // One pointer went up.
1609 if (isSplit) {
1610 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1611 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1612
1613 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1614 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1615 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1616 touchedWindow.pointerIds.clearBit(pointerId);
1617 if (touchedWindow.pointerIds.isEmpty()) {
1618 mTempTouchState.windows.removeAt(i);
1619 continue;
1620 }
1621 }
1622 i += 1;
1623 }
1624 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001625 }
1626
1627 // Save changes unless the action was scroll in which case the temporary touch
1628 // state was only valid for this one action.
1629 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1630 if (mTempTouchState.displayId >= 0) {
1631 if (oldStateIndex >= 0) {
1632 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1633 } else {
1634 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1635 }
1636 } else if (oldStateIndex >= 0) {
1637 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 }
1640
1641 // Update hover state.
1642 mLastHoverWindowHandle = newHoverWindowHandle;
1643 }
1644 } else {
1645#if DEBUG_FOCUS
1646 ALOGD("Not updating touch focus because injection was denied.");
1647#endif
1648 }
1649
1650Unresponsive:
1651 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1652 mTempTouchState.reset();
1653
1654 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1655 updateDispatchStatisticsLocked(currentTime, entry,
1656 injectionResult, timeSpentWaitingForApplication);
1657#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,
1688 int32_t displayId) {
1689 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;
1701 target.xOffset = 0;
1702 target.yOffset = 0;
1703 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 Vishniakouf93fcf42017-11-22 16:00:14 -08001858std::string InputDispatcher::getApplicationWindowLabelLocked(
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());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1958#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()) {
2077 incrementPendingForegroundDispatchesLocked(eventEntry);
2078 }
2079
2080 // Enqueue the dispatch entry.
2081 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2082 traceOutboundQueueLengthLocked(connection);
2083}
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);
2197 traceOutboundQueueLengthLocked(connection);
2198 connection->waitQueue.enqueueAtTail(dispatchEntry);
2199 traceWaitQueueLengthLocked(connection);
2200 }
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);
2230 traceOutboundQueueLengthLocked(connection);
2231 drainDispatchQueueLocked(&connection->waitQueue);
2232 traceWaitQueueLengthLocked(connection);
2233
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
2324void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2325 const CancelationOptions& options) {
2326 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2327 synthesizeCancelationEventsForConnectionLocked(
2328 mConnectionsByFd.valueAt(i), options);
2329 }
2330}
2331
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002332void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2333 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:
2375 logOutboundKeyDetailsLocked("cancel - ",
2376 static_cast<KeyEntry*>(cancelationEventEntry));
2377 break;
2378 case EventEntry::TYPE_MOTION:
2379 logOutboundMotionDetailsLocked("cancel - ",
2380 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
2995void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2996 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 =
3015 mWindowHandlesByDisplay.find(displayId);
3016 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
3039bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003040 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003041 for (auto& it : mWindowHandlesByDisplay) {
3042 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3043 size_t numWindows = windowHandles.size();
3044 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003045 if (windowHandles.itemAt(i)->getToken()
3046 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003047 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003048 ALOGE("Found window %s in display %" PRId32
3049 ", but it should belong to display %" PRId32,
3050 windowHandle->getName().c_str(), it.first,
3051 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003052 }
3053 return true;
3054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
3056 }
3057 return false;
3058}
3059
Robert Carr5c8a0262018-10-03 16:30:44 -07003060sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3061 size_t count = mInputChannelsByToken.count(token);
3062 if (count == 0) {
3063 return nullptr;
3064 }
3065 return mInputChannelsByToken.at(token);
3066}
3067
Arthur Hungb92218b2018-08-14 12:00:21 +08003068/**
3069 * Called from InputManagerService, update window handle list by displayId that can receive input.
3070 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3071 * If set an empty list, remove all handles from the specific display.
3072 * For focused handle, check if need to change and send a cancel event to previous one.
3073 * For removed handle, check if need to send a cancel event if already in touch.
3074 */
3075void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3076 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003078 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079#endif
3080 { // acquire lock
3081 AutoMutex _l(mLock);
3082
Arthur Hungb92218b2018-08-14 12:00:21 +08003083 // Copy old handles for release if they are no longer present.
3084 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Tiger Huang721e26f2018-07-24 22:26:19 +08003086 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003088
3089 if (inputWindowHandles.isEmpty()) {
3090 // Remove all handles on a display if there are no windows left.
3091 mWindowHandlesByDisplay.erase(displayId);
3092 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003093 // Since we compare the pointer of input window handles across window updates, we need
3094 // to make sure the handle object for the same window stays unchanged across updates.
3095 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3096 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3097 for (size_t i = 0; i < oldHandles.size(); i++) {
3098 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3099 oldHandlesByTokens[handle->getToken()] = handle;
3100 }
3101
3102 const size_t numWindows = inputWindowHandles.size();
3103 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003104 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003105 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3106 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003107 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003108 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003109 continue;
3110 }
3111
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003112 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003113 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003114 handle->getName().c_str(), displayId,
3115 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003116 continue;
3117 }
3118
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003119 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3120 const sp<InputWindowHandle> oldHandle =
3121 oldHandlesByTokens.at(handle->getToken());
3122 oldHandle->updateFrom(handle);
3123 newHandles.push_back(oldHandle);
3124 } else {
3125 newHandles.push_back(handle);
3126 }
3127 }
3128
3129 for (size_t i = 0; i < newHandles.size(); i++) {
3130 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Arthur Hung7ab76b12019-01-09 19:17:20 +08003131 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3132 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3133 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003134 newFocusedWindowHandle = windowHandle;
3135 }
3136 if (windowHandle == mLastHoverWindowHandle) {
3137 foundHoveredWindow = true;
3138 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003139 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003140
3141 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003142 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 }
3144
3145 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003146 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
Tiger Huang721e26f2018-07-24 22:26:19 +08003149 sp<InputWindowHandle> oldFocusedWindowHandle =
3150 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3151
3152 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3153 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003155 ALOGD("Focus left window: %s in display %" PRId32,
3156 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003158 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3159 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003160 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3162 "focus left window");
3163 synthesizeCancelationEventsForInputChannelLocked(
3164 focusedInputChannel, options);
3165 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003166 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003168 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003170 ALOGD("Focus entered window: %s in display %" PRId32,
3171 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003173 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
Robert Carrf759f162018-11-13 12:57:11 -08003175
3176 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003177 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003178 }
3179
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181
Arthur Hungb92218b2018-08-14 12:00:21 +08003182 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3183 if (stateIndex >= 0) {
3184 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003185 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003186 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003187 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003189 ALOGD("Touched window was removed: %s in display %" PRId32,
3190 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003192 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003193 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003194 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003195 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3196 "touched window was removed");
3197 synthesizeCancelationEventsForInputChannelLocked(
3198 touchedInputChannel, options);
3199 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003200 state.windows.removeAt(i);
3201 } else {
3202 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205 }
3206
3207 // Release information for windows that are no longer present.
3208 // This ensures that unused input channels are released promptly.
3209 // Otherwise, they might stick around until the window handle is destroyed
3210 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003211 size_t numWindows = oldWindowHandles.size();
3212 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003214 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003216 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003218 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 }
3220 }
3221 } // release lock
3222
3223 // Wake up poll loop since it may need to make new input dispatching choices.
3224 mLooper->wake();
3225}
3226
3227void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003228 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003230 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231#endif
3232 { // acquire lock
3233 AutoMutex _l(mLock);
3234
Tiger Huang721e26f2018-07-24 22:26:19 +08003235 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3236 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003237 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003238 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3239 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003241 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003243 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003245 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003247 oldFocusedApplicationHandle->releaseInfo();
3248 oldFocusedApplicationHandle.clear();
3249 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 }
3251
3252#if DEBUG_FOCUS
3253 //logDispatchStateLocked();
3254#endif
3255 } // release lock
3256
3257 // Wake up poll loop since it may need to make new input dispatching choices.
3258 mLooper->wake();
3259}
3260
Tiger Huang721e26f2018-07-24 22:26:19 +08003261/**
3262 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3263 * the display not specified.
3264 *
3265 * We track any unreleased events for each window. If a window loses the ability to receive the
3266 * released event, we will send a cancel event to it. So when the focused display is changed, we
3267 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3268 * display. The display-specified events won't be affected.
3269 */
3270void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3271#if DEBUG_FOCUS
3272 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3273#endif
3274 { // acquire lock
3275 AutoMutex _l(mLock);
3276
3277 if (mFocusedDisplayId != displayId) {
3278 sp<InputWindowHandle> oldFocusedWindowHandle =
3279 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3280 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003281 sp<InputChannel> inputChannel =
3282 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003283 if (inputChannel != nullptr) {
3284 CancelationOptions options(
3285 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3286 "The display which contains this window no longer has focus.");
3287 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3288 }
3289 }
3290 mFocusedDisplayId = displayId;
3291
3292 // Sanity check
3293 sp<InputWindowHandle> newFocusedWindowHandle =
3294 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003295 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003296
Tiger Huang721e26f2018-07-24 22:26:19 +08003297 if (newFocusedWindowHandle == nullptr) {
3298 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3299 if (!mFocusedWindowHandlesByDisplay.empty()) {
3300 ALOGE("But another display has a focused window:");
3301 for (auto& it : mFocusedWindowHandlesByDisplay) {
3302 const int32_t displayId = it.first;
3303 const sp<InputWindowHandle>& windowHandle = it.second;
3304 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3305 displayId, windowHandle->getName().c_str());
3306 }
3307 }
3308 }
3309 }
3310
3311#if DEBUG_FOCUS
3312 logDispatchStateLocked();
3313#endif
3314 } // release lock
3315
3316 // Wake up poll loop since it may need to make new input dispatching choices.
3317 mLooper->wake();
3318}
3319
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3321#if DEBUG_FOCUS
3322 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3323#endif
3324
3325 bool changed;
3326 { // acquire lock
3327 AutoMutex _l(mLock);
3328
3329 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3330 if (mDispatchFrozen && !frozen) {
3331 resetANRTimeoutsLocked();
3332 }
3333
3334 if (mDispatchEnabled && !enabled) {
3335 resetAndDropEverythingLocked("dispatcher is being disabled");
3336 }
3337
3338 mDispatchEnabled = enabled;
3339 mDispatchFrozen = frozen;
3340 changed = true;
3341 } else {
3342 changed = false;
3343 }
3344
3345#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003346 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347#endif
3348 } // release lock
3349
3350 if (changed) {
3351 // Wake up poll loop since it may need to make new input dispatching choices.
3352 mLooper->wake();
3353 }
3354}
3355
3356void InputDispatcher::setInputFilterEnabled(bool enabled) {
3357#if DEBUG_FOCUS
3358 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3359#endif
3360
3361 { // acquire lock
3362 AutoMutex _l(mLock);
3363
3364 if (mInputFilterEnabled == enabled) {
3365 return;
3366 }
3367
3368 mInputFilterEnabled = enabled;
3369 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3370 } // release lock
3371
3372 // Wake up poll loop since there might be work to do to drop everything.
3373 mLooper->wake();
3374}
3375
chaviwfbe5d9c2018-12-26 12:23:37 -08003376bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3377 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003379 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003381 return true;
3382 }
3383
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 { // acquire lock
3385 AutoMutex _l(mLock);
3386
chaviwfbe5d9c2018-12-26 12:23:37 -08003387 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3388 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003389 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003390 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 return false;
3392 }
chaviw4f2dd402018-12-26 15:30:27 -08003393#if DEBUG_FOCUS
3394 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3395 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3396#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3398#if DEBUG_FOCUS
3399 ALOGD("Cannot transfer focus because windows are on different displays.");
3400#endif
3401 return false;
3402 }
3403
3404 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003405 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3406 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3407 for (size_t i = 0; i < state.windows.size(); i++) {
3408 const TouchedWindow& touchedWindow = state.windows[i];
3409 if (touchedWindow.windowHandle == fromWindowHandle) {
3410 int32_t oldTargetFlags = touchedWindow.targetFlags;
3411 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
Jeff Brownf086ddb2014-02-11 14:28:48 -08003413 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Jeff Brownf086ddb2014-02-11 14:28:48 -08003415 int32_t newTargetFlags = oldTargetFlags
3416 & (InputTarget::FLAG_FOREGROUND
3417 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3418 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
Jeff Brownf086ddb2014-02-11 14:28:48 -08003420 found = true;
3421 goto Found;
3422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003425Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426
3427 if (! found) {
3428#if DEBUG_FOCUS
3429 ALOGD("Focus transfer failed because from window did not have focus.");
3430#endif
3431 return false;
3432 }
3433
chaviwfbe5d9c2018-12-26 12:23:37 -08003434
3435 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3436 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3438 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3439 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3440 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3441 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3442
3443 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3444 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3445 "transferring touch focus from this window to another window");
3446 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3447 }
3448
3449#if DEBUG_FOCUS
3450 logDispatchStateLocked();
3451#endif
3452 } // release lock
3453
3454 // Wake up poll loop since it may need to make new input dispatching choices.
3455 mLooper->wake();
3456 return true;
3457}
3458
3459void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3460#if DEBUG_FOCUS
3461 ALOGD("Resetting and dropping all events (%s).", reason);
3462#endif
3463
3464 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3465 synthesizeCancelationEventsForAllConnectionsLocked(options);
3466
3467 resetKeyRepeatLocked();
3468 releasePendingEventLocked();
3469 drainInboundQueueLocked();
3470 resetANRTimeoutsLocked();
3471
Jeff Brownf086ddb2014-02-11 14:28:48 -08003472 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003474 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475}
3476
3477void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003478 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 dumpDispatchStateLocked(dump);
3480
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003481 std::istringstream stream(dump);
3482 std::string line;
3483
3484 while (std::getline(stream, line, '\n')) {
3485 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487}
3488
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003489void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3490 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3491 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003492 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493
Tiger Huang721e26f2018-07-24 22:26:19 +08003494 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3495 dump += StringPrintf(INDENT "FocusedApplications:\n");
3496 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3497 const int32_t displayId = it.first;
3498 const sp<InputApplicationHandle>& applicationHandle = it.second;
3499 dump += StringPrintf(
3500 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3501 displayId,
3502 applicationHandle->getName().c_str(),
3503 applicationHandle->getDispatchingTimeout(
3504 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003507 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003509
3510 if (!mFocusedWindowHandlesByDisplay.empty()) {
3511 dump += StringPrintf(INDENT "FocusedWindows:\n");
3512 for (auto& it : mFocusedWindowHandlesByDisplay) {
3513 const int32_t displayId = it.first;
3514 const sp<InputWindowHandle>& windowHandle = it.second;
3515 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3516 displayId, windowHandle->getName().c_str());
3517 }
3518 } else {
3519 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521
Jeff Brownf086ddb2014-02-11 14:28:48 -08003522 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003523 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003524 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3525 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003526 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003527 state.displayId, toString(state.down), toString(state.split),
3528 state.deviceId, state.source);
3529 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003530 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003531 for (size_t i = 0; i < state.windows.size(); i++) {
3532 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003533 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3534 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003535 touchedWindow.pointerIds.value,
3536 touchedWindow.targetFlags);
3537 }
3538 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003539 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 }
3542 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003543 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 }
3545
Arthur Hungb92218b2018-08-14 12:00:21 +08003546 if (!mWindowHandlesByDisplay.empty()) {
3547 for (auto& it : mWindowHandlesByDisplay) {
3548 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003549 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003550 if (!windowHandles.isEmpty()) {
3551 dump += INDENT2 "Windows:\n";
3552 for (size_t i = 0; i < windowHandles.size(); i++) {
3553 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3554 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555
Arthur Hungb92218b2018-08-14 12:00:21 +08003556 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3557 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3558 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003559 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003560 "touchableRegion=",
3561 i, windowInfo->name.c_str(), windowInfo->displayId,
3562 toString(windowInfo->paused),
3563 toString(windowInfo->hasFocus),
3564 toString(windowInfo->hasWallpaper),
3565 toString(windowInfo->visible),
3566 toString(windowInfo->canReceiveKeys),
3567 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3568 windowInfo->layer,
3569 windowInfo->frameLeft, windowInfo->frameTop,
3570 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003571 windowInfo->globalScaleFactor,
3572 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003573 dumpRegion(dump, windowInfo->touchableRegion);
3574 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3575 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3576 windowInfo->ownerPid, windowInfo->ownerUid,
3577 windowInfo->dispatchingTimeout / 1000000.0);
3578 }
3579 } else {
3580 dump += INDENT2 "Windows: <none>\n";
3581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 }
3583 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003584 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 }
3586
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003587 if (!mMonitoringChannelsByDisplay.empty()) {
3588 for (auto& it : mMonitoringChannelsByDisplay) {
3589 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003590 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003591 const size_t numChannels = monitoringChannels.size();
3592 for (size_t i = 0; i < numChannels; i++) {
3593 const sp<InputChannel>& channel = monitoringChannels[i];
3594 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3595 }
3596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003598 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 }
3600
3601 nsecs_t currentTime = now();
3602
3603 // Dump recently dispatched or dropped events from oldest to newest.
3604 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003605 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003607 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 (currentTime - entry->eventTime) * 0.000001f);
3611 }
3612 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003613 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 }
3615
3616 // Dump event currently being dispatched.
3617 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003618 dump += INDENT "PendingEvent:\n";
3619 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3623 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003624 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626
3627 // Dump inbound events from oldest to newest.
3628 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003629 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003631 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 (currentTime - entry->eventTime) * 0.000001f);
3635 }
3636 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
3639
Michael Wright78f24442014-08-06 15:55:28 -07003640 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003642 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3643 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3644 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003646 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3647 }
3648 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003649 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003650 }
3651
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3655 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003656 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003658 i, connection->getInputChannelName().c_str(),
3659 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 connection->getStatusLabel(), toString(connection->monitor),
3661 toString(connection->inputPublisherBlocked));
3662
3663 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003664 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665 connection->outboundQueue.count());
3666 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3667 entry = entry->next) {
3668 dump.append(INDENT4);
3669 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003670 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 entry->targetFlags, entry->resolvedAction,
3672 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3673 }
3674 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003675 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 }
3677
3678 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003679 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 connection->waitQueue.count());
3681 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3682 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003683 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003685 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 "age=%0.1fms, wait=%0.1fms\n",
3687 entry->targetFlags, entry->resolvedAction,
3688 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3689 (currentTime - entry->deliveryTime) * 0.000001f);
3690 }
3691 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003692 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
3694 }
3695 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
3698
3699 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003700 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 (mAppSwitchDueTime - now()) / 1000000.0);
3702 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003703 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
3705
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003706 dump += INDENT "Configuration:\n";
3707 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003709 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 mConfig.keyRepeatTimeout * 0.000001f);
3711}
3712
Robert Carr803535b2018-08-02 16:38:15 -07003713status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003715 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3716 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717#endif
3718
3719 { // acquire lock
3720 AutoMutex _l(mLock);
3721
Robert Carr4e670e52018-08-15 13:26:12 -07003722 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3723 // treat inputChannel as monitor channel for displayId.
3724 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3725 if (monitor) {
3726 inputChannel->setToken(new BBinder());
3727 }
3728
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 if (getConnectionIndexLocked(inputChannel) >= 0) {
3730 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003731 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 return BAD_VALUE;
3733 }
3734
Robert Carr803535b2018-08-02 16:38:15 -07003735 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736
3737 int fd = inputChannel->getFd();
3738 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003739 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003741 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003743 Vector<sp<InputChannel>>& monitoringChannels =
3744 mMonitoringChannelsByDisplay[displayId];
3745 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 }
3747
3748 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3749 } // release lock
3750
3751 // Wake the looper because some connections have changed.
3752 mLooper->wake();
3753 return OK;
3754}
3755
3756status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3757#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003758 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759#endif
3760
3761 { // acquire lock
3762 AutoMutex _l(mLock);
3763
3764 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3765 if (status) {
3766 return status;
3767 }
3768 } // release lock
3769
3770 // Wake the poll loop because removing the connection may have changed the current
3771 // synchronization state.
3772 mLooper->wake();
3773 return OK;
3774}
3775
3776status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3777 bool notify) {
3778 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3779 if (connectionIndex < 0) {
3780 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003781 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 return BAD_VALUE;
3783 }
3784
3785 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3786 mConnectionsByFd.removeItemsAt(connectionIndex);
3787
Robert Carr5c8a0262018-10-03 16:30:44 -07003788 mInputChannelsByToken.erase(inputChannel->getToken());
3789
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 if (connection->monitor) {
3791 removeMonitorChannelLocked(inputChannel);
3792 }
3793
3794 mLooper->removeFd(inputChannel->getFd());
3795
3796 nsecs_t currentTime = now();
3797 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3798
3799 connection->status = Connection::STATUS_ZOMBIE;
3800 return OK;
3801}
3802
3803void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003804 for (auto it = mMonitoringChannelsByDisplay.begin();
3805 it != mMonitoringChannelsByDisplay.end(); ) {
3806 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3807 const size_t numChannels = monitoringChannels.size();
3808 for (size_t i = 0; i < numChannels; i++) {
3809 if (monitoringChannels[i] == inputChannel) {
3810 monitoringChannels.removeAt(i);
3811 break;
3812 }
3813 }
3814 if (monitoringChannels.empty()) {
3815 it = mMonitoringChannelsByDisplay.erase(it);
3816 } else {
3817 ++it;
3818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
3820}
3821
3822ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003823 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003824 return -1;
3825 }
3826
Robert Carr4e670e52018-08-15 13:26:12 -07003827 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3828 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3829 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3830 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832 }
Robert Carr4e670e52018-08-15 13:26:12 -07003833
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 return -1;
3835}
3836
3837void InputDispatcher::onDispatchCycleFinishedLocked(
3838 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3839 CommandEntry* commandEntry = postCommandLocked(
3840 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3841 commandEntry->connection = connection;
3842 commandEntry->eventTime = currentTime;
3843 commandEntry->seq = seq;
3844 commandEntry->handled = handled;
3845}
3846
3847void InputDispatcher::onDispatchCycleBrokenLocked(
3848 nsecs_t currentTime, const sp<Connection>& connection) {
3849 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003850 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851
3852 CommandEntry* commandEntry = postCommandLocked(
3853 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3854 commandEntry->connection = connection;
3855}
3856
chaviw0c06c6e2019-01-09 13:27:07 -08003857void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3858 const sp<InputWindowHandle>& newFocus) {
3859 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3860 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003861 CommandEntry* commandEntry = postCommandLocked(
3862 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003863 commandEntry->oldToken = oldToken;
3864 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003865}
3866
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867void InputDispatcher::onANRLocked(
3868 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3869 const sp<InputWindowHandle>& windowHandle,
3870 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3871 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3872 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3873 ALOGI("Application is not responding: %s. "
3874 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003875 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 dispatchLatency, waitDuration, reason);
3877
3878 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003879 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880 struct tm tm;
3881 localtime_r(&t, &tm);
3882 char timestr[64];
3883 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3884 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003885 mLastANRState += INDENT "ANR:\n";
3886 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3887 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3888 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3889 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3890 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3891 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892 dumpDispatchStateLocked(mLastANRState);
3893
3894 CommandEntry* commandEntry = postCommandLocked(
3895 & InputDispatcher::doNotifyANRLockedInterruptible);
3896 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003897 commandEntry->inputChannel = windowHandle != nullptr ?
3898 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 commandEntry->reason = reason;
3900}
3901
3902void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3903 CommandEntry* commandEntry) {
3904 mLock.unlock();
3905
3906 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3907
3908 mLock.lock();
3909}
3910
3911void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3912 CommandEntry* commandEntry) {
3913 sp<Connection> connection = commandEntry->connection;
3914
3915 if (connection->status != Connection::STATUS_ZOMBIE) {
3916 mLock.unlock();
3917
Robert Carr803535b2018-08-02 16:38:15 -07003918 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919
3920 mLock.lock();
3921 }
3922}
3923
Robert Carrf759f162018-11-13 12:57:11 -08003924void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3925 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003926 sp<IBinder> oldToken = commandEntry->oldToken;
3927 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003928 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003929 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003930 mLock.lock();
3931}
3932
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933void InputDispatcher::doNotifyANRLockedInterruptible(
3934 CommandEntry* commandEntry) {
3935 mLock.unlock();
3936
3937 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003938 commandEntry->inputApplicationHandle,
3939 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 commandEntry->reason);
3941
3942 mLock.lock();
3943
3944 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003945 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946}
3947
3948void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3949 CommandEntry* commandEntry) {
3950 KeyEntry* entry = commandEntry->keyEntry;
3951
3952 KeyEvent event;
3953 initializeKeyEvent(&event, entry);
3954
3955 mLock.unlock();
3956
Michael Wright2b3c3302018-03-02 17:19:13 +00003957 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003958 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3959 commandEntry->inputChannel->getToken() : nullptr;
3960 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003962 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3963 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3964 std::to_string(t.duration().count()).c_str());
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
3967 mLock.lock();
3968
3969 if (delay < 0) {
3970 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3971 } else if (!delay) {
3972 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3973 } else {
3974 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3975 entry->interceptKeyWakeupTime = now() + delay;
3976 }
3977 entry->release();
3978}
3979
3980void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3981 CommandEntry* commandEntry) {
3982 sp<Connection> connection = commandEntry->connection;
3983 nsecs_t finishTime = commandEntry->eventTime;
3984 uint32_t seq = commandEntry->seq;
3985 bool handled = commandEntry->handled;
3986
3987 // Handle post-event policy actions.
3988 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3989 if (dispatchEntry) {
3990 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3991 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003992 std::string msg =
3993 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003994 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003996 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 }
3998
3999 bool restartEvent;
4000 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4001 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4002 restartEvent = afterKeyEventLockedInterruptible(connection,
4003 dispatchEntry, keyEntry, handled);
4004 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4005 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4006 restartEvent = afterMotionEventLockedInterruptible(connection,
4007 dispatchEntry, motionEntry, handled);
4008 } else {
4009 restartEvent = false;
4010 }
4011
4012 // Dequeue the event and start the next cycle.
4013 // Note that because the lock might have been released, it is possible that the
4014 // contents of the wait queue to have been drained, so we need to double-check
4015 // a few things.
4016 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4017 connection->waitQueue.dequeue(dispatchEntry);
4018 traceWaitQueueLengthLocked(connection);
4019 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4020 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4021 traceOutboundQueueLengthLocked(connection);
4022 } else {
4023 releaseDispatchEntryLocked(dispatchEntry);
4024 }
4025 }
4026
4027 // Start the next dispatch cycle for this connection.
4028 startDispatchCycleLocked(now(), connection);
4029 }
4030}
4031
4032bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4033 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004034 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004035 if (!handled) {
4036 // Report the key as unhandled, since the fallback was not handled.
4037 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4038 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004039 return false;
4040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004042 // Get the fallback key state.
4043 // Clear it out after dispatching the UP.
4044 int32_t originalKeyCode = keyEntry->keyCode;
4045 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4046 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4047 connection->inputState.removeFallbackKey(originalKeyCode);
4048 }
4049
4050 if (handled || !dispatchEntry->hasForegroundTarget()) {
4051 // If the application handles the original key for which we previously
4052 // generated a fallback or if the window is not a foreground window,
4053 // then cancel the associated fallback key, if any.
4054 if (fallbackKeyCode != -1) {
4055 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004057 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4059 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4060 keyEntry->policyFlags);
4061#endif
4062 KeyEvent event;
4063 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004064 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065
4066 mLock.unlock();
4067
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004068 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4069 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
4071 mLock.lock();
4072
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004073 // Cancel the fallback key.
4074 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004076 "application handled the original non-fallback key "
4077 "or is no longer a foreground target, "
4078 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 options.keyCode = fallbackKeyCode;
4080 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004082 connection->inputState.removeFallbackKey(originalKeyCode);
4083 }
4084 } else {
4085 // If the application did not handle a non-fallback key, first check
4086 // that we are in a good state to perform unhandled key event processing
4087 // Then ask the policy what to do with it.
4088 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4089 && keyEntry->repeatCount == 0;
4090 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004092 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4093 "since this is not an initial down. "
4094 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4095 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4096 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004098 return false;
4099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004101 // Dispatch the unhandled key to the policy.
4102#if DEBUG_OUTBOUND_EVENT_DETAILS
4103 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4104 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4105 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4106 keyEntry->policyFlags);
4107#endif
4108 KeyEvent event;
4109 initializeKeyEvent(&event, keyEntry);
4110
4111 mLock.unlock();
4112
4113 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4114 &event, keyEntry->policyFlags, &event);
4115
4116 mLock.lock();
4117
4118 if (connection->status != Connection::STATUS_NORMAL) {
4119 connection->inputState.removeFallbackKey(originalKeyCode);
4120 return false;
4121 }
4122
4123 // Latch the fallback keycode for this key on an initial down.
4124 // The fallback keycode cannot change at any other point in the lifecycle.
4125 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004127 fallbackKeyCode = event.getKeyCode();
4128 } else {
4129 fallbackKeyCode = AKEYCODE_UNKNOWN;
4130 }
4131 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4132 }
4133
4134 ALOG_ASSERT(fallbackKeyCode != -1);
4135
4136 // Cancel the fallback key if the policy decides not to send it anymore.
4137 // We will continue to dispatch the key to the policy but we will no
4138 // longer dispatch a fallback key to the application.
4139 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4140 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4141#if DEBUG_OUTBOUND_EVENT_DETAILS
4142 if (fallback) {
4143 ALOGD("Unhandled key event: Policy requested to send key %d"
4144 "as a fallback for %d, but on the DOWN it had requested "
4145 "to send %d instead. Fallback canceled.",
4146 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4147 } else {
4148 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4149 "but on the DOWN it had requested to send %d. "
4150 "Fallback canceled.",
4151 originalKeyCode, fallbackKeyCode);
4152 }
4153#endif
4154
4155 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4156 "canceling fallback, policy no longer desires it");
4157 options.keyCode = fallbackKeyCode;
4158 synthesizeCancelationEventsForConnectionLocked(connection, options);
4159
4160 fallback = false;
4161 fallbackKeyCode = AKEYCODE_UNKNOWN;
4162 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4163 connection->inputState.setFallbackKey(originalKeyCode,
4164 fallbackKeyCode);
4165 }
4166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
4168#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004169 {
4170 std::string msg;
4171 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4172 connection->inputState.getFallbackKeys();
4173 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4174 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4175 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004177 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4178 fallbackKeys.size(), msg.c_str());
4179 }
4180#endif
4181
4182 if (fallback) {
4183 // Restart the dispatch cycle using the fallback key.
4184 keyEntry->eventTime = event.getEventTime();
4185 keyEntry->deviceId = event.getDeviceId();
4186 keyEntry->source = event.getSource();
4187 keyEntry->displayId = event.getDisplayId();
4188 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4189 keyEntry->keyCode = fallbackKeyCode;
4190 keyEntry->scanCode = event.getScanCode();
4191 keyEntry->metaState = event.getMetaState();
4192 keyEntry->repeatCount = event.getRepeatCount();
4193 keyEntry->downTime = event.getDownTime();
4194 keyEntry->syntheticRepeat = false;
4195
4196#if DEBUG_OUTBOUND_EVENT_DETAILS
4197 ALOGD("Unhandled key event: Dispatching fallback key. "
4198 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4199 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4200#endif
4201 return true; // restart the event
4202 } else {
4203#if DEBUG_OUTBOUND_EVENT_DETAILS
4204 ALOGD("Unhandled key event: No fallback key.");
4205#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004206
4207 // Report the key as unhandled, since there is no fallback key.
4208 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 }
4210 }
4211 return false;
4212}
4213
4214bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4215 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4216 return false;
4217}
4218
4219void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4220 mLock.unlock();
4221
4222 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4223
4224 mLock.lock();
4225}
4226
4227void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004228 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4230 entry->downTime, entry->eventTime);
4231}
4232
4233void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4234 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4235 // TODO Write some statistics about how long we spend waiting.
4236}
4237
4238void InputDispatcher::traceInboundQueueLengthLocked() {
4239 if (ATRACE_ENABLED()) {
4240 ATRACE_INT("iq", mInboundQueue.count());
4241 }
4242}
4243
4244void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4245 if (ATRACE_ENABLED()) {
4246 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004247 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 ATRACE_INT(counterName, connection->outboundQueue.count());
4249 }
4250}
4251
4252void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4253 if (ATRACE_ENABLED()) {
4254 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004255 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 ATRACE_INT(counterName, connection->waitQueue.count());
4257 }
4258}
4259
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004260void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 AutoMutex _l(mLock);
4262
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004263 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 dumpDispatchStateLocked(dump);
4265
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004266 if (!mLastANRState.empty()) {
4267 dump += "\nInput Dispatcher State at time of last ANR:\n";
4268 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270}
4271
4272void InputDispatcher::monitor() {
4273 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4274 mLock.lock();
4275 mLooper->wake();
4276 mDispatcherIsAliveCondition.wait(mLock);
4277 mLock.unlock();
4278}
4279
4280
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281// --- InputDispatcher::InjectionState ---
4282
4283InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4284 refCount(1),
4285 injectorPid(injectorPid), injectorUid(injectorUid),
4286 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4287 pendingForegroundDispatches(0) {
4288}
4289
4290InputDispatcher::InjectionState::~InjectionState() {
4291}
4292
4293void InputDispatcher::InjectionState::release() {
4294 refCount -= 1;
4295 if (refCount == 0) {
4296 delete this;
4297 } else {
4298 ALOG_ASSERT(refCount > 0);
4299 }
4300}
4301
4302
4303// --- InputDispatcher::EventEntry ---
4304
Prabir Pradhan42611e02018-11-27 14:04:02 -08004305InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4306 nsecs_t eventTime, uint32_t policyFlags) :
4307 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4308 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309}
4310
4311InputDispatcher::EventEntry::~EventEntry() {
4312 releaseInjectionState();
4313}
4314
4315void InputDispatcher::EventEntry::release() {
4316 refCount -= 1;
4317 if (refCount == 0) {
4318 delete this;
4319 } else {
4320 ALOG_ASSERT(refCount > 0);
4321 }
4322}
4323
4324void InputDispatcher::EventEntry::releaseInjectionState() {
4325 if (injectionState) {
4326 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004327 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 }
4329}
4330
4331
4332// --- InputDispatcher::ConfigurationChangedEntry ---
4333
Prabir Pradhan42611e02018-11-27 14:04:02 -08004334InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4335 uint32_t sequenceNum, nsecs_t eventTime) :
4336 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337}
4338
4339InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4340}
4341
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004342void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4343 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344}
4345
4346
4347// --- InputDispatcher::DeviceResetEntry ---
4348
Prabir Pradhan42611e02018-11-27 14:04:02 -08004349InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4350 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4351 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 deviceId(deviceId) {
4353}
4354
4355InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4356}
4357
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004358void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4359 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 deviceId, policyFlags);
4361}
4362
4363
4364// --- InputDispatcher::KeyEntry ---
4365
Prabir Pradhan42611e02018-11-27 14:04:02 -08004366InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004367 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4369 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004370 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004371 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4373 repeatCount(repeatCount), downTime(downTime),
4374 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4375 interceptKeyWakeupTime(0) {
4376}
4377
4378InputDispatcher::KeyEntry::~KeyEntry() {
4379}
4380
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004381void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004382 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4384 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004385 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004386 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387}
4388
4389void InputDispatcher::KeyEntry::recycle() {
4390 releaseInjectionState();
4391
4392 dispatchInProgress = false;
4393 syntheticRepeat = false;
4394 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4395 interceptKeyWakeupTime = 0;
4396}
4397
4398
4399// --- InputDispatcher::MotionEntry ---
4400
Prabir Pradhan42611e02018-11-27 14:04:02 -08004401InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004402 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4403 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004404 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4405 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004406 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004407 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4408 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004409 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004411 deviceId(deviceId), source(source), displayId(displayId), action(action),
4412 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004413 classification(classification), edgeFlags(edgeFlags),
4414 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004415 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 for (uint32_t i = 0; i < pointerCount; i++) {
4417 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4418 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004419 if (xOffset || yOffset) {
4420 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 }
4423}
4424
4425InputDispatcher::MotionEntry::~MotionEntry() {
4426}
4427
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004428void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004429 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004430 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004431 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004432 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004433 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4434 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004435
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 for (uint32_t i = 0; i < pointerCount; i++) {
4437 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004438 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004440 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 pointerCoords[i].getX(), pointerCoords[i].getY());
4442 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004443 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444}
4445
4446
4447// --- InputDispatcher::DispatchEntry ---
4448
4449volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4450
4451InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004452 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4453 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 seq(nextSeq()),
4455 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004456 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4457 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4459 eventEntry->refCount += 1;
4460}
4461
4462InputDispatcher::DispatchEntry::~DispatchEntry() {
4463 eventEntry->release();
4464}
4465
4466uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4467 // Sequence number 0 is reserved and will never be returned.
4468 uint32_t seq;
4469 do {
4470 seq = android_atomic_inc(&sNextSeqAtomic);
4471 } while (!seq);
4472 return seq;
4473}
4474
4475
4476// --- InputDispatcher::InputState ---
4477
4478InputDispatcher::InputState::InputState() {
4479}
4480
4481InputDispatcher::InputState::~InputState() {
4482}
4483
4484bool InputDispatcher::InputState::isNeutral() const {
4485 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4486}
4487
4488bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4489 int32_t displayId) const {
4490 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4491 const MotionMemento& memento = mMotionMementos.itemAt(i);
4492 if (memento.deviceId == deviceId
4493 && memento.source == source
4494 && memento.displayId == displayId
4495 && memento.hovering) {
4496 return true;
4497 }
4498 }
4499 return false;
4500}
4501
4502bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4503 int32_t action, int32_t flags) {
4504 switch (action) {
4505 case AKEY_EVENT_ACTION_UP: {
4506 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4507 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4508 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4509 mFallbackKeys.removeItemsAt(i);
4510 } else {
4511 i += 1;
4512 }
4513 }
4514 }
4515 ssize_t index = findKeyMemento(entry);
4516 if (index >= 0) {
4517 mKeyMementos.removeAt(index);
4518 return true;
4519 }
4520 /* FIXME: We can't just drop the key up event because that prevents creating
4521 * popup windows that are automatically shown when a key is held and then
4522 * dismissed when the key is released. The problem is that the popup will
4523 * not have received the original key down, so the key up will be considered
4524 * to be inconsistent with its observed state. We could perhaps handle this
4525 * by synthesizing a key down but that will cause other problems.
4526 *
4527 * So for now, allow inconsistent key up events to be dispatched.
4528 *
4529#if DEBUG_OUTBOUND_EVENT_DETAILS
4530 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4531 "keyCode=%d, scanCode=%d",
4532 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4533#endif
4534 return false;
4535 */
4536 return true;
4537 }
4538
4539 case AKEY_EVENT_ACTION_DOWN: {
4540 ssize_t index = findKeyMemento(entry);
4541 if (index >= 0) {
4542 mKeyMementos.removeAt(index);
4543 }
4544 addKeyMemento(entry, flags);
4545 return true;
4546 }
4547
4548 default:
4549 return true;
4550 }
4551}
4552
4553bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4554 int32_t action, int32_t flags) {
4555 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4556 switch (actionMasked) {
4557 case AMOTION_EVENT_ACTION_UP:
4558 case AMOTION_EVENT_ACTION_CANCEL: {
4559 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4560 if (index >= 0) {
4561 mMotionMementos.removeAt(index);
4562 return true;
4563 }
4564#if DEBUG_OUTBOUND_EVENT_DETAILS
4565 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004566 "displayId=%" PRId32 ", actionMasked=%d",
4567 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568#endif
4569 return false;
4570 }
4571
4572 case AMOTION_EVENT_ACTION_DOWN: {
4573 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4574 if (index >= 0) {
4575 mMotionMementos.removeAt(index);
4576 }
4577 addMotionMemento(entry, flags, false /*hovering*/);
4578 return true;
4579 }
4580
4581 case AMOTION_EVENT_ACTION_POINTER_UP:
4582 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4583 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004584 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4585 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4586 // generate cancellation events for these since they're based in relative rather than
4587 // absolute units.
4588 return true;
4589 }
4590
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004592
4593 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4594 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4595 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4596 // other value and we need to track the motion so we can send cancellation events for
4597 // anything generating fallback events (e.g. DPad keys for joystick movements).
4598 if (index >= 0) {
4599 if (entry->pointerCoords[0].isEmpty()) {
4600 mMotionMementos.removeAt(index);
4601 } else {
4602 MotionMemento& memento = mMotionMementos.editItemAt(index);
4603 memento.setPointers(entry);
4604 }
4605 } else if (!entry->pointerCoords[0].isEmpty()) {
4606 addMotionMemento(entry, flags, false /*hovering*/);
4607 }
4608
4609 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4610 return true;
4611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612 if (index >= 0) {
4613 MotionMemento& memento = mMotionMementos.editItemAt(index);
4614 memento.setPointers(entry);
4615 return true;
4616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617#if DEBUG_OUTBOUND_EVENT_DETAILS
4618 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004619 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4620 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621#endif
4622 return false;
4623 }
4624
4625 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4626 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4627 if (index >= 0) {
4628 mMotionMementos.removeAt(index);
4629 return true;
4630 }
4631#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004632 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4633 "displayId=%" PRId32,
4634 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635#endif
4636 return false;
4637 }
4638
4639 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4640 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4641 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4642 if (index >= 0) {
4643 mMotionMementos.removeAt(index);
4644 }
4645 addMotionMemento(entry, flags, true /*hovering*/);
4646 return true;
4647 }
4648
4649 default:
4650 return true;
4651 }
4652}
4653
4654ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4655 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4656 const KeyMemento& memento = mKeyMementos.itemAt(i);
4657 if (memento.deviceId == entry->deviceId
4658 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004659 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 && memento.keyCode == entry->keyCode
4661 && memento.scanCode == entry->scanCode) {
4662 return i;
4663 }
4664 }
4665 return -1;
4666}
4667
4668ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4669 bool hovering) const {
4670 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4671 const MotionMemento& memento = mMotionMementos.itemAt(i);
4672 if (memento.deviceId == entry->deviceId
4673 && memento.source == entry->source
4674 && memento.displayId == entry->displayId
4675 && memento.hovering == hovering) {
4676 return i;
4677 }
4678 }
4679 return -1;
4680}
4681
4682void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4683 mKeyMementos.push();
4684 KeyMemento& memento = mKeyMementos.editTop();
4685 memento.deviceId = entry->deviceId;
4686 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004687 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 memento.keyCode = entry->keyCode;
4689 memento.scanCode = entry->scanCode;
4690 memento.metaState = entry->metaState;
4691 memento.flags = flags;
4692 memento.downTime = entry->downTime;
4693 memento.policyFlags = entry->policyFlags;
4694}
4695
4696void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4697 int32_t flags, bool hovering) {
4698 mMotionMementos.push();
4699 MotionMemento& memento = mMotionMementos.editTop();
4700 memento.deviceId = entry->deviceId;
4701 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004702 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 memento.flags = flags;
4704 memento.xPrecision = entry->xPrecision;
4705 memento.yPrecision = entry->yPrecision;
4706 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 memento.setPointers(entry);
4708 memento.hovering = hovering;
4709 memento.policyFlags = entry->policyFlags;
4710}
4711
4712void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4713 pointerCount = entry->pointerCount;
4714 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4715 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4716 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4717 }
4718}
4719
4720void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4721 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4722 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4723 const KeyMemento& memento = mKeyMementos.itemAt(i);
4724 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004725 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004726 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4728 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4729 }
4730 }
4731
4732 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4733 const MotionMemento& memento = mMotionMementos.itemAt(i);
4734 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004735 const int32_t action = memento.hovering ?
4736 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004737 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004738 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004739 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4740 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004742 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004743 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 }
4745 }
4746}
4747
4748void InputDispatcher::InputState::clear() {
4749 mKeyMementos.clear();
4750 mMotionMementos.clear();
4751 mFallbackKeys.clear();
4752}
4753
4754void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4755 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4756 const MotionMemento& memento = mMotionMementos.itemAt(i);
4757 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4758 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4759 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4760 if (memento.deviceId == otherMemento.deviceId
4761 && memento.source == otherMemento.source
4762 && memento.displayId == otherMemento.displayId) {
4763 other.mMotionMementos.removeAt(j);
4764 } else {
4765 j += 1;
4766 }
4767 }
4768 other.mMotionMementos.push(memento);
4769 }
4770 }
4771}
4772
4773int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4774 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4775 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4776}
4777
4778void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4779 int32_t fallbackKeyCode) {
4780 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4781 if (index >= 0) {
4782 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4783 } else {
4784 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4785 }
4786}
4787
4788void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4789 mFallbackKeys.removeItem(originalKeyCode);
4790}
4791
4792bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4793 const CancelationOptions& options) {
4794 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4795 return false;
4796 }
4797
4798 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4799 return false;
4800 }
4801
4802 switch (options.mode) {
4803 case CancelationOptions::CANCEL_ALL_EVENTS:
4804 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4805 return true;
4806 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4807 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004808 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4809 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 default:
4811 return false;
4812 }
4813}
4814
4815bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4816 const CancelationOptions& options) {
4817 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4818 return false;
4819 }
4820
4821 switch (options.mode) {
4822 case CancelationOptions::CANCEL_ALL_EVENTS:
4823 return true;
4824 case CancelationOptions::CANCEL_POINTER_EVENTS:
4825 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4826 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4827 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004828 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4829 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 default:
4831 return false;
4832 }
4833}
4834
4835
4836// --- InputDispatcher::Connection ---
4837
Robert Carr803535b2018-08-02 16:38:15 -07004838InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4839 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 monitor(monitor),
4841 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4842}
4843
4844InputDispatcher::Connection::~Connection() {
4845}
4846
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004847const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004848 if (inputChannel != nullptr) {
4849 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 }
4851 if (monitor) {
4852 return "monitor";
4853 }
4854 return "?";
4855}
4856
4857const char* InputDispatcher::Connection::getStatusLabel() const {
4858 switch (status) {
4859 case STATUS_NORMAL:
4860 return "NORMAL";
4861
4862 case STATUS_BROKEN:
4863 return "BROKEN";
4864
4865 case STATUS_ZOMBIE:
4866 return "ZOMBIE";
4867
4868 default:
4869 return "UNKNOWN";
4870 }
4871}
4872
4873InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004874 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 if (entry->seq == seq) {
4876 return entry;
4877 }
4878 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004879 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880}
4881
4882
4883// --- InputDispatcher::CommandEntry ---
4884
4885InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004886 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 seq(0), handled(false) {
4888}
4889
4890InputDispatcher::CommandEntry::~CommandEntry() {
4891}
4892
4893
4894// --- InputDispatcher::TouchState ---
4895
4896InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004897 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898}
4899
4900InputDispatcher::TouchState::~TouchState() {
4901}
4902
4903void InputDispatcher::TouchState::reset() {
4904 down = false;
4905 split = false;
4906 deviceId = -1;
4907 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004908 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 windows.clear();
4910}
4911
4912void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4913 down = other.down;
4914 split = other.split;
4915 deviceId = other.deviceId;
4916 source = other.source;
4917 displayId = other.displayId;
4918 windows = other.windows;
4919}
4920
4921void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4922 int32_t targetFlags, BitSet32 pointerIds) {
4923 if (targetFlags & InputTarget::FLAG_SPLIT) {
4924 split = true;
4925 }
4926
4927 for (size_t i = 0; i < windows.size(); i++) {
4928 TouchedWindow& touchedWindow = windows.editItemAt(i);
4929 if (touchedWindow.windowHandle == windowHandle) {
4930 touchedWindow.targetFlags |= targetFlags;
4931 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4932 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4933 }
4934 touchedWindow.pointerIds.value |= pointerIds.value;
4935 return;
4936 }
4937 }
4938
4939 windows.push();
4940
4941 TouchedWindow& touchedWindow = windows.editTop();
4942 touchedWindow.windowHandle = windowHandle;
4943 touchedWindow.targetFlags = targetFlags;
4944 touchedWindow.pointerIds = pointerIds;
4945}
4946
4947void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4948 for (size_t i = 0; i < windows.size(); i++) {
4949 if (windows.itemAt(i).windowHandle == windowHandle) {
4950 windows.removeAt(i);
4951 return;
4952 }
4953 }
4954}
4955
Robert Carr803535b2018-08-02 16:38:15 -07004956void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4957 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004958 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004959 windows.removeAt(i);
4960 return;
4961 }
4962 }
4963}
4964
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4966 for (size_t i = 0 ; i < windows.size(); ) {
4967 TouchedWindow& window = windows.editItemAt(i);
4968 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4969 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4970 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4971 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4972 i += 1;
4973 } else {
4974 windows.removeAt(i);
4975 }
4976 }
4977}
4978
4979sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4980 for (size_t i = 0; i < windows.size(); i++) {
4981 const TouchedWindow& window = windows.itemAt(i);
4982 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4983 return window.windowHandle;
4984 }
4985 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004986 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987}
4988
4989bool InputDispatcher::TouchState::isSlippery() const {
4990 // Must have exactly one foreground window.
4991 bool haveSlipperyForegroundWindow = false;
4992 for (size_t i = 0; i < windows.size(); i++) {
4993 const TouchedWindow& window = windows.itemAt(i);
4994 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4995 if (haveSlipperyForegroundWindow
4996 || !(window.windowHandle->getInfo()->layoutParamsFlags
4997 & InputWindowInfo::FLAG_SLIPPERY)) {
4998 return false;
4999 }
5000 haveSlipperyForegroundWindow = true;
5001 }
5002 }
5003 return haveSlipperyForegroundWindow;
5004}
5005
5006
5007// --- InputDispatcherThread ---
5008
5009InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5010 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5011}
5012
5013InputDispatcherThread::~InputDispatcherThread() {
5014}
5015
5016bool InputDispatcherThread::threadLoop() {
5017 mDispatcher->dispatchOnce();
5018 return true;
5019}
5020
5021} // namespace android