1 /* 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 48 #include <errno.h> 49 #include <inttypes.h> 50 #include <limits.h> 51 #include <sstream> 52 #include <stddef.h> 53 #include <time.h> 54 #include <unistd.h> 55 56 #include <android-base/chrono_utils.h> 57 #include <android-base/stringprintf.h> 58 #include <log/log.h> 59 #include <utils/Trace.h> 60 #include <powermanager/PowerManager.h> 61 #include <binder/Binder.h> 62 63 #define INDENT " " 64 #define INDENT2 " " 65 #define INDENT3 " " 66 #define INDENT4 " " 67 68 using android::base::StringPrintf; 69 70 namespace 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. 74 constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec 75 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. 79 constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec 80 81 // Amount of time to allow for an event to be dispatched (measured since its eventTime) 82 // before considering it stale and dropping it. 83 constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec 84 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. 89 constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec 90 91 // Log a warning when an event takes longer than this to process, even if an ANR does not occur. 92 constexpr 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. 95 constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms; 96 97 // Number of recent events to keep for debugging purposes. 98 constexpr size_t RECENT_QUEUE_MAX_SIZE = 10; 99 100 // Sequence number for synthesized or injected events. 101 constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0; 102 103 104 static inline nsecs_t now() { 105 return systemTime(SYSTEM_TIME_MONOTONIC); 106 } 107 108 static inline const char* toString(bool value) { 109 return value ? "true" : "false"; 110 } 111 112 static 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 129 static 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 142 static std::string dispatchModeToString(int32_t dispatchMode) { 143 switch (dispatchMode) { 144 case InputTarget::FLAG_DISPATCH_AS_IS: 145 return "DISPATCH_AS_IS"; 146 case InputTarget::FLAG_DISPATCH_AS_OUTSIDE: 147 return "DISPATCH_AS_OUTSIDE"; 148 case InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER: 149 return "DISPATCH_AS_HOVER_ENTER"; 150 case InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT: 151 return "DISPATCH_AS_HOVER_EXIT"; 152 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT: 153 return "DISPATCH_AS_SLIPPERY_EXIT"; 154 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER: 155 return "DISPATCH_AS_SLIPPERY_ENTER"; 156 } 157 return StringPrintf("%" PRId32, dispatchMode); 158 } 159 160 static inline int32_t getMotionEventActionPointerIndex(int32_t action) { 161 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) 162 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; 163 } 164 165 static bool isValidKeyAction(int32_t action) { 166 switch (action) { 167 case AKEY_EVENT_ACTION_DOWN: 168 case AKEY_EVENT_ACTION_UP: 169 return true; 170 default: 171 return false; 172 } 173 } 174 175 static bool validateKeyEvent(int32_t action) { 176 if (! isValidKeyAction(action)) { 177 ALOGE("Key event has invalid action code 0x%x", action); 178 return false; 179 } 180 return true; 181 } 182 183 static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) { 184 switch (action & AMOTION_EVENT_ACTION_MASK) { 185 case AMOTION_EVENT_ACTION_DOWN: 186 case AMOTION_EVENT_ACTION_UP: 187 case AMOTION_EVENT_ACTION_CANCEL: 188 case AMOTION_EVENT_ACTION_MOVE: 189 case AMOTION_EVENT_ACTION_OUTSIDE: 190 case AMOTION_EVENT_ACTION_HOVER_ENTER: 191 case AMOTION_EVENT_ACTION_HOVER_MOVE: 192 case AMOTION_EVENT_ACTION_HOVER_EXIT: 193 case AMOTION_EVENT_ACTION_SCROLL: 194 return true; 195 case AMOTION_EVENT_ACTION_POINTER_DOWN: 196 case AMOTION_EVENT_ACTION_POINTER_UP: { 197 int32_t index = getMotionEventActionPointerIndex(action); 198 return index >= 0 && index < pointerCount; 199 } 200 case AMOTION_EVENT_ACTION_BUTTON_PRESS: 201 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: 202 return actionButton != 0; 203 default: 204 return false; 205 } 206 } 207 208 static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount, 209 const PointerProperties* pointerProperties) { 210 if (! isValidMotionAction(action, actionButton, pointerCount)) { 211 ALOGE("Motion event has invalid action code 0x%x", action); 212 return false; 213 } 214 if (pointerCount < 1 || pointerCount > MAX_POINTERS) { 215 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.", 216 pointerCount, MAX_POINTERS); 217 return false; 218 } 219 BitSet32 pointerIdBits; 220 for (size_t i = 0; i < pointerCount; i++) { 221 int32_t id = pointerProperties[i].id; 222 if (id < 0 || id > MAX_POINTER_ID) { 223 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", 224 id, MAX_POINTER_ID); 225 return false; 226 } 227 if (pointerIdBits.hasBit(id)) { 228 ALOGE("Motion event has duplicate pointer id %d", id); 229 return false; 230 } 231 pointerIdBits.markBit(id); 232 } 233 return true; 234 } 235 236 static void dumpRegion(std::string& dump, const Region& region) { 237 if (region.isEmpty()) { 238 dump += "<empty>"; 239 return; 240 } 241 242 bool first = true; 243 Region::const_iterator cur = region.begin(); 244 Region::const_iterator const tail = region.end(); 245 while (cur != tail) { 246 if (first) { 247 first = false; 248 } else { 249 dump += "|"; 250 } 251 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom); 252 cur++; 253 } 254 } 255 256 template<typename T, typename U> 257 static T getValueByKey(std::unordered_map<U, T>& map, U key) { 258 typename std::unordered_map<U, T>::const_iterator it = map.find(key); 259 return it != map.end() ? it->second : T{}; 260 } 261 262 263 // --- InputDispatcher --- 264 265 InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) : 266 mPolicy(policy), 267 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED), 268 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX), 269 mNextUnblockedEvent(nullptr), 270 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false), 271 mFocusedDisplayId(ADISPLAY_ID_DEFAULT), 272 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) { 273 mLooper = new Looper(false); 274 mReporter = createInputReporter(); 275 276 mKeyRepeatState.lastKeyEntry = nullptr; 277 278 policy->getDispatcherConfiguration(&mConfig); 279 } 280 281 InputDispatcher::~InputDispatcher() { 282 { // acquire lock 283 std::scoped_lock _l(mLock); 284 285 resetKeyRepeatLocked(); 286 releasePendingEventLocked(); 287 drainInboundQueueLocked(); 288 } 289 290 while (mConnectionsByFd.size() != 0) { 291 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel); 292 } 293 } 294 295 void InputDispatcher::dispatchOnce() { 296 nsecs_t nextWakeupTime = LONG_LONG_MAX; 297 { // acquire lock 298 std::scoped_lock _l(mLock); 299 mDispatcherIsAlive.notify_all(); 300 301 // Run a dispatch loop if there are no pending commands. 302 // The dispatch loop might enqueue commands to run afterwards. 303 if (!haveCommandsLocked()) { 304 dispatchOnceInnerLocked(&nextWakeupTime); 305 } 306 307 // Run all pending commands if there are any. 308 // If any commands were run then force the next poll to wake up immediately. 309 if (runCommandsLockedInterruptible()) { 310 nextWakeupTime = LONG_LONG_MIN; 311 } 312 } // release lock 313 314 // Wait for callback or timeout or wake. (make sure we round up, not down) 315 nsecs_t currentTime = now(); 316 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime); 317 mLooper->pollOnce(timeoutMillis); 318 } 319 320 void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) { 321 nsecs_t currentTime = now(); 322 323 // Reset the key repeat timer whenever normal dispatch is suspended while the 324 // device is in a non-interactive state. This is to ensure that we abort a key 325 // repeat if the device is just coming out of sleep. 326 if (!mDispatchEnabled) { 327 resetKeyRepeatLocked(); 328 } 329 330 // If dispatching is frozen, do not process timeouts or try to deliver any new events. 331 if (mDispatchFrozen) { 332 #if DEBUG_FOCUS 333 ALOGD("Dispatch frozen. Waiting some more."); 334 #endif 335 return; 336 } 337 338 // Optimize latency of app switches. 339 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has 340 // been pressed. When it expires, we preempt dispatch and drop all other pending events. 341 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime; 342 if (mAppSwitchDueTime < *nextWakeupTime) { 343 *nextWakeupTime = mAppSwitchDueTime; 344 } 345 346 // Ready to start a new event. 347 // If we don't already have a pending event, go grab one. 348 if (! mPendingEvent) { 349 if (mInboundQueue.isEmpty()) { 350 if (isAppSwitchDue) { 351 // The inbound queue is empty so the app switch key we were waiting 352 // for will never arrive. Stop waiting for it. 353 resetPendingAppSwitchLocked(false); 354 isAppSwitchDue = false; 355 } 356 357 // Synthesize a key repeat if appropriate. 358 if (mKeyRepeatState.lastKeyEntry) { 359 if (currentTime >= mKeyRepeatState.nextRepeatTime) { 360 mPendingEvent = synthesizeKeyRepeatLocked(currentTime); 361 } else { 362 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) { 363 *nextWakeupTime = mKeyRepeatState.nextRepeatTime; 364 } 365 } 366 } 367 368 // Nothing to do if there is no pending event. 369 if (!mPendingEvent) { 370 return; 371 } 372 } else { 373 // Inbound queue has at least one entry. 374 mPendingEvent = mInboundQueue.dequeueAtHead(); 375 traceInboundQueueLengthLocked(); 376 } 377 378 // Poke user activity for this event. 379 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) { 380 pokeUserActivityLocked(mPendingEvent); 381 } 382 383 // Get ready to dispatch the event. 384 resetANRTimeoutsLocked(); 385 } 386 387 // Now we have an event to dispatch. 388 // All events are eventually dequeued and processed this way, even if we intend to drop them. 389 ALOG_ASSERT(mPendingEvent != nullptr); 390 bool done = false; 391 DropReason dropReason = DROP_REASON_NOT_DROPPED; 392 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) { 393 dropReason = DROP_REASON_POLICY; 394 } else if (!mDispatchEnabled) { 395 dropReason = DROP_REASON_DISABLED; 396 } 397 398 if (mNextUnblockedEvent == mPendingEvent) { 399 mNextUnblockedEvent = nullptr; 400 } 401 402 switch (mPendingEvent->type) { 403 case EventEntry::TYPE_CONFIGURATION_CHANGED: { 404 ConfigurationChangedEntry* typedEntry = 405 static_cast<ConfigurationChangedEntry*>(mPendingEvent); 406 done = dispatchConfigurationChangedLocked(currentTime, typedEntry); 407 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped 408 break; 409 } 410 411 case EventEntry::TYPE_DEVICE_RESET: { 412 DeviceResetEntry* typedEntry = 413 static_cast<DeviceResetEntry*>(mPendingEvent); 414 done = dispatchDeviceResetLocked(currentTime, typedEntry); 415 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped 416 break; 417 } 418 419 case EventEntry::TYPE_KEY: { 420 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent); 421 if (isAppSwitchDue) { 422 if (isAppSwitchKeyEvent(typedEntry)) { 423 resetPendingAppSwitchLocked(true); 424 isAppSwitchDue = false; 425 } else if (dropReason == DROP_REASON_NOT_DROPPED) { 426 dropReason = DROP_REASON_APP_SWITCH; 427 } 428 } 429 if (dropReason == DROP_REASON_NOT_DROPPED 430 && isStaleEvent(currentTime, typedEntry)) { 431 dropReason = DROP_REASON_STALE; 432 } 433 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) { 434 dropReason = DROP_REASON_BLOCKED; 435 } 436 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime); 437 break; 438 } 439 440 case EventEntry::TYPE_MOTION: { 441 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent); 442 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) { 443 dropReason = DROP_REASON_APP_SWITCH; 444 } 445 if (dropReason == DROP_REASON_NOT_DROPPED 446 && isStaleEvent(currentTime, typedEntry)) { 447 dropReason = DROP_REASON_STALE; 448 } 449 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) { 450 dropReason = DROP_REASON_BLOCKED; 451 } 452 done = dispatchMotionLocked(currentTime, typedEntry, 453 &dropReason, nextWakeupTime); 454 break; 455 } 456 457 default: 458 ALOG_ASSERT(false); 459 break; 460 } 461 462 if (done) { 463 if (dropReason != DROP_REASON_NOT_DROPPED) { 464 dropInboundEventLocked(mPendingEvent, dropReason); 465 } 466 mLastDropReason = dropReason; 467 468 releasePendingEventLocked(); 469 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately 470 } 471 } 472 473 bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) { 474 bool needWake = mInboundQueue.isEmpty(); 475 mInboundQueue.enqueueAtTail(entry); 476 traceInboundQueueLengthLocked(); 477 478 switch (entry->type) { 479 case EventEntry::TYPE_KEY: { 480 // Optimize app switch latency. 481 // If the application takes too long to catch up then we drop all events preceding 482 // the app switch key. 483 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry); 484 if (isAppSwitchKeyEvent(keyEntry)) { 485 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) { 486 mAppSwitchSawKeyDown = true; 487 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) { 488 if (mAppSwitchSawKeyDown) { 489 #if DEBUG_APP_SWITCH 490 ALOGD("App switch is pending!"); 491 #endif 492 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT; 493 mAppSwitchSawKeyDown = false; 494 needWake = true; 495 } 496 } 497 } 498 break; 499 } 500 501 case EventEntry::TYPE_MOTION: { 502 // Optimize case where the current application is unresponsive and the user 503 // decides to touch a window in a different application. 504 // If the application takes too long to catch up then we drop all events preceding 505 // the touch into the other window. 506 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry); 507 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN 508 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) 509 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY 510 && mInputTargetWaitApplicationToken != nullptr) { 511 int32_t displayId = motionEntry->displayId; 512 int32_t x = int32_t(motionEntry->pointerCoords[0]. 513 getAxisValue(AMOTION_EVENT_AXIS_X)); 514 int32_t y = int32_t(motionEntry->pointerCoords[0]. 515 getAxisValue(AMOTION_EVENT_AXIS_Y)); 516 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y); 517 if (touchedWindowHandle != nullptr 518 && touchedWindowHandle->getApplicationToken() 519 != mInputTargetWaitApplicationToken) { 520 // User touched a different application than the one we are waiting on. 521 // Flag the event, and start pruning the input queue. 522 mNextUnblockedEvent = motionEntry; 523 needWake = true; 524 } 525 } 526 break; 527 } 528 } 529 530 return needWake; 531 } 532 533 void InputDispatcher::addRecentEventLocked(EventEntry* entry) { 534 entry->refCount += 1; 535 mRecentQueue.enqueueAtTail(entry); 536 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) { 537 mRecentQueue.dequeueAtHead()->release(); 538 } 539 } 540 541 sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, 542 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) { 543 // Traverse windows from front to back to find touched window. 544 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId); 545 for (const sp<InputWindowHandle>& windowHandle : windowHandles) { 546 const InputWindowInfo* windowInfo = windowHandle->getInfo(); 547 if (windowInfo->displayId == displayId) { 548 int32_t flags = windowInfo->layoutParamsFlags; 549 550 if (windowInfo->visible) { 551 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) { 552 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE 553 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0; 554 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) { 555 int32_t portalToDisplayId = windowInfo->portalToDisplayId; 556 if (portalToDisplayId != ADISPLAY_ID_NONE 557 && portalToDisplayId != displayId) { 558 if (addPortalWindows) { 559 // For the monitoring channels of the display. 560 mTempTouchState.addPortalWindow(windowHandle); 561 } 562 return findTouchedWindowAtLocked( 563 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows); 564 } 565 // Found window. 566 return windowHandle; 567 } 568 } 569 570 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) { 571 mTempTouchState.addOrUpdateWindow( 572 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0)); 573 } 574 } 575 } 576 } 577 return nullptr; 578 } 579 580 std::vector<InputDispatcher::TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked( 581 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) { 582 std::vector<TouchedMonitor> touchedMonitors; 583 584 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId); 585 addGestureMonitors(monitors, touchedMonitors); 586 for (const sp<InputWindowHandle>& portalWindow : portalWindows) { 587 const InputWindowInfo* windowInfo = portalWindow->getInfo(); 588 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId); 589 addGestureMonitors(monitors, touchedMonitors, 590 -windowInfo->frameLeft, -windowInfo->frameTop); 591 } 592 return touchedMonitors; 593 } 594 595 void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors, 596 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset, float yOffset) { 597 if (monitors.empty()) { 598 return; 599 } 600 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size()); 601 for (const Monitor& monitor : monitors) { 602 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset); 603 } 604 } 605 606 void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) { 607 const char* reason; 608 switch (dropReason) { 609 case DROP_REASON_POLICY: 610 #if DEBUG_INBOUND_EVENT_DETAILS 611 ALOGD("Dropped event because policy consumed it."); 612 #endif 613 reason = "inbound event was dropped because the policy consumed it"; 614 break; 615 case DROP_REASON_DISABLED: 616 if (mLastDropReason != DROP_REASON_DISABLED) { 617 ALOGI("Dropped event because input dispatch is disabled."); 618 } 619 reason = "inbound event was dropped because input dispatch is disabled"; 620 break; 621 case DROP_REASON_APP_SWITCH: 622 ALOGI("Dropped event because of pending overdue app switch."); 623 reason = "inbound event was dropped because of pending overdue app switch"; 624 break; 625 case DROP_REASON_BLOCKED: 626 ALOGI("Dropped event because the current application is not responding and the user " 627 "has started interacting with a different application."); 628 reason = "inbound event was dropped because the current application is not responding " 629 "and the user has started interacting with a different application"; 630 break; 631 case DROP_REASON_STALE: 632 ALOGI("Dropped event because it is stale."); 633 reason = "inbound event was dropped because it is stale"; 634 break; 635 default: 636 ALOG_ASSERT(false); 637 return; 638 } 639 640 switch (entry->type) { 641 case EventEntry::TYPE_KEY: { 642 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason); 643 synthesizeCancelationEventsForAllConnectionsLocked(options); 644 break; 645 } 646 case EventEntry::TYPE_MOTION: { 647 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry); 648 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) { 649 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason); 650 synthesizeCancelationEventsForAllConnectionsLocked(options); 651 } else { 652 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason); 653 synthesizeCancelationEventsForAllConnectionsLocked(options); 654 } 655 break; 656 } 657 } 658 } 659 660 static bool isAppSwitchKeyCode(int32_t keyCode) { 661 return keyCode == AKEYCODE_HOME 662 || keyCode == AKEYCODE_ENDCALL 663 || keyCode == AKEYCODE_APP_SWITCH; 664 } 665 666 bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) { 667 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) 668 && isAppSwitchKeyCode(keyEntry->keyCode) 669 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) 670 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER); 671 } 672 673 bool InputDispatcher::isAppSwitchPendingLocked() { 674 return mAppSwitchDueTime != LONG_LONG_MAX; 675 } 676 677 void InputDispatcher::resetPendingAppSwitchLocked(bool handled) { 678 mAppSwitchDueTime = LONG_LONG_MAX; 679 680 #if DEBUG_APP_SWITCH 681 if (handled) { 682 ALOGD("App switch has arrived."); 683 } else { 684 ALOGD("App switch was abandoned."); 685 } 686 #endif 687 } 688 689 bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) { 690 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT; 691 } 692 693 bool InputDispatcher::haveCommandsLocked() const { 694 return !mCommandQueue.isEmpty(); 695 } 696 697 bool InputDispatcher::runCommandsLockedInterruptible() { 698 if (mCommandQueue.isEmpty()) { 699 return false; 700 } 701 702 do { 703 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead(); 704 705 Command command = commandEntry->command; 706 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible' 707 708 commandEntry->connection.clear(); 709 delete commandEntry; 710 } while (! mCommandQueue.isEmpty()); 711 return true; 712 } 713 714 InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) { 715 CommandEntry* commandEntry = new CommandEntry(command); 716 mCommandQueue.enqueueAtTail(commandEntry); 717 return commandEntry; 718 } 719 720 void InputDispatcher::drainInboundQueueLocked() { 721 while (! mInboundQueue.isEmpty()) { 722 EventEntry* entry = mInboundQueue.dequeueAtHead(); 723 releaseInboundEventLocked(entry); 724 } 725 traceInboundQueueLengthLocked(); 726 } 727 728 void InputDispatcher::releasePendingEventLocked() { 729 if (mPendingEvent) { 730 resetANRTimeoutsLocked(); 731 releaseInboundEventLocked(mPendingEvent); 732 mPendingEvent = nullptr; 733 } 734 } 735 736 void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) { 737 InjectionState* injectionState = entry->injectionState; 738 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) { 739 #if DEBUG_DISPATCH_CYCLE 740 ALOGD("Injected inbound event was dropped."); 741 #endif 742 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED); 743 } 744 if (entry == mNextUnblockedEvent) { 745 mNextUnblockedEvent = nullptr; 746 } 747 addRecentEventLocked(entry); 748 entry->release(); 749 } 750 751 void InputDispatcher::resetKeyRepeatLocked() { 752 if (mKeyRepeatState.lastKeyEntry) { 753 mKeyRepeatState.lastKeyEntry->release(); 754 mKeyRepeatState.lastKeyEntry = nullptr; 755 } 756 } 757 758 InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) { 759 KeyEntry* entry = mKeyRepeatState.lastKeyEntry; 760 761 // Reuse the repeated key entry if it is otherwise unreferenced. 762 uint32_t policyFlags = entry->policyFlags & 763 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED); 764 if (entry->refCount == 1) { 765 entry->recycle(); 766 entry->eventTime = currentTime; 767 entry->policyFlags = policyFlags; 768 entry->repeatCount += 1; 769 } else { 770 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, 771 entry->deviceId, entry->source, entry->displayId, policyFlags, 772 entry->action, entry->flags, entry->keyCode, entry->scanCode, 773 entry->metaState, entry->repeatCount + 1, entry->downTime); 774 775 mKeyRepeatState.lastKeyEntry = newEntry; 776 entry->release(); 777 778 entry = newEntry; 779 } 780 entry->syntheticRepeat = true; 781 782 // Increment reference count since we keep a reference to the event in 783 // mKeyRepeatState.lastKeyEntry in addition to the one we return. 784 entry->refCount += 1; 785 786 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay; 787 return entry; 788 } 789 790 bool InputDispatcher::dispatchConfigurationChangedLocked( 791 nsecs_t currentTime, ConfigurationChangedEntry* entry) { 792 #if DEBUG_OUTBOUND_EVENT_DETAILS 793 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime); 794 #endif 795 796 // Reset key repeating in case a keyboard device was added or removed or something. 797 resetKeyRepeatLocked(); 798 799 // Enqueue a command to run outside the lock to tell the policy that the configuration changed. 800 CommandEntry* commandEntry = postCommandLocked( 801 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible); 802 commandEntry->eventTime = entry->eventTime; 803 return true; 804 } 805 806 bool InputDispatcher::dispatchDeviceResetLocked( 807 nsecs_t currentTime, DeviceResetEntry* entry) { 808 #if DEBUG_OUTBOUND_EVENT_DETAILS 809 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime, 810 entry->deviceId); 811 #endif 812 813 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, 814 "device was reset"); 815 options.deviceId = entry->deviceId; 816 synthesizeCancelationEventsForAllConnectionsLocked(options); 817 return true; 818 } 819 820 bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry, 821 DropReason* dropReason, nsecs_t* nextWakeupTime) { 822 // Preprocessing. 823 if (! entry->dispatchInProgress) { 824 if (entry->repeatCount == 0 825 && entry->action == AKEY_EVENT_ACTION_DOWN 826 && (entry->policyFlags & POLICY_FLAG_TRUSTED) 827 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) { 828 if (mKeyRepeatState.lastKeyEntry 829 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) { 830 // We have seen two identical key downs in a row which indicates that the device 831 // driver is automatically generating key repeats itself. We take note of the 832 // repeat here, but we disable our own next key repeat timer since it is clear that 833 // we will not need to synthesize key repeats ourselves. 834 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1; 835 resetKeyRepeatLocked(); 836 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves 837 } else { 838 // Not a repeat. Save key down state in case we do see a repeat later. 839 resetKeyRepeatLocked(); 840 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout; 841 } 842 mKeyRepeatState.lastKeyEntry = entry; 843 entry->refCount += 1; 844 } else if (! entry->syntheticRepeat) { 845 resetKeyRepeatLocked(); 846 } 847 848 if (entry->repeatCount == 1) { 849 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS; 850 } else { 851 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS; 852 } 853 854 entry->dispatchInProgress = true; 855 856 logOutboundKeyDetails("dispatchKey - ", entry); 857 } 858 859 // Handle case where the policy asked us to try again later last time. 860 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) { 861 if (currentTime < entry->interceptKeyWakeupTime) { 862 if (entry->interceptKeyWakeupTime < *nextWakeupTime) { 863 *nextWakeupTime = entry->interceptKeyWakeupTime; 864 } 865 return false; // wait until next wakeup 866 } 867 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN; 868 entry->interceptKeyWakeupTime = 0; 869 } 870 871 // Give the policy a chance to intercept the key. 872 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) { 873 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) { 874 CommandEntry* commandEntry = postCommandLocked( 875 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible); 876 sp<InputWindowHandle> focusedWindowHandle = 877 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry)); 878 if (focusedWindowHandle != nullptr) { 879 commandEntry->inputChannel = 880 getInputChannelLocked(focusedWindowHandle->getToken()); 881 } 882 commandEntry->keyEntry = entry; 883 entry->refCount += 1; 884 return false; // wait for the command to run 885 } else { 886 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE; 887 } 888 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) { 889 if (*dropReason == DROP_REASON_NOT_DROPPED) { 890 *dropReason = DROP_REASON_POLICY; 891 } 892 } 893 894 // Clean up if dropping the event. 895 if (*dropReason != DROP_REASON_NOT_DROPPED) { 896 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY 897 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED); 898 mReporter->reportDroppedKey(entry->sequenceNum); 899 return true; 900 } 901 902 // Identify targets. 903 std::vector<InputTarget> inputTargets; 904 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime, 905 entry, inputTargets, nextWakeupTime); 906 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) { 907 return false; 908 } 909 910 setInjectionResult(entry, injectionResult); 911 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) { 912 return true; 913 } 914 915 // Add monitor channels from event's or focused display. 916 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry)); 917 918 // Dispatch the key. 919 dispatchEventLocked(currentTime, entry, inputTargets); 920 return true; 921 } 922 923 void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) { 924 #if DEBUG_OUTBOUND_EVENT_DETAILS 925 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", " 926 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, " 927 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64, 928 prefix, 929 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags, 930 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState, 931 entry->repeatCount, entry->downTime); 932 #endif 933 } 934 935 bool InputDispatcher::dispatchMotionLocked( 936 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) { 937 ATRACE_CALL(); 938 // Preprocessing. 939 if (! entry->dispatchInProgress) { 940 entry->dispatchInProgress = true; 941 942 logOutboundMotionDetails("dispatchMotion - ", entry); 943 } 944 945 // Clean up if dropping the event. 946 if (*dropReason != DROP_REASON_NOT_DROPPED) { 947 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY 948 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED); 949 return true; 950 } 951 952 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER; 953 954 // Identify targets. 955 std::vector<InputTarget> inputTargets; 956 957 bool conflictingPointerActions = false; 958 int32_t injectionResult; 959 if (isPointerEvent) { 960 // Pointer event. (eg. touchscreen) 961 injectionResult = findTouchedWindowTargetsLocked(currentTime, 962 entry, inputTargets, nextWakeupTime, &conflictingPointerActions); 963 } else { 964 // Non touch event. (eg. trackball) 965 injectionResult = findFocusedWindowTargetsLocked(currentTime, 966 entry, inputTargets, nextWakeupTime); 967 } 968 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) { 969 return false; 970 } 971 972 setInjectionResult(entry, injectionResult); 973 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) { 974 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) { 975 CancelationOptions::Mode mode(isPointerEvent ? 976 CancelationOptions::CANCEL_POINTER_EVENTS : 977 CancelationOptions::CANCEL_NON_POINTER_EVENTS); 978 CancelationOptions options(mode, "input event injection failed"); 979 synthesizeCancelationEventsForMonitorsLocked(options); 980 } 981 return true; 982 } 983 984 // Add monitor channels from event's or focused display. 985 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry)); 986 987 if (isPointerEvent) { 988 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId); 989 if (stateIndex >= 0) { 990 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex); 991 if (!state.portalWindows.empty()) { 992 // The event has gone through these portal windows, so we add monitoring targets of 993 // the corresponding displays as well. 994 for (size_t i = 0; i < state.portalWindows.size(); i++) { 995 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo(); 996 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId, 997 -windowInfo->frameLeft, -windowInfo->frameTop); 998 } 999 } 1000 } 1001 } 1002 1003 // Dispatch the motion. 1004 if (conflictingPointerActions) { 1005 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, 1006 "conflicting pointer actions"); 1007 synthesizeCancelationEventsForAllConnectionsLocked(options); 1008 } 1009 dispatchEventLocked(currentTime, entry, inputTargets); 1010 return true; 1011 } 1012 1013 1014 void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) { 1015 #if DEBUG_OUTBOUND_EVENT_DETAILS 1016 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 1017 ", policyFlags=0x%x, " 1018 "action=0x%x, actionButton=0x%x, flags=0x%x, " 1019 "metaState=0x%x, buttonState=0x%x," 1020 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64, 1021 prefix, 1022 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags, 1023 entry->action, entry->actionButton, entry->flags, 1024 entry->metaState, entry->buttonState, 1025 entry->edgeFlags, entry->xPrecision, entry->yPrecision, 1026 entry->downTime); 1027 1028 for (uint32_t i = 0; i < entry->pointerCount; i++) { 1029 ALOGD(" Pointer %d: id=%d, toolType=%d, " 1030 "x=%f, y=%f, pressure=%f, size=%f, " 1031 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, " 1032 "orientation=%f", 1033 i, entry->pointerProperties[i].id, 1034 entry->pointerProperties[i].toolType, 1035 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X), 1036 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y), 1037 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), 1038 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE), 1039 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), 1040 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), 1041 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), 1042 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), 1043 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION)); 1044 } 1045 #endif 1046 } 1047 1048 void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, 1049 EventEntry* eventEntry, const std::vector<InputTarget>& inputTargets) { 1050 ATRACE_CALL(); 1051 #if DEBUG_DISPATCH_CYCLE 1052 ALOGD("dispatchEventToCurrentInputTargets"); 1053 #endif 1054 1055 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true 1056 1057 pokeUserActivityLocked(eventEntry); 1058 1059 for (const InputTarget& inputTarget : inputTargets) { 1060 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel); 1061 if (connectionIndex >= 0) { 1062 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex); 1063 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget); 1064 } else { 1065 #if DEBUG_FOCUS 1066 ALOGD("Dropping event delivery to target with channel '%s' because it " 1067 "is no longer registered with the input dispatcher.", 1068 inputTarget.inputChannel->getName().c_str()); 1069 #endif 1070 } 1071 } 1072 } 1073 1074 int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime, 1075 const EventEntry* entry, 1076 const sp<InputApplicationHandle>& applicationHandle, 1077 const sp<InputWindowHandle>& windowHandle, 1078 nsecs_t* nextWakeupTime, const char* reason) { 1079 if (applicationHandle == nullptr && windowHandle == nullptr) { 1080 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) { 1081 #if DEBUG_FOCUS 1082 ALOGD("Waiting for system to become ready for input. Reason: %s", reason); 1083 #endif 1084 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY; 1085 mInputTargetWaitStartTime = currentTime; 1086 mInputTargetWaitTimeoutTime = LONG_LONG_MAX; 1087 mInputTargetWaitTimeoutExpired = false; 1088 mInputTargetWaitApplicationToken.clear(); 1089 } 1090 } else { 1091 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) { 1092 #if DEBUG_FOCUS 1093 ALOGD("Waiting for application to become ready for input: %s. Reason: %s", 1094 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), 1095 reason); 1096 #endif 1097 nsecs_t timeout; 1098 if (windowHandle != nullptr) { 1099 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT); 1100 } else if (applicationHandle != nullptr) { 1101 timeout = applicationHandle->getDispatchingTimeout( 1102 DEFAULT_INPUT_DISPATCHING_TIMEOUT); 1103 } else { 1104 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT; 1105 } 1106 1107 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY; 1108 mInputTargetWaitStartTime = currentTime; 1109 mInputTargetWaitTimeoutTime = currentTime + timeout; 1110 mInputTargetWaitTimeoutExpired = false; 1111 mInputTargetWaitApplicationToken.clear(); 1112 1113 if (windowHandle != nullptr) { 1114 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken(); 1115 } 1116 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) { 1117 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken(); 1118 } 1119 } 1120 } 1121 1122 if (mInputTargetWaitTimeoutExpired) { 1123 return INPUT_EVENT_INJECTION_TIMED_OUT; 1124 } 1125 1126 if (currentTime >= mInputTargetWaitTimeoutTime) { 1127 onANRLocked(currentTime, applicationHandle, windowHandle, 1128 entry->eventTime, mInputTargetWaitStartTime, reason); 1129 1130 // Force poll loop to wake up immediately on next iteration once we get the 1131 // ANR response back from the policy. 1132 *nextWakeupTime = LONG_LONG_MIN; 1133 return INPUT_EVENT_INJECTION_PENDING; 1134 } else { 1135 // Force poll loop to wake up when timeout is due. 1136 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) { 1137 *nextWakeupTime = mInputTargetWaitTimeoutTime; 1138 } 1139 return INPUT_EVENT_INJECTION_PENDING; 1140 } 1141 } 1142 1143 void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) { 1144 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) { 1145 TouchState& state = mTouchStatesByDisplay.editValueAt(d); 1146 state.removeWindowByToken(token); 1147 } 1148 } 1149 1150 void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout, 1151 const sp<InputChannel>& inputChannel) { 1152 if (newTimeout > 0) { 1153 // Extend the timeout. 1154 mInputTargetWaitTimeoutTime = now() + newTimeout; 1155 } else { 1156 // Give up. 1157 mInputTargetWaitTimeoutExpired = true; 1158 1159 // Input state will not be realistic. Mark it out of sync. 1160 if (inputChannel.get()) { 1161 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel); 1162 if (connectionIndex >= 0) { 1163 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex); 1164 sp<IBinder> token = connection->inputChannel->getToken(); 1165 1166 if (token != nullptr) { 1167 removeWindowByTokenLocked(token); 1168 } 1169 1170 if (connection->status == Connection::STATUS_NORMAL) { 1171 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, 1172 "application not responding"); 1173 synthesizeCancelationEventsForConnectionLocked(connection, options); 1174 } 1175 } 1176 } 1177 } 1178 } 1179 1180 nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked( 1181 nsecs_t currentTime) { 1182 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) { 1183 return currentTime - mInputTargetWaitStartTime; 1184 } 1185 return 0; 1186 } 1187 1188 void InputDispatcher::resetANRTimeoutsLocked() { 1189 #if DEBUG_FOCUS 1190 ALOGD("Resetting ANR timeouts."); 1191 #endif 1192 1193 // Reset input target wait timeout. 1194 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE; 1195 mInputTargetWaitApplicationToken.clear(); 1196 } 1197 1198 /** 1199 * Get the display id that the given event should go to. If this event specifies a valid display id, 1200 * then it should be dispatched to that display. Otherwise, the event goes to the focused display. 1201 * Focused display is the display that the user most recently interacted with. 1202 */ 1203 int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) { 1204 int32_t displayId; 1205 switch (entry->type) { 1206 case EventEntry::TYPE_KEY: { 1207 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry); 1208 displayId = typedEntry->displayId; 1209 break; 1210 } 1211 case EventEntry::TYPE_MOTION: { 1212 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry); 1213 displayId = typedEntry->displayId; 1214 break; 1215 } 1216 default: { 1217 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type); 1218 return ADISPLAY_ID_NONE; 1219 } 1220 } 1221 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId; 1222 } 1223 1224 int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime, 1225 const EventEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) { 1226 int32_t injectionResult; 1227 std::string reason; 1228 1229 int32_t displayId = getTargetDisplayId(entry); 1230 sp<InputWindowHandle> focusedWindowHandle = 1231 getValueByKey(mFocusedWindowHandlesByDisplay, displayId); 1232 sp<InputApplicationHandle> focusedApplicationHandle = 1233 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId); 1234 1235 // If there is no currently focused window and no focused application 1236 // then drop the event. 1237 if (focusedWindowHandle == nullptr) { 1238 if (focusedApplicationHandle != nullptr) { 1239 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, 1240 focusedApplicationHandle, nullptr, nextWakeupTime, 1241 "Waiting because no window has focus but there is a " 1242 "focused application that may eventually add a window " 1243 "when it finishes starting up."); 1244 goto Unresponsive; 1245 } 1246 1247 ALOGI("Dropping event because there is no focused window or focused application in display " 1248 "%" PRId32 ".", displayId); 1249 injectionResult = INPUT_EVENT_INJECTION_FAILED; 1250 goto Failed; 1251 } 1252 1253 // Check permissions. 1254 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) { 1255 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; 1256 goto Failed; 1257 } 1258 1259 // Check whether the window is ready for more input. 1260 reason = checkWindowReadyForMoreInputLocked(currentTime, 1261 focusedWindowHandle, entry, "focused"); 1262 if (!reason.empty()) { 1263 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, 1264 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str()); 1265 goto Unresponsive; 1266 } 1267 1268 // Success! Output targets. 1269 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; 1270 addWindowTargetLocked(focusedWindowHandle, 1271 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0), 1272 inputTargets); 1273 1274 // Done. 1275 Failed: 1276 Unresponsive: 1277 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime); 1278 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication); 1279 #if DEBUG_FOCUS 1280 ALOGD("findFocusedWindow finished: injectionResult=%d, " 1281 "timeSpentWaitingForApplication=%0.1fms", 1282 injectionResult, timeSpentWaitingForApplication / 1000000.0); 1283 #endif 1284 return injectionResult; 1285 } 1286 1287 int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, 1288 const MotionEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime, 1289 bool* outConflictingPointerActions) { 1290 ATRACE_CALL(); 1291 enum InjectionPermission { 1292 INJECTION_PERMISSION_UNKNOWN, 1293 INJECTION_PERMISSION_GRANTED, 1294 INJECTION_PERMISSION_DENIED 1295 }; 1296 1297 // For security reasons, we defer updating the touch state until we are sure that 1298 // event injection will be allowed. 1299 int32_t displayId = entry->displayId; 1300 int32_t action = entry->action; 1301 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; 1302 1303 // Update the touch state as needed based on the properties of the touch event. 1304 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING; 1305 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN; 1306 sp<InputWindowHandle> newHoverWindowHandle; 1307 1308 // Copy current touch state into mTempTouchState. 1309 // This state is always reset at the end of this function, so if we don't find state 1310 // for the specified display then our initial state will be empty. 1311 const TouchState* oldState = nullptr; 1312 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId); 1313 if (oldStateIndex >= 0) { 1314 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex); 1315 mTempTouchState.copyFrom(*oldState); 1316 } 1317 1318 bool isSplit = mTempTouchState.split; 1319 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 1320 && (mTempTouchState.deviceId != entry->deviceId 1321 || mTempTouchState.source != entry->source 1322 || mTempTouchState.displayId != displayId); 1323 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE 1324 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER 1325 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT); 1326 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN 1327 || maskedAction == AMOTION_EVENT_ACTION_SCROLL 1328 || isHoverAction); 1329 bool wrongDevice = false; 1330 if (newGesture) { 1331 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN; 1332 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) { 1333 #if DEBUG_FOCUS 1334 ALOGD("Dropping event because a pointer for a different device is already down " 1335 "in display %" PRId32, displayId); 1336 #endif 1337 // TODO: test multiple simultaneous input streams. 1338 injectionResult = INPUT_EVENT_INJECTION_FAILED; 1339 switchedDevice = false; 1340 wrongDevice = true; 1341 goto Failed; 1342 } 1343 mTempTouchState.reset(); 1344 mTempTouchState.down = down; 1345 mTempTouchState.deviceId = entry->deviceId; 1346 mTempTouchState.source = entry->source; 1347 mTempTouchState.displayId = displayId; 1348 isSplit = false; 1349 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) { 1350 #if DEBUG_FOCUS 1351 ALOGI("Dropping move event because a pointer for a different device is already active " 1352 "in display %" PRId32, displayId); 1353 #endif 1354 // TODO: test multiple simultaneous input streams. 1355 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; 1356 switchedDevice = false; 1357 wrongDevice = true; 1358 goto Failed; 1359 } 1360 1361 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) { 1362 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */ 1363 1364 int32_t pointerIndex = getMotionEventActionPointerIndex(action); 1365 int32_t x = int32_t(entry->pointerCoords[pointerIndex]. 1366 getAxisValue(AMOTION_EVENT_AXIS_X)); 1367 int32_t y = int32_t(entry->pointerCoords[pointerIndex]. 1368 getAxisValue(AMOTION_EVENT_AXIS_Y)); 1369 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN; 1370 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked( 1371 displayId, x, y, isDown /*addOutsideTargets*/, true /*addPortalWindows*/); 1372 1373 std::vector<TouchedMonitor> newGestureMonitors = isDown 1374 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows) 1375 : std::vector<TouchedMonitor>{}; 1376 1377 // Figure out whether splitting will be allowed for this window. 1378 if (newTouchedWindowHandle != nullptr 1379 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { 1380 // New window supports splitting. 1381 isSplit = true; 1382 } else if (isSplit) { 1383 // New window does not support splitting but we have already split events. 1384 // Ignore the new window. 1385 newTouchedWindowHandle = nullptr; 1386 } 1387 1388 // Handle the case where we did not find a window. 1389 if (newTouchedWindowHandle == nullptr) { 1390 // Try to assign the pointer to the first foreground window we find, if there is one. 1391 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); 1392 } 1393 1394 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) { 1395 ALOGI("Dropping event because there is no touchable window or gesture monitor at " 1396 "(%d, %d) in display %" PRId32 ".", x, y, displayId); 1397 injectionResult = INPUT_EVENT_INJECTION_FAILED; 1398 goto Failed; 1399 } 1400 1401 if (newTouchedWindowHandle != nullptr) { 1402 // Set target flags. 1403 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS; 1404 if (isSplit) { 1405 targetFlags |= InputTarget::FLAG_SPLIT; 1406 } 1407 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { 1408 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; 1409 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) { 1410 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED; 1411 } 1412 1413 // Update hover state. 1414 if (isHoverAction) { 1415 newHoverWindowHandle = newTouchedWindowHandle; 1416 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) { 1417 newHoverWindowHandle = mLastHoverWindowHandle; 1418 } 1419 1420 // Update the temporary touch state. 1421 BitSet32 pointerIds; 1422 if (isSplit) { 1423 uint32_t pointerId = entry->pointerProperties[pointerIndex].id; 1424 pointerIds.markBit(pointerId); 1425 } 1426 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); 1427 } 1428 1429 mTempTouchState.addGestureMonitors(newGestureMonitors); 1430 } else { 1431 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */ 1432 1433 // If the pointer is not currently down, then ignore the event. 1434 if (! mTempTouchState.down) { 1435 #if DEBUG_FOCUS 1436 ALOGD("Dropping event because the pointer is not down or we previously " 1437 "dropped the pointer down event in display %" PRId32, displayId); 1438 #endif 1439 injectionResult = INPUT_EVENT_INJECTION_FAILED; 1440 goto Failed; 1441 } 1442 1443 // Check whether touches should slip outside of the current foreground window. 1444 if (maskedAction == AMOTION_EVENT_ACTION_MOVE 1445 && entry->pointerCount == 1 1446 && mTempTouchState.isSlippery()) { 1447 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X)); 1448 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y)); 1449 1450 sp<InputWindowHandle> oldTouchedWindowHandle = 1451 mTempTouchState.getFirstForegroundWindowHandle(); 1452 sp<InputWindowHandle> newTouchedWindowHandle = 1453 findTouchedWindowAtLocked(displayId, x, y); 1454 if (oldTouchedWindowHandle != newTouchedWindowHandle 1455 && oldTouchedWindowHandle != nullptr 1456 && newTouchedWindowHandle != nullptr) { 1457 #if DEBUG_FOCUS 1458 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32, 1459 oldTouchedWindowHandle->getName().c_str(), 1460 newTouchedWindowHandle->getName().c_str(), 1461 displayId); 1462 #endif 1463 // Make a slippery exit from the old window. 1464 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle, 1465 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0)); 1466 1467 // Make a slippery entrance into the new window. 1468 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { 1469 isSplit = true; 1470 } 1471 1472 int32_t targetFlags = InputTarget::FLAG_FOREGROUND 1473 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER; 1474 if (isSplit) { 1475 targetFlags |= InputTarget::FLAG_SPLIT; 1476 } 1477 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { 1478 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; 1479 } 1480 1481 BitSet32 pointerIds; 1482 if (isSplit) { 1483 pointerIds.markBit(entry->pointerProperties[0].id); 1484 } 1485 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); 1486 } 1487 } 1488 } 1489 1490 if (newHoverWindowHandle != mLastHoverWindowHandle) { 1491 // Let the previous window know that the hover sequence is over. 1492 if (mLastHoverWindowHandle != nullptr) { 1493 #if DEBUG_HOVER 1494 ALOGD("Sending hover exit event to window %s.", 1495 mLastHoverWindowHandle->getName().c_str()); 1496 #endif 1497 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle, 1498 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0)); 1499 } 1500 1501 // Let the new window know that the hover sequence is starting. 1502 if (newHoverWindowHandle != nullptr) { 1503 #if DEBUG_HOVER 1504 ALOGD("Sending hover enter event to window %s.", 1505 newHoverWindowHandle->getName().c_str()); 1506 #endif 1507 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle, 1508 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0)); 1509 } 1510 } 1511 1512 // Check permission to inject into all touched foreground windows and ensure there 1513 // is at least one touched foreground window. 1514 { 1515 bool haveForegroundWindow = false; 1516 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { 1517 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { 1518 haveForegroundWindow = true; 1519 if (! checkInjectionPermission(touchedWindow.windowHandle, 1520 entry->injectionState)) { 1521 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; 1522 injectionPermission = INJECTION_PERMISSION_DENIED; 1523 goto Failed; 1524 } 1525 } 1526 } 1527 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty(); 1528 if (!haveForegroundWindow && !hasGestureMonitor) { 1529 #if DEBUG_FOCUS 1530 ALOGD("Dropping event because there is no touched foreground window in display %" 1531 PRId32 " or gesture monitor to receive it.", displayId); 1532 #endif 1533 injectionResult = INPUT_EVENT_INJECTION_FAILED; 1534 goto Failed; 1535 } 1536 1537 // Permission granted to injection into all touched foreground windows. 1538 injectionPermission = INJECTION_PERMISSION_GRANTED; 1539 } 1540 1541 // Check whether windows listening for outside touches are owned by the same UID. If it is 1542 // set the policy flag that we will not reveal coordinate information to this window. 1543 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { 1544 sp<InputWindowHandle> foregroundWindowHandle = 1545 mTempTouchState.getFirstForegroundWindowHandle(); 1546 if (foregroundWindowHandle) { 1547 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid; 1548 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { 1549 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { 1550 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle; 1551 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) { 1552 mTempTouchState.addOrUpdateWindow(inputWindowHandle, 1553 InputTarget::FLAG_ZERO_COORDS, BitSet32(0)); 1554 } 1555 } 1556 } 1557 } 1558 } 1559 1560 // Ensure all touched foreground windows are ready for new input. 1561 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { 1562 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { 1563 // Check whether the window is ready for more input. 1564 std::string reason = checkWindowReadyForMoreInputLocked(currentTime, 1565 touchedWindow.windowHandle, entry, "touched"); 1566 if (!reason.empty()) { 1567 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, 1568 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str()); 1569 goto Unresponsive; 1570 } 1571 } 1572 } 1573 1574 // If this is the first pointer going down and the touched window has a wallpaper 1575 // then also add the touched wallpaper windows so they are locked in for the duration 1576 // of the touch gesture. 1577 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper 1578 // engine only supports touch events. We would need to add a mechanism similar 1579 // to View.onGenericMotionEvent to enable wallpapers to handle these events. 1580 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { 1581 sp<InputWindowHandle> foregroundWindowHandle = 1582 mTempTouchState.getFirstForegroundWindowHandle(); 1583 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) { 1584 const std::vector<sp<InputWindowHandle>> windowHandles = 1585 getWindowHandlesLocked(displayId); 1586 for (const sp<InputWindowHandle>& windowHandle : windowHandles) { 1587 const InputWindowInfo* info = windowHandle->getInfo(); 1588 if (info->displayId == displayId 1589 && windowHandle->getInfo()->layoutParamsType 1590 == InputWindowInfo::TYPE_WALLPAPER) { 1591 mTempTouchState.addOrUpdateWindow(windowHandle, 1592 InputTarget::FLAG_WINDOW_IS_OBSCURED 1593 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED 1594 | InputTarget::FLAG_DISPATCH_AS_IS, 1595 BitSet32(0)); 1596 } 1597 } 1598 } 1599 } 1600 1601 // Success! Output targets. 1602 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; 1603 1604 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { 1605 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags, 1606 touchedWindow.pointerIds, inputTargets); 1607 } 1608 1609 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) { 1610 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset, 1611 touchedMonitor.yOffset, inputTargets); 1612 } 1613 1614 // Drop the outside or hover touch windows since we will not care about them 1615 // in the next iteration. 1616 mTempTouchState.filterNonAsIsTouchWindows(); 1617 1618 Failed: 1619 // Check injection permission once and for all. 1620 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) { 1621 if (checkInjectionPermission(nullptr, entry->injectionState)) { 1622 injectionPermission = INJECTION_PERMISSION_GRANTED; 1623 } else { 1624 injectionPermission = INJECTION_PERMISSION_DENIED; 1625 } 1626 } 1627 1628 // Update final pieces of touch state if the injector had permission. 1629 if (injectionPermission == INJECTION_PERMISSION_GRANTED) { 1630 if (!wrongDevice) { 1631 if (switchedDevice) { 1632 #if DEBUG_FOCUS 1633 ALOGD("Conflicting pointer actions: Switched to a different device."); 1634 #endif 1635 *outConflictingPointerActions = true; 1636 } 1637 1638 if (isHoverAction) { 1639 // Started hovering, therefore no longer down. 1640 if (oldState && oldState->down) { 1641 #if DEBUG_FOCUS 1642 ALOGD("Conflicting pointer actions: Hover received while pointer was down."); 1643 #endif 1644 *outConflictingPointerActions = true; 1645 } 1646 mTempTouchState.reset(); 1647 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER 1648 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) { 1649 mTempTouchState.deviceId = entry->deviceId; 1650 mTempTouchState.source = entry->source; 1651 mTempTouchState.displayId = displayId; 1652 } 1653 } else if (maskedAction == AMOTION_EVENT_ACTION_UP 1654 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) { 1655 // All pointers up or canceled. 1656 mTempTouchState.reset(); 1657 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { 1658 // First pointer went down. 1659 if (oldState && oldState->down) { 1660 #if DEBUG_FOCUS 1661 ALOGD("Conflicting pointer actions: Down received while already down."); 1662 #endif 1663 *outConflictingPointerActions = true; 1664 } 1665 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) { 1666 // One pointer went up. 1667 if (isSplit) { 1668 int32_t pointerIndex = getMotionEventActionPointerIndex(action); 1669 uint32_t pointerId = entry->pointerProperties[pointerIndex].id; 1670 1671 for (size_t i = 0; i < mTempTouchState.windows.size(); ) { 1672 TouchedWindow& touchedWindow = mTempTouchState.windows[i]; 1673 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) { 1674 touchedWindow.pointerIds.clearBit(pointerId); 1675 if (touchedWindow.pointerIds.isEmpty()) { 1676 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i); 1677 continue; 1678 } 1679 } 1680 i += 1; 1681 } 1682 } 1683 } 1684 1685 // Save changes unless the action was scroll in which case the temporary touch 1686 // state was only valid for this one action. 1687 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) { 1688 if (mTempTouchState.displayId >= 0) { 1689 if (oldStateIndex >= 0) { 1690 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState); 1691 } else { 1692 mTouchStatesByDisplay.add(displayId, mTempTouchState); 1693 } 1694 } else if (oldStateIndex >= 0) { 1695 mTouchStatesByDisplay.removeItemsAt(oldStateIndex); 1696 } 1697 } 1698 1699 // Update hover state. 1700 mLastHoverWindowHandle = newHoverWindowHandle; 1701 } 1702 } else { 1703 #if DEBUG_FOCUS 1704 ALOGD("Not updating touch focus because injection was denied."); 1705 #endif 1706 } 1707 1708 Unresponsive: 1709 // Reset temporary touch state to ensure we release unnecessary references to input channels. 1710 mTempTouchState.reset(); 1711 1712 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime); 1713 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication); 1714 #if DEBUG_FOCUS 1715 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, " 1716 "timeSpentWaitingForApplication=%0.1fms", 1717 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0); 1718 #endif 1719 return injectionResult; 1720 } 1721 1722 void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle, 1723 int32_t targetFlags, BitSet32 pointerIds, std::vector<InputTarget>& inputTargets) { 1724 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken()); 1725 if (inputChannel == nullptr) { 1726 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str()); 1727 return; 1728 } 1729 1730 const InputWindowInfo* windowInfo = windowHandle->getInfo(); 1731 InputTarget target; 1732 target.inputChannel = inputChannel; 1733 target.flags = targetFlags; 1734 target.xOffset = - windowInfo->frameLeft; 1735 target.yOffset = - windowInfo->frameTop; 1736 target.globalScaleFactor = windowInfo->globalScaleFactor; 1737 target.windowXScale = windowInfo->windowXScale; 1738 target.windowYScale = windowInfo->windowYScale; 1739 target.pointerIds = pointerIds; 1740 inputTargets.push_back(target); 1741 } 1742 1743 void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets, 1744 int32_t displayId, float xOffset, float yOffset) { 1745 1746 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it = 1747 mGlobalMonitorsByDisplay.find(displayId); 1748 1749 if (it != mGlobalMonitorsByDisplay.end()) { 1750 const std::vector<Monitor>& monitors = it->second; 1751 for (const Monitor& monitor : monitors) { 1752 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets); 1753 } 1754 } 1755 } 1756 1757 void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, 1758 float xOffset, float yOffset, std::vector<InputTarget>& inputTargets) { 1759 InputTarget target; 1760 target.inputChannel = monitor.inputChannel; 1761 target.flags = InputTarget::FLAG_DISPATCH_AS_IS; 1762 target.xOffset = xOffset; 1763 target.yOffset = yOffset; 1764 target.pointerIds.clear(); 1765 target.globalScaleFactor = 1.0f; 1766 inputTargets.push_back(target); 1767 } 1768 1769 bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle, 1770 const InjectionState* injectionState) { 1771 if (injectionState 1772 && (windowHandle == nullptr 1773 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid) 1774 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) { 1775 if (windowHandle != nullptr) { 1776 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s " 1777 "owned by uid %d", 1778 injectionState->injectorPid, injectionState->injectorUid, 1779 windowHandle->getName().c_str(), 1780 windowHandle->getInfo()->ownerUid); 1781 } else { 1782 ALOGW("Permission denied: injecting event from pid %d uid %d", 1783 injectionState->injectorPid, injectionState->injectorUid); 1784 } 1785 return false; 1786 } 1787 return true; 1788 } 1789 1790 bool InputDispatcher::isWindowObscuredAtPointLocked( 1791 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const { 1792 int32_t displayId = windowHandle->getInfo()->displayId; 1793 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId); 1794 for (const sp<InputWindowHandle>& otherHandle : windowHandles) { 1795 if (otherHandle == windowHandle) { 1796 break; 1797 } 1798 1799 const InputWindowInfo* otherInfo = otherHandle->getInfo(); 1800 if (otherInfo->displayId == displayId 1801 && otherInfo->visible && !otherInfo->isTrustedOverlay() 1802 && otherInfo->frameContainsPoint(x, y)) { 1803 return true; 1804 } 1805 } 1806 return false; 1807 } 1808 1809 1810 bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const { 1811 int32_t displayId = windowHandle->getInfo()->displayId; 1812 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId); 1813 const InputWindowInfo* windowInfo = windowHandle->getInfo(); 1814 for (const sp<InputWindowHandle>& otherHandle : windowHandles) { 1815 if (otherHandle == windowHandle) { 1816 break; 1817 } 1818 1819 const InputWindowInfo* otherInfo = otherHandle->getInfo(); 1820 if (otherInfo->displayId == displayId 1821 && otherInfo->visible && !otherInfo->isTrustedOverlay() 1822 && otherInfo->overlaps(windowInfo)) { 1823 return true; 1824 } 1825 } 1826 return false; 1827 } 1828 1829 std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime, 1830 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry, 1831 const char* targetType) { 1832 // If the window is paused then keep waiting. 1833 if (windowHandle->getInfo()->paused) { 1834 return StringPrintf("Waiting because the %s window is paused.", targetType); 1835 } 1836 1837 // If the window's connection is not registered then keep waiting. 1838 ssize_t connectionIndex = getConnectionIndexLocked( 1839 getInputChannelLocked(windowHandle->getToken())); 1840 if (connectionIndex < 0) { 1841 return StringPrintf("Waiting because the %s window's input channel is not " 1842 "registered with the input dispatcher. The window may be in the process " 1843 "of being removed.", targetType); 1844 } 1845 1846 // If the connection is dead then keep waiting. 1847 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex); 1848 if (connection->status != Connection::STATUS_NORMAL) { 1849 return StringPrintf("Waiting because the %s window's input connection is %s." 1850 "The window may be in the process of being removed.", targetType, 1851 connection->getStatusLabel()); 1852 } 1853 1854 // If the connection is backed up then keep waiting. 1855 if (connection->inputPublisherBlocked) { 1856 return StringPrintf("Waiting because the %s window's input channel is full. " 1857 "Outbound queue length: %d. Wait queue length: %d.", 1858 targetType, connection->outboundQueue.count(), connection->waitQueue.count()); 1859 } 1860 1861 // Ensure that the dispatch queues aren't too far backed up for this event. 1862 if (eventEntry->type == EventEntry::TYPE_KEY) { 1863 // If the event is a key event, then we must wait for all previous events to 1864 // complete before delivering it because previous events may have the 1865 // side-effect of transferring focus to a different window and we want to 1866 // ensure that the following keys are sent to the new window. 1867 // 1868 // Suppose the user touches a button in a window then immediately presses "A". 1869 // If the button causes a pop-up window to appear then we want to ensure that 1870 // the "A" key is delivered to the new pop-up window. This is because users 1871 // often anticipate pending UI changes when typing on a keyboard. 1872 // To obtain this behavior, we must serialize key events with respect to all 1873 // prior input events. 1874 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) { 1875 return StringPrintf("Waiting to send key event because the %s window has not " 1876 "finished processing all of the input events that were previously " 1877 "delivered to it. Outbound queue length: %d. Wait queue length: %d.", 1878 targetType, connection->outboundQueue.count(), connection->waitQueue.count()); 1879 } 1880 } else { 1881 // Touch events can always be sent to a window immediately because the user intended 1882 // to touch whatever was visible at the time. Even if focus changes or a new 1883 // window appears moments later, the touch event was meant to be delivered to 1884 // whatever window happened to be on screen at the time. 1885 // 1886 // Generic motion events, such as trackball or joystick events are a little trickier. 1887 // Like key events, generic motion events are delivered to the focused window. 1888 // Unlike key events, generic motion events don't tend to transfer focus to other 1889 // windows and it is not important for them to be serialized. So we prefer to deliver 1890 // generic motion events as soon as possible to improve efficiency and reduce lag 1891 // through batching. 1892 // 1893 // The one case where we pause input event delivery is when the wait queue is piling 1894 // up with lots of events because the application is not responding. 1895 // This condition ensures that ANRs are detected reliably. 1896 if (!connection->waitQueue.isEmpty() 1897 && currentTime >= connection->waitQueue.head->deliveryTime 1898 + STREAM_AHEAD_EVENT_TIMEOUT) { 1899 return StringPrintf("Waiting to send non-key event because the %s window has not " 1900 "finished processing certain input events that were delivered to it over " 1901 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.", 1902 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f, 1903 connection->waitQueue.count(), 1904 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f); 1905 } 1906 } 1907 return ""; 1908 } 1909 1910 std::string InputDispatcher::getApplicationWindowLabel( 1911 const sp<InputApplicationHandle>& applicationHandle, 1912 const sp<InputWindowHandle>& windowHandle) { 1913 if (applicationHandle != nullptr) { 1914 if (windowHandle != nullptr) { 1915 std::string label(applicationHandle->getName()); 1916 label += " - "; 1917 label += windowHandle->getName(); 1918 return label; 1919 } else { 1920 return applicationHandle->getName(); 1921 } 1922 } else if (windowHandle != nullptr) { 1923 return windowHandle->getName(); 1924 } else { 1925 return "<unknown application or window>"; 1926 } 1927 } 1928 1929 void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) { 1930 int32_t displayId = getTargetDisplayId(eventEntry); 1931 sp<InputWindowHandle> focusedWindowHandle = 1932 getValueByKey(mFocusedWindowHandlesByDisplay, displayId); 1933 if (focusedWindowHandle != nullptr) { 1934 const InputWindowInfo* info = focusedWindowHandle->getInfo(); 1935 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) { 1936 #if DEBUG_DISPATCH_CYCLE 1937 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str()); 1938 #endif 1939 return; 1940 } 1941 } 1942 1943 int32_t eventType = USER_ACTIVITY_EVENT_OTHER; 1944 switch (eventEntry->type) { 1945 case EventEntry::TYPE_MOTION: { 1946 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry); 1947 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) { 1948 return; 1949 } 1950 1951 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) { 1952 eventType = USER_ACTIVITY_EVENT_TOUCH; 1953 } 1954 break; 1955 } 1956 case EventEntry::TYPE_KEY: { 1957 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry); 1958 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) { 1959 return; 1960 } 1961 eventType = USER_ACTIVITY_EVENT_BUTTON; 1962 break; 1963 } 1964 } 1965 1966 CommandEntry* commandEntry = postCommandLocked( 1967 & InputDispatcher::doPokeUserActivityLockedInterruptible); 1968 commandEntry->eventTime = eventEntry->eventTime; 1969 commandEntry->userActivityEventType = eventType; 1970 } 1971 1972 void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime, 1973 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) { 1974 if (ATRACE_ENABLED()) { 1975 std::string message = StringPrintf( 1976 "prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")", 1977 connection->getInputChannelName().c_str(), eventEntry->sequenceNum); 1978 ATRACE_NAME(message.c_str()); 1979 } 1980 #if DEBUG_DISPATCH_CYCLE 1981 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, " 1982 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, " 1983 "windowScaleFactor=(%f, %f), pointerIds=0x%x", 1984 connection->getInputChannelName().c_str(), inputTarget->flags, 1985 inputTarget->xOffset, inputTarget->yOffset, 1986 inputTarget->globalScaleFactor, 1987 inputTarget->windowXScale, inputTarget->windowYScale, 1988 inputTarget->pointerIds.value); 1989 #endif 1990 1991 // Skip this event if the connection status is not normal. 1992 // We don't want to enqueue additional outbound events if the connection is broken. 1993 if (connection->status != Connection::STATUS_NORMAL) { 1994 #if DEBUG_DISPATCH_CYCLE 1995 ALOGD("channel '%s' ~ Dropping event because the channel status is %s", 1996 connection->getInputChannelName().c_str(), connection->getStatusLabel()); 1997 #endif 1998 return; 1999 } 2000 2001 // Split a motion event if needed. 2002 if (inputTarget->flags & InputTarget::FLAG_SPLIT) { 2003 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION); 2004 2005 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry); 2006 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) { 2007 MotionEntry* splitMotionEntry = splitMotionEvent( 2008 originalMotionEntry, inputTarget->pointerIds); 2009 if (!splitMotionEntry) { 2010 return; // split event was dropped 2011 } 2012 #if DEBUG_FOCUS 2013 ALOGD("channel '%s' ~ Split motion event.", 2014 connection->getInputChannelName().c_str()); 2015 logOutboundMotionDetails(" ", splitMotionEntry); 2016 #endif 2017 enqueueDispatchEntriesLocked(currentTime, connection, 2018 splitMotionEntry, inputTarget); 2019 splitMotionEntry->release(); 2020 return; 2021 } 2022 } 2023 2024 // Not splitting. Enqueue dispatch entries for the event as is. 2025 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget); 2026 } 2027 2028 void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime, 2029 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) { 2030 if (ATRACE_ENABLED()) { 2031 std::string message = StringPrintf( 2032 "enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")", 2033 connection->getInputChannelName().c_str(), eventEntry->sequenceNum); 2034 ATRACE_NAME(message.c_str()); 2035 } 2036 2037 bool wasEmpty = connection->outboundQueue.isEmpty(); 2038 2039 // Enqueue dispatch entries for the requested modes. 2040 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, 2041 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT); 2042 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, 2043 InputTarget::FLAG_DISPATCH_AS_OUTSIDE); 2044 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, 2045 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER); 2046 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, 2047 InputTarget::FLAG_DISPATCH_AS_IS); 2048 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, 2049 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT); 2050 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, 2051 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER); 2052 2053 // If the outbound queue was previously empty, start the dispatch cycle going. 2054 if (wasEmpty && !connection->outboundQueue.isEmpty()) { 2055 startDispatchCycleLocked(currentTime, connection); 2056 } 2057 } 2058 2059 void InputDispatcher::enqueueDispatchEntryLocked( 2060 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget, 2061 int32_t dispatchMode) { 2062 if (ATRACE_ENABLED()) { 2063 std::string message = StringPrintf( 2064 "enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)", 2065 connection->getInputChannelName().c_str(), 2066 dispatchModeToString(dispatchMode).c_str()); 2067 ATRACE_NAME(message.c_str()); 2068 } 2069 int32_t inputTargetFlags = inputTarget->flags; 2070 if (!(inputTargetFlags & dispatchMode)) { 2071 return; 2072 } 2073 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode; 2074 2075 // This is a new event. 2076 // Enqueue a new dispatch entry onto the outbound queue for this connection. 2077 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref 2078 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset, 2079 inputTarget->globalScaleFactor, inputTarget->windowXScale, 2080 inputTarget->windowYScale); 2081 2082 // Apply target flags and update the connection's input state. 2083 switch (eventEntry->type) { 2084 case EventEntry::TYPE_KEY: { 2085 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry); 2086 dispatchEntry->resolvedAction = keyEntry->action; 2087 dispatchEntry->resolvedFlags = keyEntry->flags; 2088 2089 if (!connection->inputState.trackKey(keyEntry, 2090 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { 2091 #if DEBUG_DISPATCH_CYCLE 2092 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event", 2093 connection->getInputChannelName().c_str()); 2094 #endif 2095 delete dispatchEntry; 2096 return; // skip the inconsistent event 2097 } 2098 break; 2099 } 2100 2101 case EventEntry::TYPE_MOTION: { 2102 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry); 2103 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { 2104 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE; 2105 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) { 2106 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT; 2107 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) { 2108 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; 2109 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { 2110 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL; 2111 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) { 2112 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN; 2113 } else { 2114 dispatchEntry->resolvedAction = motionEntry->action; 2115 } 2116 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE 2117 && !connection->inputState.isHovering( 2118 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) { 2119 #if DEBUG_DISPATCH_CYCLE 2120 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event", 2121 connection->getInputChannelName().c_str()); 2122 #endif 2123 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; 2124 } 2125 2126 dispatchEntry->resolvedFlags = motionEntry->flags; 2127 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) { 2128 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED; 2129 } 2130 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) { 2131 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED; 2132 } 2133 2134 if (!connection->inputState.trackMotion(motionEntry, 2135 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { 2136 #if DEBUG_DISPATCH_CYCLE 2137 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event", 2138 connection->getInputChannelName().c_str()); 2139 #endif 2140 delete dispatchEntry; 2141 return; // skip the inconsistent event 2142 } 2143 2144 dispatchPointerDownOutsideFocus(motionEntry->source, 2145 dispatchEntry->resolvedAction, inputTarget->inputChannel->getToken()); 2146 2147 break; 2148 } 2149 } 2150 2151 // Remember that we are waiting for this dispatch to complete. 2152 if (dispatchEntry->hasForegroundTarget()) { 2153 incrementPendingForegroundDispatches(eventEntry); 2154 } 2155 2156 // Enqueue the dispatch entry. 2157 connection->outboundQueue.enqueueAtTail(dispatchEntry); 2158 traceOutboundQueueLength(connection); 2159 2160 } 2161 2162 void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action, 2163 const sp<IBinder>& newToken) { 2164 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; 2165 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK; 2166 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) { 2167 return; 2168 } 2169 2170 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken); 2171 if (inputWindowHandle == nullptr) { 2172 return; 2173 } 2174 2175 sp<InputWindowHandle> focusedWindowHandle = 2176 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId); 2177 2178 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken; 2179 2180 if (!hasFocusChanged) { 2181 return; 2182 } 2183 2184 CommandEntry* commandEntry = postCommandLocked( 2185 & InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible); 2186 commandEntry->newToken = newToken; 2187 } 2188 2189 void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime, 2190 const sp<Connection>& connection) { 2191 if (ATRACE_ENABLED()) { 2192 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)", 2193 connection->getInputChannelName().c_str()); 2194 ATRACE_NAME(message.c_str()); 2195 } 2196 #if DEBUG_DISPATCH_CYCLE 2197 ALOGD("channel '%s' ~ startDispatchCycle", 2198 connection->getInputChannelName().c_str()); 2199 #endif 2200 2201 while (connection->status == Connection::STATUS_NORMAL 2202 && !connection->outboundQueue.isEmpty()) { 2203 DispatchEntry* dispatchEntry = connection->outboundQueue.head; 2204 dispatchEntry->deliveryTime = currentTime; 2205 2206 // Publish the event. 2207 status_t status; 2208 EventEntry* eventEntry = dispatchEntry->eventEntry; 2209 switch (eventEntry->type) { 2210 case EventEntry::TYPE_KEY: { 2211 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry); 2212 2213 // Publish the key event. 2214 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq, 2215 keyEntry->deviceId, keyEntry->source, keyEntry->displayId, 2216 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags, 2217 keyEntry->keyCode, keyEntry->scanCode, 2218 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime, 2219 keyEntry->eventTime); 2220 break; 2221 } 2222 2223 case EventEntry::TYPE_MOTION: { 2224 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry); 2225 2226 PointerCoords scaledCoords[MAX_POINTERS]; 2227 const PointerCoords* usingCoords = motionEntry->pointerCoords; 2228 2229 // Set the X and Y offset depending on the input source. 2230 float xOffset, yOffset; 2231 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) 2232 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) { 2233 float globalScaleFactor = dispatchEntry->globalScaleFactor; 2234 float wxs = dispatchEntry->windowXScale; 2235 float wys = dispatchEntry->windowYScale; 2236 xOffset = dispatchEntry->xOffset * wxs; 2237 yOffset = dispatchEntry->yOffset * wys; 2238 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) { 2239 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) { 2240 scaledCoords[i] = motionEntry->pointerCoords[i]; 2241 scaledCoords[i].scale(globalScaleFactor, wxs, wys); 2242 } 2243 usingCoords = scaledCoords; 2244 } 2245 } else { 2246 xOffset = 0.0f; 2247 yOffset = 0.0f; 2248 2249 // We don't want the dispatch target to know. 2250 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) { 2251 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) { 2252 scaledCoords[i].clear(); 2253 } 2254 usingCoords = scaledCoords; 2255 } 2256 } 2257 2258 // Publish the motion event. 2259 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq, 2260 motionEntry->deviceId, motionEntry->source, motionEntry->displayId, 2261 dispatchEntry->resolvedAction, motionEntry->actionButton, 2262 dispatchEntry->resolvedFlags, motionEntry->edgeFlags, 2263 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification, 2264 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision, 2265 motionEntry->downTime, motionEntry->eventTime, 2266 motionEntry->pointerCount, motionEntry->pointerProperties, 2267 usingCoords); 2268 break; 2269 } 2270 2271 default: 2272 ALOG_ASSERT(false); 2273 return; 2274 } 2275 2276 // Check the result. 2277 if (status) { 2278 if (status == WOULD_BLOCK) { 2279 if (connection->waitQueue.isEmpty()) { 2280 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. " 2281 "This is unexpected because the wait queue is empty, so the pipe " 2282 "should be empty and we shouldn't have any problems writing an " 2283 "event to it, status=%d", connection->getInputChannelName().c_str(), 2284 status); 2285 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/); 2286 } else { 2287 // Pipe is full and we are waiting for the app to finish process some events 2288 // before sending more events to it. 2289 #if DEBUG_DISPATCH_CYCLE 2290 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, " 2291 "waiting for the application to catch up", 2292 connection->getInputChannelName().c_str()); 2293 #endif 2294 connection->inputPublisherBlocked = true; 2295 } 2296 } else { 2297 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, " 2298 "status=%d", connection->getInputChannelName().c_str(), status); 2299 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/); 2300 } 2301 return; 2302 } 2303 2304 // Re-enqueue the event on the wait queue. 2305 connection->outboundQueue.dequeue(dispatchEntry); 2306 traceOutboundQueueLength(connection); 2307 connection->waitQueue.enqueueAtTail(dispatchEntry); 2308 traceWaitQueueLength(connection); 2309 } 2310 } 2311 2312 void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime, 2313 const sp<Connection>& connection, uint32_t seq, bool handled) { 2314 #if DEBUG_DISPATCH_CYCLE 2315 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s", 2316 connection->getInputChannelName().c_str(), seq, toString(handled)); 2317 #endif 2318 2319 connection->inputPublisherBlocked = false; 2320 2321 if (connection->status == Connection::STATUS_BROKEN 2322 || connection->status == Connection::STATUS_ZOMBIE) { 2323 return; 2324 } 2325 2326 // Notify other system components and prepare to start the next dispatch cycle. 2327 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled); 2328 } 2329 2330 void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime, 2331 const sp<Connection>& connection, bool notify) { 2332 #if DEBUG_DISPATCH_CYCLE 2333 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s", 2334 connection->getInputChannelName().c_str(), toString(notify)); 2335 #endif 2336 2337 // Clear the dispatch queues. 2338 drainDispatchQueue(&connection->outboundQueue); 2339 traceOutboundQueueLength(connection); 2340 drainDispatchQueue(&connection->waitQueue); 2341 traceWaitQueueLength(connection); 2342 2343 // The connection appears to be unrecoverably broken. 2344 // Ignore already broken or zombie connections. 2345 if (connection->status == Connection::STATUS_NORMAL) { 2346 connection->status = Connection::STATUS_BROKEN; 2347 2348 if (notify) { 2349 // Notify other system components. 2350 onDispatchCycleBrokenLocked(currentTime, connection); 2351 } 2352 } 2353 } 2354 2355 void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) { 2356 while (!queue->isEmpty()) { 2357 DispatchEntry* dispatchEntry = queue->dequeueAtHead(); 2358 releaseDispatchEntry(dispatchEntry); 2359 } 2360 } 2361 2362 void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) { 2363 if (dispatchEntry->hasForegroundTarget()) { 2364 decrementPendingForegroundDispatches(dispatchEntry->eventEntry); 2365 } 2366 delete dispatchEntry; 2367 } 2368 2369 int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) { 2370 InputDispatcher* d = static_cast<InputDispatcher*>(data); 2371 2372 { // acquire lock 2373 std::scoped_lock _l(d->mLock); 2374 2375 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd); 2376 if (connectionIndex < 0) { 2377 ALOGE("Received spurious receive callback for unknown input channel. " 2378 "fd=%d, events=0x%x", fd, events); 2379 return 0; // remove the callback 2380 } 2381 2382 bool notify; 2383 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex); 2384 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) { 2385 if (!(events & ALOOPER_EVENT_INPUT)) { 2386 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. " 2387 "events=0x%x", connection->getInputChannelName().c_str(), events); 2388 return 1; 2389 } 2390 2391 nsecs_t currentTime = now(); 2392 bool gotOne = false; 2393 status_t status; 2394 for (;;) { 2395 uint32_t seq; 2396 bool handled; 2397 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled); 2398 if (status) { 2399 break; 2400 } 2401 d->finishDispatchCycleLocked(currentTime, connection, seq, handled); 2402 gotOne = true; 2403 } 2404 if (gotOne) { 2405 d->runCommandsLockedInterruptible(); 2406 if (status == WOULD_BLOCK) { 2407 return 1; 2408 } 2409 } 2410 2411 notify = status != DEAD_OBJECT || !connection->monitor; 2412 if (notify) { 2413 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d", 2414 connection->getInputChannelName().c_str(), status); 2415 } 2416 } else { 2417 // Monitor channels are never explicitly unregistered. 2418 // We do it automatically when the remote endpoint is closed so don't warn 2419 // about them. 2420 notify = !connection->monitor; 2421 if (notify) { 2422 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. " 2423 "events=0x%x", connection->getInputChannelName().c_str(), events); 2424 } 2425 } 2426 2427 // Unregister the channel. 2428 d->unregisterInputChannelLocked(connection->inputChannel, notify); 2429 return 0; // remove the callback 2430 } // release lock 2431 } 2432 2433 void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked ( 2434 const CancelationOptions& options) { 2435 for (size_t i = 0; i < mConnectionsByFd.size(); i++) { 2436 synthesizeCancelationEventsForConnectionLocked( 2437 mConnectionsByFd.valueAt(i), options); 2438 } 2439 } 2440 2441 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked ( 2442 const CancelationOptions& options) { 2443 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay); 2444 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay); 2445 } 2446 2447 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked( 2448 const CancelationOptions& options, 2449 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) { 2450 for (const auto& it : monitorsByDisplay) { 2451 const std::vector<Monitor>& monitors = it.second; 2452 for (const Monitor& monitor : monitors) { 2453 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options); 2454 } 2455 } 2456 } 2457 2458 void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked( 2459 const sp<InputChannel>& channel, const CancelationOptions& options) { 2460 ssize_t index = getConnectionIndexLocked(channel); 2461 if (index >= 0) { 2462 synthesizeCancelationEventsForConnectionLocked( 2463 mConnectionsByFd.valueAt(index), options); 2464 } 2465 } 2466 2467 void InputDispatcher::synthesizeCancelationEventsForConnectionLocked( 2468 const sp<Connection>& connection, const CancelationOptions& options) { 2469 if (connection->status == Connection::STATUS_BROKEN) { 2470 return; 2471 } 2472 2473 nsecs_t currentTime = now(); 2474 2475 std::vector<EventEntry*> cancelationEvents; 2476 connection->inputState.synthesizeCancelationEvents(currentTime, 2477 cancelationEvents, options); 2478 2479 if (!cancelationEvents.empty()) { 2480 #if DEBUG_OUTBOUND_EVENT_DETAILS 2481 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync " 2482 "with reality: %s, mode=%d.", 2483 connection->getInputChannelName().c_str(), cancelationEvents.size(), 2484 options.reason, options.mode); 2485 #endif 2486 for (size_t i = 0; i < cancelationEvents.size(); i++) { 2487 EventEntry* cancelationEventEntry = cancelationEvents[i]; 2488 switch (cancelationEventEntry->type) { 2489 case EventEntry::TYPE_KEY: 2490 logOutboundKeyDetails("cancel - ", 2491 static_cast<KeyEntry*>(cancelationEventEntry)); 2492 break; 2493 case EventEntry::TYPE_MOTION: 2494 logOutboundMotionDetails("cancel - ", 2495 static_cast<MotionEntry*>(cancelationEventEntry)); 2496 break; 2497 } 2498 2499 InputTarget target; 2500 sp<InputWindowHandle> windowHandle = getWindowHandleLocked( 2501 connection->inputChannel->getToken()); 2502 if (windowHandle != nullptr) { 2503 const InputWindowInfo* windowInfo = windowHandle->getInfo(); 2504 target.xOffset = -windowInfo->frameLeft; 2505 target.yOffset = -windowInfo->frameTop; 2506 target.globalScaleFactor = windowInfo->globalScaleFactor; 2507 target.windowXScale = windowInfo->windowXScale; 2508 target.windowYScale = windowInfo->windowYScale; 2509 } else { 2510 target.xOffset = 0; 2511 target.yOffset = 0; 2512 target.globalScaleFactor = 1.0f; 2513 } 2514 target.inputChannel = connection->inputChannel; 2515 target.flags = InputTarget::FLAG_DISPATCH_AS_IS; 2516 2517 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref 2518 &target, InputTarget::FLAG_DISPATCH_AS_IS); 2519 2520 cancelationEventEntry->release(); 2521 } 2522 2523 startDispatchCycleLocked(currentTime, connection); 2524 } 2525 } 2526 2527 InputDispatcher::MotionEntry* 2528 InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) { 2529 ALOG_ASSERT(pointerIds.value != 0); 2530 2531 uint32_t splitPointerIndexMap[MAX_POINTERS]; 2532 PointerProperties splitPointerProperties[MAX_POINTERS]; 2533 PointerCoords splitPointerCoords[MAX_POINTERS]; 2534 2535 uint32_t originalPointerCount = originalMotionEntry->pointerCount; 2536 uint32_t splitPointerCount = 0; 2537 2538 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount; 2539 originalPointerIndex++) { 2540 const PointerProperties& pointerProperties = 2541 originalMotionEntry->pointerProperties[originalPointerIndex]; 2542 uint32_t pointerId = uint32_t(pointerProperties.id); 2543 if (pointerIds.hasBit(pointerId)) { 2544 splitPointerIndexMap[splitPointerCount] = originalPointerIndex; 2545 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties); 2546 splitPointerCoords[splitPointerCount].copyFrom( 2547 originalMotionEntry->pointerCoords[originalPointerIndex]); 2548 splitPointerCount += 1; 2549 } 2550 } 2551 2552 if (splitPointerCount != pointerIds.count()) { 2553 // This is bad. We are missing some of the pointers that we expected to deliver. 2554 // Most likely this indicates that we received an ACTION_MOVE events that has 2555 // different pointer ids than we expected based on the previous ACTION_DOWN 2556 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers 2557 // in this way. 2558 ALOGW("Dropping split motion event because the pointer count is %d but " 2559 "we expected there to be %d pointers. This probably means we received " 2560 "a broken sequence of pointer ids from the input device.", 2561 splitPointerCount, pointerIds.count()); 2562 return nullptr; 2563 } 2564 2565 int32_t action = originalMotionEntry->action; 2566 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; 2567 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN 2568 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) { 2569 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action); 2570 const PointerProperties& pointerProperties = 2571 originalMotionEntry->pointerProperties[originalPointerIndex]; 2572 uint32_t pointerId = uint32_t(pointerProperties.id); 2573 if (pointerIds.hasBit(pointerId)) { 2574 if (pointerIds.count() == 1) { 2575 // The first/last pointer went down/up. 2576 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN 2577 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP; 2578 } else { 2579 // A secondary pointer went down/up. 2580 uint32_t splitPointerIndex = 0; 2581 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) { 2582 splitPointerIndex += 1; 2583 } 2584 action = maskedAction | (splitPointerIndex 2585 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); 2586 } 2587 } else { 2588 // An unrelated pointer changed. 2589 action = AMOTION_EVENT_ACTION_MOVE; 2590 } 2591 } 2592 2593 MotionEntry* splitMotionEntry = new MotionEntry( 2594 originalMotionEntry->sequenceNum, 2595 originalMotionEntry->eventTime, 2596 originalMotionEntry->deviceId, 2597 originalMotionEntry->source, 2598 originalMotionEntry->displayId, 2599 originalMotionEntry->policyFlags, 2600 action, 2601 originalMotionEntry->actionButton, 2602 originalMotionEntry->flags, 2603 originalMotionEntry->metaState, 2604 originalMotionEntry->buttonState, 2605 originalMotionEntry->classification, 2606 originalMotionEntry->edgeFlags, 2607 originalMotionEntry->xPrecision, 2608 originalMotionEntry->yPrecision, 2609 originalMotionEntry->downTime, 2610 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0); 2611 2612 if (originalMotionEntry->injectionState) { 2613 splitMotionEntry->injectionState = originalMotionEntry->injectionState; 2614 splitMotionEntry->injectionState->refCount += 1; 2615 } 2616 2617 return splitMotionEntry; 2618 } 2619 2620 void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) { 2621 #if DEBUG_INBOUND_EVENT_DETAILS 2622 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime); 2623 #endif 2624 2625 bool needWake; 2626 { // acquire lock 2627 std::scoped_lock _l(mLock); 2628 2629 ConfigurationChangedEntry* newEntry = 2630 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime); 2631 needWake = enqueueInboundEventLocked(newEntry); 2632 } // release lock 2633 2634 if (needWake) { 2635 mLooper->wake(); 2636 } 2637 } 2638 2639 /** 2640 * If one of the meta shortcuts is detected, process them here: 2641 * Meta + Backspace -> generate BACK 2642 * Meta + Enter -> generate HOME 2643 * This will potentially overwrite keyCode and metaState. 2644 */ 2645 void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action, 2646 int32_t& keyCode, int32_t& metaState) { 2647 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) { 2648 int32_t newKeyCode = AKEYCODE_UNKNOWN; 2649 if (keyCode == AKEYCODE_DEL) { 2650 newKeyCode = AKEYCODE_BACK; 2651 } else if (keyCode == AKEYCODE_ENTER) { 2652 newKeyCode = AKEYCODE_HOME; 2653 } 2654 if (newKeyCode != AKEYCODE_UNKNOWN) { 2655 std::scoped_lock _l(mLock); 2656 struct KeyReplacement replacement = {keyCode, deviceId}; 2657 mReplacedKeys.add(replacement, newKeyCode); 2658 keyCode = newKeyCode; 2659 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON); 2660 } 2661 } else if (action == AKEY_EVENT_ACTION_UP) { 2662 // In order to maintain a consistent stream of up and down events, check to see if the key 2663 // going up is one we've replaced in a down event and haven't yet replaced in an up event, 2664 // even if the modifier was released between the down and the up events. 2665 std::scoped_lock _l(mLock); 2666 struct KeyReplacement replacement = {keyCode, deviceId}; 2667 ssize_t index = mReplacedKeys.indexOfKey(replacement); 2668 if (index >= 0) { 2669 keyCode = mReplacedKeys.valueAt(index); 2670 mReplacedKeys.removeItemsAt(index); 2671 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON); 2672 } 2673 } 2674 } 2675 2676 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) { 2677 #if DEBUG_INBOUND_EVENT_DETAILS 2678 ALOGD("notifyKey - eventTime=%" PRId64 2679 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, " 2680 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64, 2681 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags, 2682 args->action, args->flags, args->keyCode, args->scanCode, 2683 args->metaState, args->downTime); 2684 #endif 2685 if (!validateKeyEvent(args->action)) { 2686 return; 2687 } 2688 2689 uint32_t policyFlags = args->policyFlags; 2690 int32_t flags = args->flags; 2691 int32_t metaState = args->metaState; 2692 // InputDispatcher tracks and generates key repeats on behalf of 2693 // whatever notifies it, so repeatCount should always be set to 0 2694 constexpr int32_t repeatCount = 0; 2695 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) { 2696 policyFlags |= POLICY_FLAG_VIRTUAL; 2697 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY; 2698 } 2699 if (policyFlags & POLICY_FLAG_FUNCTION) { 2700 metaState |= AMETA_FUNCTION_ON; 2701 } 2702 2703 policyFlags |= POLICY_FLAG_TRUSTED; 2704 2705 int32_t keyCode = args->keyCode; 2706 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState); 2707 2708 KeyEvent event; 2709 event.initialize(args->deviceId, args->source, args->displayId, args->action, 2710 flags, keyCode, args->scanCode, metaState, repeatCount, 2711 args->downTime, args->eventTime); 2712 2713 android::base::Timer t; 2714 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags); 2715 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) { 2716 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms", 2717 std::to_string(t.duration().count()).c_str()); 2718 } 2719 2720 bool needWake; 2721 { // acquire lock 2722 mLock.lock(); 2723 2724 if (shouldSendKeyToInputFilterLocked(args)) { 2725 mLock.unlock(); 2726 2727 policyFlags |= POLICY_FLAG_FILTERED; 2728 if (!mPolicy->filterInputEvent(&event, policyFlags)) { 2729 return; // event was consumed by the filter 2730 } 2731 2732 mLock.lock(); 2733 } 2734 2735 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime, 2736 args->deviceId, args->source, args->displayId, policyFlags, 2737 args->action, flags, keyCode, args->scanCode, 2738 metaState, repeatCount, args->downTime); 2739 2740 needWake = enqueueInboundEventLocked(newEntry); 2741 mLock.unlock(); 2742 } // release lock 2743 2744 if (needWake) { 2745 mLooper->wake(); 2746 } 2747 } 2748 2749 bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) { 2750 return mInputFilterEnabled; 2751 } 2752 2753 void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) { 2754 #if DEBUG_INBOUND_EVENT_DETAILS 2755 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 2756 ", policyFlags=0x%x, " 2757 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x," 2758 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64, 2759 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags, 2760 args->action, args->actionButton, args->flags, args->metaState, args->buttonState, 2761 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime); 2762 for (uint32_t i = 0; i < args->pointerCount; i++) { 2763 ALOGD(" Pointer %d: id=%d, toolType=%d, " 2764 "x=%f, y=%f, pressure=%f, size=%f, " 2765 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, " 2766 "orientation=%f", 2767 i, args->pointerProperties[i].id, 2768 args->pointerProperties[i].toolType, 2769 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X), 2770 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y), 2771 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), 2772 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE), 2773 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), 2774 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), 2775 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), 2776 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), 2777 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION)); 2778 } 2779 #endif 2780 if (!validateMotionEvent(args->action, args->actionButton, 2781 args->pointerCount, args->pointerProperties)) { 2782 return; 2783 } 2784 2785 uint32_t policyFlags = args->policyFlags; 2786 policyFlags |= POLICY_FLAG_TRUSTED; 2787 2788 android::base::Timer t; 2789 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags); 2790 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) { 2791 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms", 2792 std::to_string(t.duration().count()).c_str()); 2793 } 2794 2795 bool needWake; 2796 { // acquire lock 2797 mLock.lock(); 2798 2799 if (shouldSendMotionToInputFilterLocked(args)) { 2800 mLock.unlock(); 2801 2802 MotionEvent event; 2803 event.initialize(args->deviceId, args->source, args->displayId, 2804 args->action, args->actionButton, 2805 args->flags, args->edgeFlags, args->metaState, args->buttonState, 2806 args->classification, 0, 0, args->xPrecision, args->yPrecision, 2807 args->downTime, args->eventTime, 2808 args->pointerCount, args->pointerProperties, args->pointerCoords); 2809 2810 policyFlags |= POLICY_FLAG_FILTERED; 2811 if (!mPolicy->filterInputEvent(&event, policyFlags)) { 2812 return; // event was consumed by the filter 2813 } 2814 2815 mLock.lock(); 2816 } 2817 2818 // Just enqueue a new motion event. 2819 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime, 2820 args->deviceId, args->source, args->displayId, policyFlags, 2821 args->action, args->actionButton, args->flags, 2822 args->metaState, args->buttonState, args->classification, 2823 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime, 2824 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0); 2825 2826 needWake = enqueueInboundEventLocked(newEntry); 2827 mLock.unlock(); 2828 } // release lock 2829 2830 if (needWake) { 2831 mLooper->wake(); 2832 } 2833 } 2834 2835 bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) { 2836 return mInputFilterEnabled; 2837 } 2838 2839 void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) { 2840 #if DEBUG_INBOUND_EVENT_DETAILS 2841 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, " 2842 "switchMask=0x%08x", 2843 args->eventTime, args->policyFlags, args->switchValues, args->switchMask); 2844 #endif 2845 2846 uint32_t policyFlags = args->policyFlags; 2847 policyFlags |= POLICY_FLAG_TRUSTED; 2848 mPolicy->notifySwitch(args->eventTime, 2849 args->switchValues, args->switchMask, policyFlags); 2850 } 2851 2852 void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) { 2853 #if DEBUG_INBOUND_EVENT_DETAILS 2854 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", 2855 args->eventTime, args->deviceId); 2856 #endif 2857 2858 bool needWake; 2859 { // acquire lock 2860 std::scoped_lock _l(mLock); 2861 2862 DeviceResetEntry* newEntry = 2863 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId); 2864 needWake = enqueueInboundEventLocked(newEntry); 2865 } // release lock 2866 2867 if (needWake) { 2868 mLooper->wake(); 2869 } 2870 } 2871 2872 int32_t InputDispatcher::injectInputEvent(const InputEvent* event, 2873 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis, 2874 uint32_t policyFlags) { 2875 #if DEBUG_INBOUND_EVENT_DETAILS 2876 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, " 2877 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x", 2878 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags); 2879 #endif 2880 2881 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis); 2882 2883 policyFlags |= POLICY_FLAG_INJECTED; 2884 if (hasInjectionPermission(injectorPid, injectorUid)) { 2885 policyFlags |= POLICY_FLAG_TRUSTED; 2886 } 2887 2888 EventEntry* firstInjectedEntry; 2889 EventEntry* lastInjectedEntry; 2890 switch (event->getType()) { 2891 case AINPUT_EVENT_TYPE_KEY: { 2892 KeyEvent keyEvent; 2893 keyEvent.initialize(*static_cast<const KeyEvent*>(event)); 2894 int32_t action = keyEvent.getAction(); 2895 if (! validateKeyEvent(action)) { 2896 return INPUT_EVENT_INJECTION_FAILED; 2897 } 2898 2899 int32_t flags = keyEvent.getFlags(); 2900 int32_t keyCode = keyEvent.getKeyCode(); 2901 int32_t metaState = keyEvent.getMetaState(); 2902 accelerateMetaShortcuts(keyEvent.getDeviceId(), action, 2903 /*byref*/ keyCode, /*byref*/ metaState); 2904 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(), 2905 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(), 2906 keyEvent.getDownTime(), keyEvent.getEventTime()); 2907 2908 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) { 2909 policyFlags |= POLICY_FLAG_VIRTUAL; 2910 } 2911 2912 if (!(policyFlags & POLICY_FLAG_FILTERED)) { 2913 android::base::Timer t; 2914 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags); 2915 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) { 2916 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms", 2917 std::to_string(t.duration().count()).c_str()); 2918 } 2919 } 2920 2921 mLock.lock(); 2922 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(), 2923 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(), 2924 policyFlags, action, flags, 2925 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(), 2926 keyEvent.getRepeatCount(), keyEvent.getDownTime()); 2927 lastInjectedEntry = firstInjectedEntry; 2928 break; 2929 } 2930 2931 case AINPUT_EVENT_TYPE_MOTION: { 2932 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event); 2933 int32_t action = motionEvent->getAction(); 2934 size_t pointerCount = motionEvent->getPointerCount(); 2935 const PointerProperties* pointerProperties = motionEvent->getPointerProperties(); 2936 int32_t actionButton = motionEvent->getActionButton(); 2937 int32_t displayId = motionEvent->getDisplayId(); 2938 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) { 2939 return INPUT_EVENT_INJECTION_FAILED; 2940 } 2941 2942 if (!(policyFlags & POLICY_FLAG_FILTERED)) { 2943 nsecs_t eventTime = motionEvent->getEventTime(); 2944 android::base::Timer t; 2945 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags); 2946 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) { 2947 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms", 2948 std::to_string(t.duration().count()).c_str()); 2949 } 2950 } 2951 2952 mLock.lock(); 2953 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes(); 2954 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords(); 2955 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes, 2956 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(), 2957 policyFlags, 2958 action, actionButton, motionEvent->getFlags(), 2959 motionEvent->getMetaState(), motionEvent->getButtonState(), 2960 motionEvent->getClassification(), motionEvent->getEdgeFlags(), 2961 motionEvent->getXPrecision(), motionEvent->getYPrecision(), 2962 motionEvent->getDownTime(), 2963 uint32_t(pointerCount), pointerProperties, samplePointerCoords, 2964 motionEvent->getXOffset(), motionEvent->getYOffset()); 2965 lastInjectedEntry = firstInjectedEntry; 2966 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) { 2967 sampleEventTimes += 1; 2968 samplePointerCoords += pointerCount; 2969 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, 2970 *sampleEventTimes, 2971 motionEvent->getDeviceId(), motionEvent->getSource(), 2972 motionEvent->getDisplayId(), policyFlags, 2973 action, actionButton, motionEvent->getFlags(), 2974 motionEvent->getMetaState(), motionEvent->getButtonState(), 2975 motionEvent->getClassification(), motionEvent->getEdgeFlags(), 2976 motionEvent->getXPrecision(), motionEvent->getYPrecision(), 2977 motionEvent->getDownTime(), 2978 uint32_t(pointerCount), pointerProperties, samplePointerCoords, 2979 motionEvent->getXOffset(), motionEvent->getYOffset()); 2980 lastInjectedEntry->next = nextInjectedEntry; 2981 lastInjectedEntry = nextInjectedEntry; 2982 } 2983 break; 2984 } 2985 2986 default: 2987 ALOGW("Cannot inject event of type %d", event->getType()); 2988 return INPUT_EVENT_INJECTION_FAILED; 2989 } 2990 2991 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid); 2992 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) { 2993 injectionState->injectionIsAsync = true; 2994 } 2995 2996 injectionState->refCount += 1; 2997 lastInjectedEntry->injectionState = injectionState; 2998 2999 bool needWake = false; 3000 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) { 3001 EventEntry* nextEntry = entry->next; 3002 needWake |= enqueueInboundEventLocked(entry); 3003 entry = nextEntry; 3004 } 3005 3006 mLock.unlock(); 3007 3008 if (needWake) { 3009 mLooper->wake(); 3010 } 3011 3012 int32_t injectionResult; 3013 { // acquire lock 3014 std::unique_lock _l(mLock); 3015 3016 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) { 3017 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; 3018 } else { 3019 for (;;) { 3020 injectionResult = injectionState->injectionResult; 3021 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) { 3022 break; 3023 } 3024 3025 nsecs_t remainingTimeout = endTime - now(); 3026 if (remainingTimeout <= 0) { 3027 #if DEBUG_INJECTION 3028 ALOGD("injectInputEvent - Timed out waiting for injection result " 3029 "to become available."); 3030 #endif 3031 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT; 3032 break; 3033 } 3034 3035 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout)); 3036 } 3037 3038 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED 3039 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) { 3040 while (injectionState->pendingForegroundDispatches != 0) { 3041 #if DEBUG_INJECTION 3042 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.", 3043 injectionState->pendingForegroundDispatches); 3044 #endif 3045 nsecs_t remainingTimeout = endTime - now(); 3046 if (remainingTimeout <= 0) { 3047 #if DEBUG_INJECTION 3048 ALOGD("injectInputEvent - Timed out waiting for pending foreground " 3049 "dispatches to finish."); 3050 #endif 3051 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT; 3052 break; 3053 } 3054 3055 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout)); 3056 } 3057 } 3058 } 3059 3060 injectionState->release(); 3061 } // release lock 3062 3063 #if DEBUG_INJECTION 3064 ALOGD("injectInputEvent - Finished with result %d. " 3065 "injectorPid=%d, injectorUid=%d", 3066 injectionResult, injectorPid, injectorUid); 3067 #endif 3068 3069 return injectionResult; 3070 } 3071 3072 bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) { 3073 return injectorUid == 0 3074 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid); 3075 } 3076 3077 void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) { 3078 InjectionState* injectionState = entry->injectionState; 3079 if (injectionState) { 3080 #if DEBUG_INJECTION 3081 ALOGD("Setting input event injection result to %d. " 3082 "injectorPid=%d, injectorUid=%d", 3083 injectionResult, injectionState->injectorPid, injectionState->injectorUid); 3084 #endif 3085 3086 if (injectionState->injectionIsAsync 3087 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) { 3088 // Log the outcome since the injector did not wait for the injection result. 3089 switch (injectionResult) { 3090 case INPUT_EVENT_INJECTION_SUCCEEDED: 3091 ALOGV("Asynchronous input event injection succeeded."); 3092 break; 3093 case INPUT_EVENT_INJECTION_FAILED: 3094 ALOGW("Asynchronous input event injection failed."); 3095 break; 3096 case INPUT_EVENT_INJECTION_PERMISSION_DENIED: 3097 ALOGW("Asynchronous input event injection permission denied."); 3098 break; 3099 case INPUT_EVENT_INJECTION_TIMED_OUT: 3100 ALOGW("Asynchronous input event injection timed out."); 3101 break; 3102 } 3103 } 3104 3105 injectionState->injectionResult = injectionResult; 3106 mInjectionResultAvailable.notify_all(); 3107 } 3108 } 3109 3110 void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) { 3111 InjectionState* injectionState = entry->injectionState; 3112 if (injectionState) { 3113 injectionState->pendingForegroundDispatches += 1; 3114 } 3115 } 3116 3117 void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) { 3118 InjectionState* injectionState = entry->injectionState; 3119 if (injectionState) { 3120 injectionState->pendingForegroundDispatches -= 1; 3121 3122 if (injectionState->pendingForegroundDispatches == 0) { 3123 mInjectionSyncFinished.notify_all(); 3124 } 3125 } 3126 } 3127 3128 std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked( 3129 int32_t displayId) const { 3130 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it = 3131 mWindowHandlesByDisplay.find(displayId); 3132 if(it != mWindowHandlesByDisplay.end()) { 3133 return it->second; 3134 } 3135 3136 // Return an empty one if nothing found. 3137 return std::vector<sp<InputWindowHandle>>(); 3138 } 3139 3140 sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked( 3141 const sp<IBinder>& windowHandleToken) const { 3142 for (auto& it : mWindowHandlesByDisplay) { 3143 const std::vector<sp<InputWindowHandle>> windowHandles = it.second; 3144 for (const sp<InputWindowHandle>& windowHandle : windowHandles) { 3145 if (windowHandle->getToken() == windowHandleToken) { 3146 return windowHandle; 3147 } 3148 } 3149 } 3150 return nullptr; 3151 } 3152 3153 bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const { 3154 for (auto& it : mWindowHandlesByDisplay) { 3155 const std::vector<sp<InputWindowHandle>> windowHandles = it.second; 3156 for (const sp<InputWindowHandle>& handle : windowHandles) { 3157 if (handle->getToken() == windowHandle->getToken()) { 3158 if (windowHandle->getInfo()->displayId != it.first) { 3159 ALOGE("Found window %s in display %" PRId32 3160 ", but it should belong to display %" PRId32, 3161 windowHandle->getName().c_str(), it.first, 3162 windowHandle->getInfo()->displayId); 3163 } 3164 return true; 3165 } 3166 } 3167 } 3168 return false; 3169 } 3170 3171 sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const { 3172 size_t count = mInputChannelsByToken.count(token); 3173 if (count == 0) { 3174 return nullptr; 3175 } 3176 return mInputChannelsByToken.at(token); 3177 } 3178 3179 /** 3180 * Called from InputManagerService, update window handle list by displayId that can receive input. 3181 * A window handle contains information about InputChannel, Touch Region, Types, Focused,... 3182 * If set an empty list, remove all handles from the specific display. 3183 * For focused handle, check if need to change and send a cancel event to previous one. 3184 * For removed handle, check if need to send a cancel event if already in touch. 3185 */ 3186 void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles, 3187 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) { 3188 #if DEBUG_FOCUS 3189 ALOGD("setInputWindows displayId=%" PRId32, displayId); 3190 #endif 3191 { // acquire lock 3192 std::scoped_lock _l(mLock); 3193 3194 // Copy old handles for release if they are no longer present. 3195 const std::vector<sp<InputWindowHandle>> oldWindowHandles = 3196 getWindowHandlesLocked(displayId); 3197 3198 sp<InputWindowHandle> newFocusedWindowHandle = nullptr; 3199 bool foundHoveredWindow = false; 3200 3201 if (inputWindowHandles.empty()) { 3202 // Remove all handles on a display if there are no windows left. 3203 mWindowHandlesByDisplay.erase(displayId); 3204 } else { 3205 // Since we compare the pointer of input window handles across window updates, we need 3206 // to make sure the handle object for the same window stays unchanged across updates. 3207 const std::vector<sp<InputWindowHandle>>& oldHandles = 3208 mWindowHandlesByDisplay[displayId]; 3209 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens; 3210 for (const sp<InputWindowHandle>& handle : oldHandles) { 3211 oldHandlesByTokens[handle->getToken()] = handle; 3212 } 3213 3214 std::vector<sp<InputWindowHandle>> newHandles; 3215 for (const sp<InputWindowHandle>& handle : inputWindowHandles) { 3216 if (!handle->updateInfo()) { 3217 // handle no longer valid 3218 continue; 3219 } 3220 const InputWindowInfo* info = handle->getInfo(); 3221 3222 if ((getInputChannelLocked(handle->getToken()) == nullptr && 3223 info->portalToDisplayId == ADISPLAY_ID_NONE)) { 3224 const bool noInputChannel = 3225 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL; 3226 const bool canReceiveInput = 3227 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) || 3228 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE); 3229 if (canReceiveInput && !noInputChannel) { 3230 ALOGE("Window handle %s has no registered input channel", 3231 handle->getName().c_str()); 3232 } 3233 continue; 3234 } 3235 3236 if (info->displayId != displayId) { 3237 ALOGE("Window %s updated by wrong display %d, should belong to display %d", 3238 handle->getName().c_str(), displayId, info->displayId); 3239 continue; 3240 } 3241 3242 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) { 3243 const sp<InputWindowHandle> oldHandle = 3244 oldHandlesByTokens.at(handle->getToken()); 3245 oldHandle->updateFrom(handle); 3246 newHandles.push_back(oldHandle); 3247 } else { 3248 newHandles.push_back(handle); 3249 } 3250 } 3251 3252 for (const sp<InputWindowHandle>& windowHandle : newHandles) { 3253 // Set newFocusedWindowHandle to the top most focused window instead of the last one 3254 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus 3255 && windowHandle->getInfo()->visible) { 3256 newFocusedWindowHandle = windowHandle; 3257 } 3258 if (windowHandle == mLastHoverWindowHandle) { 3259 foundHoveredWindow = true; 3260 } 3261 } 3262 3263 // Insert or replace 3264 mWindowHandlesByDisplay[displayId] = newHandles; 3265 } 3266 3267 if (!foundHoveredWindow) { 3268 mLastHoverWindowHandle = nullptr; 3269 } 3270 3271 sp<InputWindowHandle> oldFocusedWindowHandle = 3272 getValueByKey(mFocusedWindowHandlesByDisplay, displayId); 3273 3274 if (oldFocusedWindowHandle != newFocusedWindowHandle) { 3275 if (oldFocusedWindowHandle != nullptr) { 3276 #if DEBUG_FOCUS 3277 ALOGD("Focus left window: %s in display %" PRId32, 3278 oldFocusedWindowHandle->getName().c_str(), displayId); 3279 #endif 3280 sp<InputChannel> focusedInputChannel = getInputChannelLocked( 3281 oldFocusedWindowHandle->getToken()); 3282 if (focusedInputChannel != nullptr) { 3283 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, 3284 "focus left window"); 3285 synthesizeCancelationEventsForInputChannelLocked( 3286 focusedInputChannel, options); 3287 } 3288 mFocusedWindowHandlesByDisplay.erase(displayId); 3289 } 3290 if (newFocusedWindowHandle != nullptr) { 3291 #if DEBUG_FOCUS 3292 ALOGD("Focus entered window: %s in display %" PRId32, 3293 newFocusedWindowHandle->getName().c_str(), displayId); 3294 #endif 3295 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle; 3296 } 3297 3298 if (mFocusedDisplayId == displayId) { 3299 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle); 3300 } 3301 3302 } 3303 3304 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId); 3305 if (stateIndex >= 0) { 3306 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex); 3307 for (size_t i = 0; i < state.windows.size(); ) { 3308 TouchedWindow& touchedWindow = state.windows[i]; 3309 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) { 3310 #if DEBUG_FOCUS 3311 ALOGD("Touched window was removed: %s in display %" PRId32, 3312 touchedWindow.windowHandle->getName().c_str(), displayId); 3313 #endif 3314 sp<InputChannel> touchedInputChannel = 3315 getInputChannelLocked(touchedWindow.windowHandle->getToken()); 3316 if (touchedInputChannel != nullptr) { 3317 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, 3318 "touched window was removed"); 3319 synthesizeCancelationEventsForInputChannelLocked( 3320 touchedInputChannel, options); 3321 } 3322 state.windows.erase(state.windows.begin() + i); 3323 } else { 3324 ++i; 3325 } 3326 } 3327 } 3328 3329 // Release information for windows that are no longer present. 3330 // This ensures that unused input channels are released promptly. 3331 // Otherwise, they might stick around until the window handle is destroyed 3332 // which might not happen until the next GC. 3333 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) { 3334 if (!hasWindowHandleLocked(oldWindowHandle)) { 3335 #if DEBUG_FOCUS 3336 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str()); 3337 #endif 3338 oldWindowHandle->releaseChannel(); 3339 } 3340 } 3341 } // release lock 3342 3343 // Wake up poll loop since it may need to make new input dispatching choices. 3344 mLooper->wake(); 3345 3346 if (setInputWindowsListener) { 3347 setInputWindowsListener->onSetInputWindowsFinished(); 3348 } 3349 } 3350 3351 void InputDispatcher::setFocusedApplication( 3352 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) { 3353 #if DEBUG_FOCUS 3354 ALOGD("setFocusedApplication displayId=%" PRId32, displayId); 3355 #endif 3356 { // acquire lock 3357 std::scoped_lock _l(mLock); 3358 3359 sp<InputApplicationHandle> oldFocusedApplicationHandle = 3360 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId); 3361 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) { 3362 if (oldFocusedApplicationHandle != inputApplicationHandle) { 3363 if (oldFocusedApplicationHandle != nullptr) { 3364 resetANRTimeoutsLocked(); 3365 } 3366 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle; 3367 } 3368 } else if (oldFocusedApplicationHandle != nullptr) { 3369 resetANRTimeoutsLocked(); 3370 oldFocusedApplicationHandle.clear(); 3371 mFocusedApplicationHandlesByDisplay.erase(displayId); 3372 } 3373 3374 #if DEBUG_FOCUS 3375 //logDispatchStateLocked(); 3376 #endif 3377 } // release lock 3378 3379 // Wake up poll loop since it may need to make new input dispatching choices. 3380 mLooper->wake(); 3381 } 3382 3383 /** 3384 * Sets the focused display, which is responsible for receiving focus-dispatched input events where 3385 * the display not specified. 3386 * 3387 * We track any unreleased events for each window. If a window loses the ability to receive the 3388 * released event, we will send a cancel event to it. So when the focused display is changed, we 3389 * cancel all the unreleased display-unspecified events for the focused window on the old focused 3390 * display. The display-specified events won't be affected. 3391 */ 3392 void InputDispatcher::setFocusedDisplay(int32_t displayId) { 3393 #if DEBUG_FOCUS 3394 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId); 3395 #endif 3396 { // acquire lock 3397 std::scoped_lock _l(mLock); 3398 3399 if (mFocusedDisplayId != displayId) { 3400 sp<InputWindowHandle> oldFocusedWindowHandle = 3401 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId); 3402 if (oldFocusedWindowHandle != nullptr) { 3403 sp<InputChannel> inputChannel = 3404 getInputChannelLocked(oldFocusedWindowHandle->getToken()); 3405 if (inputChannel != nullptr) { 3406 CancelationOptions options( 3407 CancelationOptions::CANCEL_NON_POINTER_EVENTS, 3408 "The display which contains this window no longer has focus."); 3409 options.displayId = ADISPLAY_ID_NONE; 3410 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options); 3411 } 3412 } 3413 mFocusedDisplayId = displayId; 3414 3415 // Sanity check 3416 sp<InputWindowHandle> newFocusedWindowHandle = 3417 getValueByKey(mFocusedWindowHandlesByDisplay, displayId); 3418 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle); 3419 3420 if (newFocusedWindowHandle == nullptr) { 3421 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId); 3422 if (!mFocusedWindowHandlesByDisplay.empty()) { 3423 ALOGE("But another display has a focused window:"); 3424 for (auto& it : mFocusedWindowHandlesByDisplay) { 3425 const int32_t displayId = it.first; 3426 const sp<InputWindowHandle>& windowHandle = it.second; 3427 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", 3428 displayId, windowHandle->getName().c_str()); 3429 } 3430 } 3431 } 3432 } 3433 3434 #if DEBUG_FOCUS 3435 logDispatchStateLocked(); 3436 #endif 3437 } // release lock 3438 3439 // Wake up poll loop since it may need to make new input dispatching choices. 3440 mLooper->wake(); 3441 } 3442 3443 void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) { 3444 #if DEBUG_FOCUS 3445 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen); 3446 #endif 3447 3448 bool changed; 3449 { // acquire lock 3450 std::scoped_lock _l(mLock); 3451 3452 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) { 3453 if (mDispatchFrozen && !frozen) { 3454 resetANRTimeoutsLocked(); 3455 } 3456 3457 if (mDispatchEnabled && !enabled) { 3458 resetAndDropEverythingLocked("dispatcher is being disabled"); 3459 } 3460 3461 mDispatchEnabled = enabled; 3462 mDispatchFrozen = frozen; 3463 changed = true; 3464 } else { 3465 changed = false; 3466 } 3467 3468 #if DEBUG_FOCUS 3469 logDispatchStateLocked(); 3470 #endif 3471 } // release lock 3472 3473 if (changed) { 3474 // Wake up poll loop since it may need to make new input dispatching choices. 3475 mLooper->wake(); 3476 } 3477 } 3478 3479 void InputDispatcher::setInputFilterEnabled(bool enabled) { 3480 #if DEBUG_FOCUS 3481 ALOGD("setInputFilterEnabled: enabled=%d", enabled); 3482 #endif 3483 3484 { // acquire lock 3485 std::scoped_lock _l(mLock); 3486 3487 if (mInputFilterEnabled == enabled) { 3488 return; 3489 } 3490 3491 mInputFilterEnabled = enabled; 3492 resetAndDropEverythingLocked("input filter is being enabled or disabled"); 3493 } // release lock 3494 3495 // Wake up poll loop since there might be work to do to drop everything. 3496 mLooper->wake(); 3497 } 3498 3499 bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) { 3500 if (fromToken == toToken) { 3501 #if DEBUG_FOCUS 3502 ALOGD("Trivial transfer to same window."); 3503 #endif 3504 return true; 3505 } 3506 3507 { // acquire lock 3508 std::scoped_lock _l(mLock); 3509 3510 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken); 3511 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken); 3512 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) { 3513 ALOGW("Cannot transfer focus because from or to window not found."); 3514 return false; 3515 } 3516 #if DEBUG_FOCUS 3517 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s", 3518 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str()); 3519 #endif 3520 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) { 3521 #if DEBUG_FOCUS 3522 ALOGD("Cannot transfer focus because windows are on different displays."); 3523 #endif 3524 return false; 3525 } 3526 3527 bool found = false; 3528 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) { 3529 TouchState& state = mTouchStatesByDisplay.editValueAt(d); 3530 for (size_t i = 0; i < state.windows.size(); i++) { 3531 const TouchedWindow& touchedWindow = state.windows[i]; 3532 if (touchedWindow.windowHandle == fromWindowHandle) { 3533 int32_t oldTargetFlags = touchedWindow.targetFlags; 3534 BitSet32 pointerIds = touchedWindow.pointerIds; 3535 3536 state.windows.erase(state.windows.begin() + i); 3537 3538 int32_t newTargetFlags = oldTargetFlags 3539 & (InputTarget::FLAG_FOREGROUND 3540 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS); 3541 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds); 3542 3543 found = true; 3544 goto Found; 3545 } 3546 } 3547 } 3548 Found: 3549 3550 if (! found) { 3551 #if DEBUG_FOCUS 3552 ALOGD("Focus transfer failed because from window did not have focus."); 3553 #endif 3554 return false; 3555 } 3556 3557 3558 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken); 3559 sp<InputChannel> toChannel = getInputChannelLocked(toToken); 3560 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel); 3561 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel); 3562 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) { 3563 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex); 3564 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex); 3565 3566 fromConnection->inputState.copyPointerStateTo(toConnection->inputState); 3567 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, 3568 "transferring touch focus from this window to another window"); 3569 synthesizeCancelationEventsForConnectionLocked(fromConnection, options); 3570 } 3571 3572 #if DEBUG_FOCUS 3573 logDispatchStateLocked(); 3574 #endif 3575 } // release lock 3576 3577 // Wake up poll loop since it may need to make new input dispatching choices. 3578 mLooper->wake(); 3579 return true; 3580 } 3581 3582 void InputDispatcher::resetAndDropEverythingLocked(const char* reason) { 3583 #if DEBUG_FOCUS 3584 ALOGD("Resetting and dropping all events (%s).", reason); 3585 #endif 3586 3587 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason); 3588 synthesizeCancelationEventsForAllConnectionsLocked(options); 3589 3590 resetKeyRepeatLocked(); 3591 releasePendingEventLocked(); 3592 drainInboundQueueLocked(); 3593 resetANRTimeoutsLocked(); 3594 3595 mTouchStatesByDisplay.clear(); 3596 mLastHoverWindowHandle.clear(); 3597 mReplacedKeys.clear(); 3598 } 3599 3600 void InputDispatcher::logDispatchStateLocked() { 3601 std::string dump; 3602 dumpDispatchStateLocked(dump); 3603 3604 std::istringstream stream(dump); 3605 std::string line; 3606 3607 while (std::getline(stream, line, '\n')) { 3608 ALOGD("%s", line.c_str()); 3609 } 3610 } 3611 3612 void InputDispatcher::dumpDispatchStateLocked(std::string& dump) { 3613 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled)); 3614 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen)); 3615 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled)); 3616 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId); 3617 3618 if (!mFocusedApplicationHandlesByDisplay.empty()) { 3619 dump += StringPrintf(INDENT "FocusedApplications:\n"); 3620 for (auto& it : mFocusedApplicationHandlesByDisplay) { 3621 const int32_t displayId = it.first; 3622 const sp<InputApplicationHandle>& applicationHandle = it.second; 3623 dump += StringPrintf( 3624 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n", 3625 displayId, 3626 applicationHandle->getName().c_str(), 3627 applicationHandle->getDispatchingTimeout( 3628 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0); 3629 } 3630 } else { 3631 dump += StringPrintf(INDENT "FocusedApplications: <none>\n"); 3632 } 3633 3634 if (!mFocusedWindowHandlesByDisplay.empty()) { 3635 dump += StringPrintf(INDENT "FocusedWindows:\n"); 3636 for (auto& it : mFocusedWindowHandlesByDisplay) { 3637 const int32_t displayId = it.first; 3638 const sp<InputWindowHandle>& windowHandle = it.second; 3639 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", 3640 displayId, windowHandle->getName().c_str()); 3641 } 3642 } else { 3643 dump += StringPrintf(INDENT "FocusedWindows: <none>\n"); 3644 } 3645 3646 if (!mTouchStatesByDisplay.isEmpty()) { 3647 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n"); 3648 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) { 3649 const TouchState& state = mTouchStatesByDisplay.valueAt(i); 3650 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n", 3651 state.displayId, toString(state.down), toString(state.split), 3652 state.deviceId, state.source); 3653 if (!state.windows.empty()) { 3654 dump += INDENT3 "Windows:\n"; 3655 for (size_t i = 0; i < state.windows.size(); i++) { 3656 const TouchedWindow& touchedWindow = state.windows[i]; 3657 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n", 3658 i, touchedWindow.windowHandle->getName().c_str(), 3659 touchedWindow.pointerIds.value, 3660 touchedWindow.targetFlags); 3661 } 3662 } else { 3663 dump += INDENT3 "Windows: <none>\n"; 3664 } 3665 if (!state.portalWindows.empty()) { 3666 dump += INDENT3 "Portal windows:\n"; 3667 for (size_t i = 0; i < state.portalWindows.size(); i++) { 3668 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i]; 3669 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", 3670 i, portalWindowHandle->getName().c_str()); 3671 } 3672 } 3673 } 3674 } else { 3675 dump += INDENT "TouchStates: <no displays touched>\n"; 3676 } 3677 3678 if (!mWindowHandlesByDisplay.empty()) { 3679 for (auto& it : mWindowHandlesByDisplay) { 3680 const std::vector<sp<InputWindowHandle>> windowHandles = it.second; 3681 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first); 3682 if (!windowHandles.empty()) { 3683 dump += INDENT2 "Windows:\n"; 3684 for (size_t i = 0; i < windowHandles.size(); i++) { 3685 const sp<InputWindowHandle>& windowHandle = windowHandles[i]; 3686 const InputWindowInfo* windowInfo = windowHandle->getInfo(); 3687 3688 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, " 3689 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, " 3690 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, " 3691 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), " 3692 "touchableRegion=", 3693 i, windowInfo->name.c_str(), windowInfo->displayId, 3694 windowInfo->portalToDisplayId, 3695 toString(windowInfo->paused), 3696 toString(windowInfo->hasFocus), 3697 toString(windowInfo->hasWallpaper), 3698 toString(windowInfo->visible), 3699 toString(windowInfo->canReceiveKeys), 3700 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType, 3701 windowInfo->layer, 3702 windowInfo->frameLeft, windowInfo->frameTop, 3703 windowInfo->frameRight, windowInfo->frameBottom, 3704 windowInfo->globalScaleFactor, 3705 windowInfo->windowXScale, windowInfo->windowYScale); 3706 dumpRegion(dump, windowInfo->touchableRegion); 3707 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures); 3708 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n", 3709 windowInfo->ownerPid, windowInfo->ownerUid, 3710 windowInfo->dispatchingTimeout / 1000000.0); 3711 } 3712 } else { 3713 dump += INDENT2 "Windows: <none>\n"; 3714 } 3715 } 3716 } else { 3717 dump += INDENT "Displays: <none>\n"; 3718 } 3719 3720 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) { 3721 for (auto& it : mGlobalMonitorsByDisplay) { 3722 const std::vector<Monitor>& monitors = it.second; 3723 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first); 3724 dumpMonitors(dump, monitors); 3725 } 3726 for (auto& it : mGestureMonitorsByDisplay) { 3727 const std::vector<Monitor>& monitors = it.second; 3728 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first); 3729 dumpMonitors(dump, monitors); 3730 } 3731 } else { 3732 dump += INDENT "Monitors: <none>\n"; 3733 } 3734 3735 nsecs_t currentTime = now(); 3736 3737 // Dump recently dispatched or dropped events from oldest to newest. 3738 if (!mRecentQueue.isEmpty()) { 3739 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count()); 3740 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) { 3741 dump += INDENT2; 3742 entry->appendDescription(dump); 3743 dump += StringPrintf(", age=%0.1fms\n", 3744 (currentTime - entry->eventTime) * 0.000001f); 3745 } 3746 } else { 3747 dump += INDENT "RecentQueue: <empty>\n"; 3748 } 3749 3750 // Dump event currently being dispatched. 3751 if (mPendingEvent) { 3752 dump += INDENT "PendingEvent:\n"; 3753 dump += INDENT2; 3754 mPendingEvent->appendDescription(dump); 3755 dump += StringPrintf(", age=%0.1fms\n", 3756 (currentTime - mPendingEvent->eventTime) * 0.000001f); 3757 } else { 3758 dump += INDENT "PendingEvent: <none>\n"; 3759 } 3760 3761 // Dump inbound events from oldest to newest. 3762 if (!mInboundQueue.isEmpty()) { 3763 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count()); 3764 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) { 3765 dump += INDENT2; 3766 entry->appendDescription(dump); 3767 dump += StringPrintf(", age=%0.1fms\n", 3768 (currentTime - entry->eventTime) * 0.000001f); 3769 } 3770 } else { 3771 dump += INDENT "InboundQueue: <empty>\n"; 3772 } 3773 3774 if (!mReplacedKeys.isEmpty()) { 3775 dump += INDENT "ReplacedKeys:\n"; 3776 for (size_t i = 0; i < mReplacedKeys.size(); i++) { 3777 const KeyReplacement& replacement = mReplacedKeys.keyAt(i); 3778 int32_t newKeyCode = mReplacedKeys.valueAt(i); 3779 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", 3780 i, replacement.keyCode, replacement.deviceId, newKeyCode); 3781 } 3782 } else { 3783 dump += INDENT "ReplacedKeys: <empty>\n"; 3784 } 3785 3786 if (!mConnectionsByFd.isEmpty()) { 3787 dump += INDENT "Connections:\n"; 3788 for (size_t i = 0; i < mConnectionsByFd.size(); i++) { 3789 const sp<Connection>& connection = mConnectionsByFd.valueAt(i); 3790 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', " 3791 "status=%s, monitor=%s, inputPublisherBlocked=%s\n", 3792 i, connection->getInputChannelName().c_str(), 3793 connection->getWindowName().c_str(), 3794 connection->getStatusLabel(), toString(connection->monitor), 3795 toString(connection->inputPublisherBlocked)); 3796 3797 if (!connection->outboundQueue.isEmpty()) { 3798 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n", 3799 connection->outboundQueue.count()); 3800 for (DispatchEntry* entry = connection->outboundQueue.head; entry; 3801 entry = entry->next) { 3802 dump.append(INDENT4); 3803 entry->eventEntry->appendDescription(dump); 3804 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n", 3805 entry->targetFlags, entry->resolvedAction, 3806 (currentTime - entry->eventEntry->eventTime) * 0.000001f); 3807 } 3808 } else { 3809 dump += INDENT3 "OutboundQueue: <empty>\n"; 3810 } 3811 3812 if (!connection->waitQueue.isEmpty()) { 3813 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n", 3814 connection->waitQueue.count()); 3815 for (DispatchEntry* entry = connection->waitQueue.head; entry; 3816 entry = entry->next) { 3817 dump += INDENT4; 3818 entry->eventEntry->appendDescription(dump); 3819 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, " 3820 "age=%0.1fms, wait=%0.1fms\n", 3821 entry->targetFlags, entry->resolvedAction, 3822 (currentTime - entry->eventEntry->eventTime) * 0.000001f, 3823 (currentTime - entry->deliveryTime) * 0.000001f); 3824 } 3825 } else { 3826 dump += INDENT3 "WaitQueue: <empty>\n"; 3827 } 3828 } 3829 } else { 3830 dump += INDENT "Connections: <none>\n"; 3831 } 3832 3833 if (isAppSwitchPendingLocked()) { 3834 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n", 3835 (mAppSwitchDueTime - now()) / 1000000.0); 3836 } else { 3837 dump += INDENT "AppSwitch: not pending\n"; 3838 } 3839 3840 dump += INDENT "Configuration:\n"; 3841 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", 3842 mConfig.keyRepeatDelay * 0.000001f); 3843 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n", 3844 mConfig.keyRepeatTimeout * 0.000001f); 3845 } 3846 3847 void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) { 3848 const size_t numMonitors = monitors.size(); 3849 for (size_t i = 0; i < numMonitors; i++) { 3850 const Monitor& monitor = monitors[i]; 3851 const sp<InputChannel>& channel = monitor.inputChannel; 3852 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str()); 3853 dump += "\n"; 3854 } 3855 } 3856 3857 status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, 3858 int32_t displayId) { 3859 #if DEBUG_REGISTRATION 3860 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32, 3861 inputChannel->getName().c_str(), displayId); 3862 #endif 3863 3864 { // acquire lock 3865 std::scoped_lock _l(mLock); 3866 3867 if (getConnectionIndexLocked(inputChannel) >= 0) { 3868 ALOGW("Attempted to register already registered input channel '%s'", 3869 inputChannel->getName().c_str()); 3870 return BAD_VALUE; 3871 } 3872 3873 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/); 3874 3875 int fd = inputChannel->getFd(); 3876 mConnectionsByFd.add(fd, connection); 3877 mInputChannelsByToken[inputChannel->getToken()] = inputChannel; 3878 3879 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this); 3880 } // release lock 3881 3882 // Wake the looper because some connections have changed. 3883 mLooper->wake(); 3884 return OK; 3885 } 3886 3887 status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel, 3888 int32_t displayId, bool isGestureMonitor) { 3889 { // acquire lock 3890 std::scoped_lock _l(mLock); 3891 3892 if (displayId < 0) { 3893 ALOGW("Attempted to register input monitor without a specified display."); 3894 return BAD_VALUE; 3895 } 3896 3897 if (inputChannel->getToken() == nullptr) { 3898 ALOGW("Attempted to register input monitor without an identifying token."); 3899 return BAD_VALUE; 3900 } 3901 3902 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/); 3903 3904 const int fd = inputChannel->getFd(); 3905 mConnectionsByFd.add(fd, connection); 3906 mInputChannelsByToken[inputChannel->getToken()] = inputChannel; 3907 3908 auto& monitorsByDisplay = isGestureMonitor 3909 ? mGestureMonitorsByDisplay 3910 : mGlobalMonitorsByDisplay; 3911 monitorsByDisplay[displayId].emplace_back(inputChannel); 3912 3913 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this); 3914 3915 } 3916 // Wake the looper because some connections have changed. 3917 mLooper->wake(); 3918 return OK; 3919 } 3920 3921 status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) { 3922 #if DEBUG_REGISTRATION 3923 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str()); 3924 #endif 3925 3926 { // acquire lock 3927 std::scoped_lock _l(mLock); 3928 3929 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/); 3930 if (status) { 3931 return status; 3932 } 3933 } // release lock 3934 3935 // Wake the poll loop because removing the connection may have changed the current 3936 // synchronization state. 3937 mLooper->wake(); 3938 return OK; 3939 } 3940 3941 status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, 3942 bool notify) { 3943 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel); 3944 if (connectionIndex < 0) { 3945 ALOGW("Attempted to unregister already unregistered input channel '%s'", 3946 inputChannel->getName().c_str()); 3947 return BAD_VALUE; 3948 } 3949 3950 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex); 3951 mConnectionsByFd.removeItemsAt(connectionIndex); 3952 3953 mInputChannelsByToken.erase(inputChannel->getToken()); 3954 3955 if (connection->monitor) { 3956 removeMonitorChannelLocked(inputChannel); 3957 } 3958 3959 mLooper->removeFd(inputChannel->getFd()); 3960 3961 nsecs_t currentTime = now(); 3962 abortBrokenDispatchCycleLocked(currentTime, connection, notify); 3963 3964 connection->status = Connection::STATUS_ZOMBIE; 3965 return OK; 3966 } 3967 3968 void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) { 3969 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay); 3970 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay); 3971 } 3972 3973 void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel, 3974 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) { 3975 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end(); ) { 3976 std::vector<Monitor>& monitors = it->second; 3977 const size_t numMonitors = monitors.size(); 3978 for (size_t i = 0; i < numMonitors; i++) { 3979 if (monitors[i].inputChannel == inputChannel) { 3980 monitors.erase(monitors.begin() + i); 3981 break; 3982 } 3983 } 3984 if (monitors.empty()) { 3985 it = monitorsByDisplay.erase(it); 3986 } else { 3987 ++it; 3988 } 3989 } 3990 } 3991 3992 status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) { 3993 { // acquire lock 3994 std::scoped_lock _l(mLock); 3995 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token); 3996 3997 if (!foundDisplayId) { 3998 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token"); 3999 return BAD_VALUE; 4000 } 4001 int32_t displayId = foundDisplayId.value(); 4002 4003 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId); 4004 if (stateIndex < 0) { 4005 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId); 4006 return BAD_VALUE; 4007 } 4008 4009 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex); 4010 std::optional<int32_t> foundDeviceId; 4011 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) { 4012 if (touchedMonitor.monitor.inputChannel->getToken() == token) { 4013 foundDeviceId = state.deviceId; 4014 } 4015 } 4016 if (!foundDeviceId || !state.down) { 4017 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams." 4018 " Ignoring."); 4019 return BAD_VALUE; 4020 } 4021 int32_t deviceId = foundDeviceId.value(); 4022 4023 // Send cancel events to all the input channels we're stealing from. 4024 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, 4025 "gesture monitor stole pointer stream"); 4026 options.deviceId = deviceId; 4027 options.displayId = displayId; 4028 for (const TouchedWindow& window : state.windows) { 4029 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken()); 4030 synthesizeCancelationEventsForInputChannelLocked(channel, options); 4031 } 4032 // Then clear the current touch state so we stop dispatching to them as well. 4033 state.filterNonMonitors(); 4034 } 4035 return OK; 4036 } 4037 4038 4039 std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked( 4040 const sp<IBinder>& token) { 4041 for (const auto& it : mGestureMonitorsByDisplay) { 4042 const std::vector<Monitor>& monitors = it.second; 4043 for (const Monitor& monitor : monitors) { 4044 if (monitor.inputChannel->getToken() == token) { 4045 return it.first; 4046 } 4047 } 4048 } 4049 return std::nullopt; 4050 } 4051 4052 ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) { 4053 if (inputChannel == nullptr) { 4054 return -1; 4055 } 4056 4057 for (size_t i = 0; i < mConnectionsByFd.size(); i++) { 4058 sp<Connection> connection = mConnectionsByFd.valueAt(i); 4059 if (connection->inputChannel->getToken() == inputChannel->getToken()) { 4060 return i; 4061 } 4062 } 4063 4064 return -1; 4065 } 4066 4067 void InputDispatcher::onDispatchCycleFinishedLocked( 4068 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) { 4069 CommandEntry* commandEntry = postCommandLocked( 4070 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible); 4071 commandEntry->connection = connection; 4072 commandEntry->eventTime = currentTime; 4073 commandEntry->seq = seq; 4074 commandEntry->handled = handled; 4075 } 4076 4077 void InputDispatcher::onDispatchCycleBrokenLocked( 4078 nsecs_t currentTime, const sp<Connection>& connection) { 4079 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!", 4080 connection->getInputChannelName().c_str()); 4081 4082 CommandEntry* commandEntry = postCommandLocked( 4083 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible); 4084 commandEntry->connection = connection; 4085 } 4086 4087 void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus, 4088 const sp<InputWindowHandle>& newFocus) { 4089 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr; 4090 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr; 4091 CommandEntry* commandEntry = postCommandLocked( 4092 & InputDispatcher::doNotifyFocusChangedLockedInterruptible); 4093 commandEntry->oldToken = oldToken; 4094 commandEntry->newToken = newToken; 4095 } 4096 4097 void InputDispatcher::onANRLocked( 4098 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle, 4099 const sp<InputWindowHandle>& windowHandle, 4100 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) { 4101 float dispatchLatency = (currentTime - eventTime) * 0.000001f; 4102 float waitDuration = (currentTime - waitStartTime) * 0.000001f; 4103 ALOGI("Application is not responding: %s. " 4104 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s", 4105 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), 4106 dispatchLatency, waitDuration, reason); 4107 4108 // Capture a record of the InputDispatcher state at the time of the ANR. 4109 time_t t = time(nullptr); 4110 struct tm tm; 4111 localtime_r(&t, &tm); 4112 char timestr[64]; 4113 strftime(timestr, sizeof(timestr), "%F %T", &tm); 4114 mLastANRState.clear(); 4115 mLastANRState += INDENT "ANR:\n"; 4116 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr); 4117 mLastANRState += StringPrintf(INDENT2 "Window: %s\n", 4118 getApplicationWindowLabel(applicationHandle, windowHandle).c_str()); 4119 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency); 4120 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration); 4121 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason); 4122 dumpDispatchStateLocked(mLastANRState); 4123 4124 CommandEntry* commandEntry = postCommandLocked( 4125 & InputDispatcher::doNotifyANRLockedInterruptible); 4126 commandEntry->inputApplicationHandle = applicationHandle; 4127 commandEntry->inputChannel = windowHandle != nullptr ? 4128 getInputChannelLocked(windowHandle->getToken()) : nullptr; 4129 commandEntry->reason = reason; 4130 } 4131 4132 void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible ( 4133 CommandEntry* commandEntry) { 4134 mLock.unlock(); 4135 4136 mPolicy->notifyConfigurationChanged(commandEntry->eventTime); 4137 4138 mLock.lock(); 4139 } 4140 4141 void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible( 4142 CommandEntry* commandEntry) { 4143 sp<Connection> connection = commandEntry->connection; 4144 4145 if (connection->status != Connection::STATUS_ZOMBIE) { 4146 mLock.unlock(); 4147 4148 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken()); 4149 4150 mLock.lock(); 4151 } 4152 } 4153 4154 void InputDispatcher::doNotifyFocusChangedLockedInterruptible( 4155 CommandEntry* commandEntry) { 4156 sp<IBinder> oldToken = commandEntry->oldToken; 4157 sp<IBinder> newToken = commandEntry->newToken; 4158 mLock.unlock(); 4159 mPolicy->notifyFocusChanged(oldToken, newToken); 4160 mLock.lock(); 4161 } 4162 4163 void InputDispatcher::doNotifyANRLockedInterruptible( 4164 CommandEntry* commandEntry) { 4165 mLock.unlock(); 4166 4167 nsecs_t newTimeout = mPolicy->notifyANR( 4168 commandEntry->inputApplicationHandle, 4169 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr, 4170 commandEntry->reason); 4171 4172 mLock.lock(); 4173 4174 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, 4175 commandEntry->inputChannel); 4176 } 4177 4178 void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible( 4179 CommandEntry* commandEntry) { 4180 KeyEntry* entry = commandEntry->keyEntry; 4181 4182 KeyEvent event; 4183 initializeKeyEvent(&event, entry); 4184 4185 mLock.unlock(); 4186 4187 android::base::Timer t; 4188 sp<IBinder> token = commandEntry->inputChannel != nullptr ? 4189 commandEntry->inputChannel->getToken() : nullptr; 4190 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, 4191 &event, entry->policyFlags); 4192 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) { 4193 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms", 4194 std::to_string(t.duration().count()).c_str()); 4195 } 4196 4197 mLock.lock(); 4198 4199 if (delay < 0) { 4200 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP; 4201 } else if (!delay) { 4202 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE; 4203 } else { 4204 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER; 4205 entry->interceptKeyWakeupTime = now() + delay; 4206 } 4207 entry->release(); 4208 } 4209 4210 void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) { 4211 mLock.unlock(); 4212 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken); 4213 mLock.lock(); 4214 } 4215 4216 void InputDispatcher::doDispatchCycleFinishedLockedInterruptible( 4217 CommandEntry* commandEntry) { 4218 sp<Connection> connection = commandEntry->connection; 4219 nsecs_t finishTime = commandEntry->eventTime; 4220 uint32_t seq = commandEntry->seq; 4221 bool handled = commandEntry->handled; 4222 4223 // Handle post-event policy actions. 4224 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq); 4225 if (dispatchEntry) { 4226 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime; 4227 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) { 4228 std::string msg = 4229 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ", 4230 connection->getWindowName().c_str(), eventDuration * 0.000001f); 4231 dispatchEntry->eventEntry->appendDescription(msg); 4232 ALOGI("%s", msg.c_str()); 4233 } 4234 4235 bool restartEvent; 4236 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) { 4237 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry); 4238 restartEvent = afterKeyEventLockedInterruptible(connection, 4239 dispatchEntry, keyEntry, handled); 4240 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) { 4241 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry); 4242 restartEvent = afterMotionEventLockedInterruptible(connection, 4243 dispatchEntry, motionEntry, handled); 4244 } else { 4245 restartEvent = false; 4246 } 4247 4248 // Dequeue the event and start the next cycle. 4249 // Note that because the lock might have been released, it is possible that the 4250 // contents of the wait queue to have been drained, so we need to double-check 4251 // a few things. 4252 if (dispatchEntry == connection->findWaitQueueEntry(seq)) { 4253 connection->waitQueue.dequeue(dispatchEntry); 4254 traceWaitQueueLength(connection); 4255 if (restartEvent && connection->status == Connection::STATUS_NORMAL) { 4256 connection->outboundQueue.enqueueAtHead(dispatchEntry); 4257 traceOutboundQueueLength(connection); 4258 } else { 4259 releaseDispatchEntry(dispatchEntry); 4260 } 4261 } 4262 4263 // Start the next dispatch cycle for this connection. 4264 startDispatchCycleLocked(now(), connection); 4265 } 4266 } 4267 4268 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection, 4269 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) { 4270 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) { 4271 if (!handled) { 4272 // Report the key as unhandled, since the fallback was not handled. 4273 mReporter->reportUnhandledKey(keyEntry->sequenceNum); 4274 } 4275 return false; 4276 } 4277 4278 // Get the fallback key state. 4279 // Clear it out after dispatching the UP. 4280 int32_t originalKeyCode = keyEntry->keyCode; 4281 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode); 4282 if (keyEntry->action == AKEY_EVENT_ACTION_UP) { 4283 connection->inputState.removeFallbackKey(originalKeyCode); 4284 } 4285 4286 if (handled || !dispatchEntry->hasForegroundTarget()) { 4287 // If the application handles the original key for which we previously 4288 // generated a fallback or if the window is not a foreground window, 4289 // then cancel the associated fallback key, if any. 4290 if (fallbackKeyCode != -1) { 4291 // Dispatch the unhandled key to the policy with the cancel flag. 4292 #if DEBUG_OUTBOUND_EVENT_DETAILS 4293 ALOGD("Unhandled key event: Asking policy to cancel fallback action. " 4294 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", 4295 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, 4296 keyEntry->policyFlags); 4297 #endif 4298 KeyEvent event; 4299 initializeKeyEvent(&event, keyEntry); 4300 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED); 4301 4302 mLock.unlock(); 4303 4304 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), 4305 &event, keyEntry->policyFlags, &event); 4306 4307 mLock.lock(); 4308 4309 // Cancel the fallback key. 4310 if (fallbackKeyCode != AKEYCODE_UNKNOWN) { 4311 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS, 4312 "application handled the original non-fallback key " 4313 "or is no longer a foreground target, " 4314 "canceling previously dispatched fallback key"); 4315 options.keyCode = fallbackKeyCode; 4316 synthesizeCancelationEventsForConnectionLocked(connection, options); 4317 } 4318 connection->inputState.removeFallbackKey(originalKeyCode); 4319 } 4320 } else { 4321 // If the application did not handle a non-fallback key, first check 4322 // that we are in a good state to perform unhandled key event processing 4323 // Then ask the policy what to do with it. 4324 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN 4325 && keyEntry->repeatCount == 0; 4326 if (fallbackKeyCode == -1 && !initialDown) { 4327 #if DEBUG_OUTBOUND_EVENT_DETAILS 4328 ALOGD("Unhandled key event: Skipping unhandled key event processing " 4329 "since this is not an initial down. " 4330 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", 4331 originalKeyCode, keyEntry->action, keyEntry->repeatCount, 4332 keyEntry->policyFlags); 4333 #endif 4334 return false; 4335 } 4336 4337 // Dispatch the unhandled key to the policy. 4338 #if DEBUG_OUTBOUND_EVENT_DETAILS 4339 ALOGD("Unhandled key event: Asking policy to perform fallback action. " 4340 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", 4341 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, 4342 keyEntry->policyFlags); 4343 #endif 4344 KeyEvent event; 4345 initializeKeyEvent(&event, keyEntry); 4346 4347 mLock.unlock(); 4348 4349 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), 4350 &event, keyEntry->policyFlags, &event); 4351 4352 mLock.lock(); 4353 4354 if (connection->status != Connection::STATUS_NORMAL) { 4355 connection->inputState.removeFallbackKey(originalKeyCode); 4356 return false; 4357 } 4358 4359 // Latch the fallback keycode for this key on an initial down. 4360 // The fallback keycode cannot change at any other point in the lifecycle. 4361 if (initialDown) { 4362 if (fallback) { 4363 fallbackKeyCode = event.getKeyCode(); 4364 } else { 4365 fallbackKeyCode = AKEYCODE_UNKNOWN; 4366 } 4367 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode); 4368 } 4369 4370 ALOG_ASSERT(fallbackKeyCode != -1); 4371 4372 // Cancel the fallback key if the policy decides not to send it anymore. 4373 // We will continue to dispatch the key to the policy but we will no 4374 // longer dispatch a fallback key to the application. 4375 if (fallbackKeyCode != AKEYCODE_UNKNOWN 4376 && (!fallback || fallbackKeyCode != event.getKeyCode())) { 4377 #if DEBUG_OUTBOUND_EVENT_DETAILS 4378 if (fallback) { 4379 ALOGD("Unhandled key event: Policy requested to send key %d" 4380 "as a fallback for %d, but on the DOWN it had requested " 4381 "to send %d instead. Fallback canceled.", 4382 event.getKeyCode(), originalKeyCode, fallbackKeyCode); 4383 } else { 4384 ALOGD("Unhandled key event: Policy did not request fallback for %d, " 4385 "but on the DOWN it had requested to send %d. " 4386 "Fallback canceled.", 4387 originalKeyCode, fallbackKeyCode); 4388 } 4389 #endif 4390 4391 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS, 4392 "canceling fallback, policy no longer desires it"); 4393 options.keyCode = fallbackKeyCode; 4394 synthesizeCancelationEventsForConnectionLocked(connection, options); 4395 4396 fallback = false; 4397 fallbackKeyCode = AKEYCODE_UNKNOWN; 4398 if (keyEntry->action != AKEY_EVENT_ACTION_UP) { 4399 connection->inputState.setFallbackKey(originalKeyCode, 4400 fallbackKeyCode); 4401 } 4402 } 4403 4404 #if DEBUG_OUTBOUND_EVENT_DETAILS 4405 { 4406 std::string msg; 4407 const KeyedVector<int32_t, int32_t>& fallbackKeys = 4408 connection->inputState.getFallbackKeys(); 4409 for (size_t i = 0; i < fallbackKeys.size(); i++) { 4410 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), 4411 fallbackKeys.valueAt(i)); 4412 } 4413 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.", 4414 fallbackKeys.size(), msg.c_str()); 4415 } 4416 #endif 4417 4418 if (fallback) { 4419 // Restart the dispatch cycle using the fallback key. 4420 keyEntry->eventTime = event.getEventTime(); 4421 keyEntry->deviceId = event.getDeviceId(); 4422 keyEntry->source = event.getSource(); 4423 keyEntry->displayId = event.getDisplayId(); 4424 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK; 4425 keyEntry->keyCode = fallbackKeyCode; 4426 keyEntry->scanCode = event.getScanCode(); 4427 keyEntry->metaState = event.getMetaState(); 4428 keyEntry->repeatCount = event.getRepeatCount(); 4429 keyEntry->downTime = event.getDownTime(); 4430 keyEntry->syntheticRepeat = false; 4431 4432 #if DEBUG_OUTBOUND_EVENT_DETAILS 4433 ALOGD("Unhandled key event: Dispatching fallback key. " 4434 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x", 4435 originalKeyCode, fallbackKeyCode, keyEntry->metaState); 4436 #endif 4437 return true; // restart the event 4438 } else { 4439 #if DEBUG_OUTBOUND_EVENT_DETAILS 4440 ALOGD("Unhandled key event: No fallback key."); 4441 #endif 4442 4443 // Report the key as unhandled, since there is no fallback key. 4444 mReporter->reportUnhandledKey(keyEntry->sequenceNum); 4445 } 4446 } 4447 return false; 4448 } 4449 4450 bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection, 4451 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) { 4452 return false; 4453 } 4454 4455 void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) { 4456 mLock.unlock(); 4457 4458 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType); 4459 4460 mLock.lock(); 4461 } 4462 4463 void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) { 4464 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags, 4465 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount, 4466 entry->downTime, entry->eventTime); 4467 } 4468 4469 void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry, 4470 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) { 4471 // TODO Write some statistics about how long we spend waiting. 4472 } 4473 4474 void InputDispatcher::traceInboundQueueLengthLocked() { 4475 if (ATRACE_ENABLED()) { 4476 ATRACE_INT("iq", mInboundQueue.count()); 4477 } 4478 } 4479 4480 void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) { 4481 if (ATRACE_ENABLED()) { 4482 char counterName[40]; 4483 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str()); 4484 ATRACE_INT(counterName, connection->outboundQueue.count()); 4485 } 4486 } 4487 4488 void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) { 4489 if (ATRACE_ENABLED()) { 4490 char counterName[40]; 4491 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str()); 4492 ATRACE_INT(counterName, connection->waitQueue.count()); 4493 } 4494 } 4495 4496 void InputDispatcher::dump(std::string& dump) { 4497 std::scoped_lock _l(mLock); 4498 4499 dump += "Input Dispatcher State:\n"; 4500 dumpDispatchStateLocked(dump); 4501 4502 if (!mLastANRState.empty()) { 4503 dump += "\nInput Dispatcher State at time of last ANR:\n"; 4504 dump += mLastANRState; 4505 } 4506 } 4507 4508 void InputDispatcher::monitor() { 4509 // Acquire and release the lock to ensure that the dispatcher has not deadlocked. 4510 std::unique_lock _l(mLock); 4511 mLooper->wake(); 4512 mDispatcherIsAlive.wait(_l); 4513 } 4514 4515 4516 // --- InputDispatcher::InjectionState --- 4517 4518 InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) : 4519 refCount(1), 4520 injectorPid(injectorPid), injectorUid(injectorUid), 4521 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false), 4522 pendingForegroundDispatches(0) { 4523 } 4524 4525 InputDispatcher::InjectionState::~InjectionState() { 4526 } 4527 4528 void InputDispatcher::InjectionState::release() { 4529 refCount -= 1; 4530 if (refCount == 0) { 4531 delete this; 4532 } else { 4533 ALOG_ASSERT(refCount > 0); 4534 } 4535 } 4536 4537 4538 // --- InputDispatcher::EventEntry --- 4539 4540 InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type, 4541 nsecs_t eventTime, uint32_t policyFlags) : 4542 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime), 4543 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) { 4544 } 4545 4546 InputDispatcher::EventEntry::~EventEntry() { 4547 releaseInjectionState(); 4548 } 4549 4550 void InputDispatcher::EventEntry::release() { 4551 refCount -= 1; 4552 if (refCount == 0) { 4553 delete this; 4554 } else { 4555 ALOG_ASSERT(refCount > 0); 4556 } 4557 } 4558 4559 void InputDispatcher::EventEntry::releaseInjectionState() { 4560 if (injectionState) { 4561 injectionState->release(); 4562 injectionState = nullptr; 4563 } 4564 } 4565 4566 4567 // --- InputDispatcher::ConfigurationChangedEntry --- 4568 4569 InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry( 4570 uint32_t sequenceNum, nsecs_t eventTime) : 4571 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) { 4572 } 4573 4574 InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() { 4575 } 4576 4577 void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const { 4578 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags); 4579 } 4580 4581 4582 // --- InputDispatcher::DeviceResetEntry --- 4583 4584 InputDispatcher::DeviceResetEntry::DeviceResetEntry( 4585 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) : 4586 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0), 4587 deviceId(deviceId) { 4588 } 4589 4590 InputDispatcher::DeviceResetEntry::~DeviceResetEntry() { 4591 } 4592 4593 void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const { 4594 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x", 4595 deviceId, policyFlags); 4596 } 4597 4598 4599 // --- InputDispatcher::KeyEntry --- 4600 4601 InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime, 4602 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, 4603 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, 4604 int32_t repeatCount, nsecs_t downTime) : 4605 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags), 4606 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags), 4607 keyCode(keyCode), scanCode(scanCode), metaState(metaState), 4608 repeatCount(repeatCount), downTime(downTime), 4609 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN), 4610 interceptKeyWakeupTime(0) { 4611 } 4612 4613 InputDispatcher::KeyEntry::~KeyEntry() { 4614 } 4615 4616 void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const { 4617 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, " 4618 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, " 4619 "repeatCount=%d), policyFlags=0x%08x", 4620 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode, 4621 scanCode, metaState, repeatCount, policyFlags); 4622 } 4623 4624 void InputDispatcher::KeyEntry::recycle() { 4625 releaseInjectionState(); 4626 4627 dispatchInProgress = false; 4628 syntheticRepeat = false; 4629 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN; 4630 interceptKeyWakeupTime = 0; 4631 } 4632 4633 4634 // --- InputDispatcher::MotionEntry --- 4635 4636 InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, 4637 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, 4638 int32_t actionButton, 4639 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification, 4640 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime, 4641 uint32_t pointerCount, 4642 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, 4643 float xOffset, float yOffset) : 4644 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags), 4645 eventTime(eventTime), 4646 deviceId(deviceId), source(source), displayId(displayId), action(action), 4647 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState), 4648 classification(classification), edgeFlags(edgeFlags), 4649 xPrecision(xPrecision), yPrecision(yPrecision), 4650 downTime(downTime), pointerCount(pointerCount) { 4651 for (uint32_t i = 0; i < pointerCount; i++) { 4652 this->pointerProperties[i].copyFrom(pointerProperties[i]); 4653 this->pointerCoords[i].copyFrom(pointerCoords[i]); 4654 if (xOffset || yOffset) { 4655 this->pointerCoords[i].applyOffset(xOffset, yOffset); 4656 } 4657 } 4658 } 4659 4660 InputDispatcher::MotionEntry::~MotionEntry() { 4661 } 4662 4663 void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const { 4664 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 4665 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, " 4666 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[", 4667 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags, 4668 metaState, buttonState, motionClassificationToString(classification), edgeFlags, 4669 xPrecision, yPrecision); 4670 4671 for (uint32_t i = 0; i < pointerCount; i++) { 4672 if (i) { 4673 msg += ", "; 4674 } 4675 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id, 4676 pointerCoords[i].getX(), pointerCoords[i].getY()); 4677 } 4678 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags); 4679 } 4680 4681 4682 // --- InputDispatcher::DispatchEntry --- 4683 4684 volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic; 4685 4686 InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry, 4687 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor, 4688 float windowXScale, float windowYScale) : 4689 seq(nextSeq()), 4690 eventEntry(eventEntry), targetFlags(targetFlags), 4691 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor), 4692 windowXScale(windowXScale), windowYScale(windowYScale), 4693 deliveryTime(0), resolvedAction(0), resolvedFlags(0) { 4694 eventEntry->refCount += 1; 4695 } 4696 4697 InputDispatcher::DispatchEntry::~DispatchEntry() { 4698 eventEntry->release(); 4699 } 4700 4701 uint32_t InputDispatcher::DispatchEntry::nextSeq() { 4702 // Sequence number 0 is reserved and will never be returned. 4703 uint32_t seq; 4704 do { 4705 seq = android_atomic_inc(&sNextSeqAtomic); 4706 } while (!seq); 4707 return seq; 4708 } 4709 4710 4711 // --- InputDispatcher::InputState --- 4712 4713 InputDispatcher::InputState::InputState() { 4714 } 4715 4716 InputDispatcher::InputState::~InputState() { 4717 } 4718 4719 bool InputDispatcher::InputState::isNeutral() const { 4720 return mKeyMementos.empty() && mMotionMementos.empty(); 4721 } 4722 4723 bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source, 4724 int32_t displayId) const { 4725 for (const MotionMemento& memento : mMotionMementos) { 4726 if (memento.deviceId == deviceId 4727 && memento.source == source 4728 && memento.displayId == displayId 4729 && memento.hovering) { 4730 return true; 4731 } 4732 } 4733 return false; 4734 } 4735 4736 bool InputDispatcher::InputState::trackKey(const KeyEntry* entry, 4737 int32_t action, int32_t flags) { 4738 switch (action) { 4739 case AKEY_EVENT_ACTION_UP: { 4740 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) { 4741 for (size_t i = 0; i < mFallbackKeys.size(); ) { 4742 if (mFallbackKeys.valueAt(i) == entry->keyCode) { 4743 mFallbackKeys.removeItemsAt(i); 4744 } else { 4745 i += 1; 4746 } 4747 } 4748 } 4749 ssize_t index = findKeyMemento(entry); 4750 if (index >= 0) { 4751 mKeyMementos.erase(mKeyMementos.begin() + index); 4752 return true; 4753 } 4754 /* FIXME: We can't just drop the key up event because that prevents creating 4755 * popup windows that are automatically shown when a key is held and then 4756 * dismissed when the key is released. The problem is that the popup will 4757 * not have received the original key down, so the key up will be considered 4758 * to be inconsistent with its observed state. We could perhaps handle this 4759 * by synthesizing a key down but that will cause other problems. 4760 * 4761 * So for now, allow inconsistent key up events to be dispatched. 4762 * 4763 #if DEBUG_OUTBOUND_EVENT_DETAILS 4764 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, " 4765 "keyCode=%d, scanCode=%d", 4766 entry->deviceId, entry->source, entry->keyCode, entry->scanCode); 4767 #endif 4768 return false; 4769 */ 4770 return true; 4771 } 4772 4773 case AKEY_EVENT_ACTION_DOWN: { 4774 ssize_t index = findKeyMemento(entry); 4775 if (index >= 0) { 4776 mKeyMementos.erase(mKeyMementos.begin() + index); 4777 } 4778 addKeyMemento(entry, flags); 4779 return true; 4780 } 4781 4782 default: 4783 return true; 4784 } 4785 } 4786 4787 bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, 4788 int32_t action, int32_t flags) { 4789 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK; 4790 switch (actionMasked) { 4791 case AMOTION_EVENT_ACTION_UP: 4792 case AMOTION_EVENT_ACTION_CANCEL: { 4793 ssize_t index = findMotionMemento(entry, false /*hovering*/); 4794 if (index >= 0) { 4795 mMotionMementos.erase(mMotionMementos.begin() + index); 4796 return true; 4797 } 4798 #if DEBUG_OUTBOUND_EVENT_DETAILS 4799 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, " 4800 "displayId=%" PRId32 ", actionMasked=%d", 4801 entry->deviceId, entry->source, entry->displayId, actionMasked); 4802 #endif 4803 return false; 4804 } 4805 4806 case AMOTION_EVENT_ACTION_DOWN: { 4807 ssize_t index = findMotionMemento(entry, false /*hovering*/); 4808 if (index >= 0) { 4809 mMotionMementos.erase(mMotionMementos.begin() + index); 4810 } 4811 addMotionMemento(entry, flags, false /*hovering*/); 4812 return true; 4813 } 4814 4815 case AMOTION_EVENT_ACTION_POINTER_UP: 4816 case AMOTION_EVENT_ACTION_POINTER_DOWN: 4817 case AMOTION_EVENT_ACTION_MOVE: { 4818 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) { 4819 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to 4820 // generate cancellation events for these since they're based in relative rather than 4821 // absolute units. 4822 return true; 4823 } 4824 4825 ssize_t index = findMotionMemento(entry, false /*hovering*/); 4826 4827 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) { 4828 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all 4829 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any 4830 // other value and we need to track the motion so we can send cancellation events for 4831 // anything generating fallback events (e.g. DPad keys for joystick movements). 4832 if (index >= 0) { 4833 if (entry->pointerCoords[0].isEmpty()) { 4834 mMotionMementos.erase(mMotionMementos.begin() + index); 4835 } else { 4836 MotionMemento& memento = mMotionMementos[index]; 4837 memento.setPointers(entry); 4838 } 4839 } else if (!entry->pointerCoords[0].isEmpty()) { 4840 addMotionMemento(entry, flags, false /*hovering*/); 4841 } 4842 4843 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP. 4844 return true; 4845 } 4846 if (index >= 0) { 4847 MotionMemento& memento = mMotionMementos[index]; 4848 memento.setPointers(entry); 4849 return true; 4850 } 4851 #if DEBUG_OUTBOUND_EVENT_DETAILS 4852 ALOGD("Dropping inconsistent motion pointer up/down or move event: " 4853 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d", 4854 entry->deviceId, entry->source, entry->displayId, actionMasked); 4855 #endif 4856 return false; 4857 } 4858 4859 case AMOTION_EVENT_ACTION_HOVER_EXIT: { 4860 ssize_t index = findMotionMemento(entry, true /*hovering*/); 4861 if (index >= 0) { 4862 mMotionMementos.erase(mMotionMementos.begin() + index); 4863 return true; 4864 } 4865 #if DEBUG_OUTBOUND_EVENT_DETAILS 4866 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, " 4867 "displayId=%" PRId32, 4868 entry->deviceId, entry->source, entry->displayId); 4869 #endif 4870 return false; 4871 } 4872 4873 case AMOTION_EVENT_ACTION_HOVER_ENTER: 4874 case AMOTION_EVENT_ACTION_HOVER_MOVE: { 4875 ssize_t index = findMotionMemento(entry, true /*hovering*/); 4876 if (index >= 0) { 4877 mMotionMementos.erase(mMotionMementos.begin() + index); 4878 } 4879 addMotionMemento(entry, flags, true /*hovering*/); 4880 return true; 4881 } 4882 4883 default: 4884 return true; 4885 } 4886 } 4887 4888 ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const { 4889 for (size_t i = 0; i < mKeyMementos.size(); i++) { 4890 const KeyMemento& memento = mKeyMementos[i]; 4891 if (memento.deviceId == entry->deviceId 4892 && memento.source == entry->source 4893 && memento.displayId == entry->displayId 4894 && memento.keyCode == entry->keyCode 4895 && memento.scanCode == entry->scanCode) { 4896 return i; 4897 } 4898 } 4899 return -1; 4900 } 4901 4902 ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry, 4903 bool hovering) const { 4904 for (size_t i = 0; i < mMotionMementos.size(); i++) { 4905 const MotionMemento& memento = mMotionMementos[i]; 4906 if (memento.deviceId == entry->deviceId 4907 && memento.source == entry->source 4908 && memento.displayId == entry->displayId 4909 && memento.hovering == hovering) { 4910 return i; 4911 } 4912 } 4913 return -1; 4914 } 4915 4916 void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) { 4917 KeyMemento memento; 4918 memento.deviceId = entry->deviceId; 4919 memento.source = entry->source; 4920 memento.displayId = entry->displayId; 4921 memento.keyCode = entry->keyCode; 4922 memento.scanCode = entry->scanCode; 4923 memento.metaState = entry->metaState; 4924 memento.flags = flags; 4925 memento.downTime = entry->downTime; 4926 memento.policyFlags = entry->policyFlags; 4927 mKeyMementos.push_back(memento); 4928 } 4929 4930 void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry, 4931 int32_t flags, bool hovering) { 4932 MotionMemento memento; 4933 memento.deviceId = entry->deviceId; 4934 memento.source = entry->source; 4935 memento.displayId = entry->displayId; 4936 memento.flags = flags; 4937 memento.xPrecision = entry->xPrecision; 4938 memento.yPrecision = entry->yPrecision; 4939 memento.downTime = entry->downTime; 4940 memento.setPointers(entry); 4941 memento.hovering = hovering; 4942 memento.policyFlags = entry->policyFlags; 4943 mMotionMementos.push_back(memento); 4944 } 4945 4946 void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) { 4947 pointerCount = entry->pointerCount; 4948 for (uint32_t i = 0; i < entry->pointerCount; i++) { 4949 pointerProperties[i].copyFrom(entry->pointerProperties[i]); 4950 pointerCoords[i].copyFrom(entry->pointerCoords[i]); 4951 } 4952 } 4953 4954 void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime, 4955 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) { 4956 for (KeyMemento& memento : mKeyMementos) { 4957 if (shouldCancelKey(memento, options)) { 4958 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, 4959 memento.deviceId, memento.source, memento.displayId, memento.policyFlags, 4960 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED, 4961 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime)); 4962 } 4963 } 4964 4965 for (const MotionMemento& memento : mMotionMementos) { 4966 if (shouldCancelMotion(memento, options)) { 4967 const int32_t action = memento.hovering ? 4968 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL; 4969 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, 4970 memento.deviceId, memento.source, memento.displayId, memento.policyFlags, 4971 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/, 4972 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 4973 memento.xPrecision, memento.yPrecision, memento.downTime, 4974 memento.pointerCount, memento.pointerProperties, memento.pointerCoords, 4975 0 /*xOffset*/, 0 /*yOffset*/)); 4976 } 4977 } 4978 } 4979 4980 void InputDispatcher::InputState::clear() { 4981 mKeyMementos.clear(); 4982 mMotionMementos.clear(); 4983 mFallbackKeys.clear(); 4984 } 4985 4986 void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const { 4987 for (size_t i = 0; i < mMotionMementos.size(); i++) { 4988 const MotionMemento& memento = mMotionMementos[i]; 4989 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) { 4990 for (size_t j = 0; j < other.mMotionMementos.size(); ) { 4991 const MotionMemento& otherMemento = other.mMotionMementos[j]; 4992 if (memento.deviceId == otherMemento.deviceId 4993 && memento.source == otherMemento.source 4994 && memento.displayId == otherMemento.displayId) { 4995 other.mMotionMementos.erase(other.mMotionMementos.begin() + j); 4996 } else { 4997 j += 1; 4998 } 4999 } 5000 other.mMotionMementos.push_back(memento); 5001 } 5002 } 5003 } 5004 5005 int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) { 5006 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode); 5007 return index >= 0 ? mFallbackKeys.valueAt(index) : -1; 5008 } 5009 5010 void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode, 5011 int32_t fallbackKeyCode) { 5012 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode); 5013 if (index >= 0) { 5014 mFallbackKeys.replaceValueAt(index, fallbackKeyCode); 5015 } else { 5016 mFallbackKeys.add(originalKeyCode, fallbackKeyCode); 5017 } 5018 } 5019 5020 void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) { 5021 mFallbackKeys.removeItem(originalKeyCode); 5022 } 5023 5024 bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento, 5025 const CancelationOptions& options) { 5026 if (options.keyCode && memento.keyCode != options.keyCode.value()) { 5027 return false; 5028 } 5029 5030 if (options.deviceId && memento.deviceId != options.deviceId.value()) { 5031 return false; 5032 } 5033 5034 if (options.displayId && memento.displayId != options.displayId.value()) { 5035 return false; 5036 } 5037 5038 switch (options.mode) { 5039 case CancelationOptions::CANCEL_ALL_EVENTS: 5040 case CancelationOptions::CANCEL_NON_POINTER_EVENTS: 5041 return true; 5042 case CancelationOptions::CANCEL_FALLBACK_EVENTS: 5043 return memento.flags & AKEY_EVENT_FLAG_FALLBACK; 5044 default: 5045 return false; 5046 } 5047 } 5048 5049 bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento, 5050 const CancelationOptions& options) { 5051 if (options.deviceId && memento.deviceId != options.deviceId.value()) { 5052 return false; 5053 } 5054 5055 if (options.displayId && memento.displayId != options.displayId.value()) { 5056 return false; 5057 } 5058 5059 switch (options.mode) { 5060 case CancelationOptions::CANCEL_ALL_EVENTS: 5061 return true; 5062 case CancelationOptions::CANCEL_POINTER_EVENTS: 5063 return memento.source & AINPUT_SOURCE_CLASS_POINTER; 5064 case CancelationOptions::CANCEL_NON_POINTER_EVENTS: 5065 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER); 5066 default: 5067 return false; 5068 } 5069 } 5070 5071 5072 // --- InputDispatcher::Connection --- 5073 5074 InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) : 5075 status(STATUS_NORMAL), inputChannel(inputChannel), 5076 monitor(monitor), 5077 inputPublisher(inputChannel), inputPublisherBlocked(false) { 5078 } 5079 5080 InputDispatcher::Connection::~Connection() { 5081 } 5082 5083 const std::string InputDispatcher::Connection::getWindowName() const { 5084 if (inputChannel != nullptr) { 5085 return inputChannel->getName(); 5086 } 5087 if (monitor) { 5088 return "monitor"; 5089 } 5090 return "?"; 5091 } 5092 5093 const char* InputDispatcher::Connection::getStatusLabel() const { 5094 switch (status) { 5095 case STATUS_NORMAL: 5096 return "NORMAL"; 5097 5098 case STATUS_BROKEN: 5099 return "BROKEN"; 5100 5101 case STATUS_ZOMBIE: 5102 return "ZOMBIE"; 5103 5104 default: 5105 return "UNKNOWN"; 5106 } 5107 } 5108 5109 InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) { 5110 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) { 5111 if (entry->seq == seq) { 5112 return entry; 5113 } 5114 } 5115 return nullptr; 5116 } 5117 5118 // --- InputDispatcher::Monitor 5119 InputDispatcher::Monitor::Monitor(const sp<InputChannel>& inputChannel) : 5120 inputChannel(inputChannel) { 5121 } 5122 5123 5124 // --- InputDispatcher::CommandEntry --- 5125 // 5126 InputDispatcher::CommandEntry::CommandEntry(Command command) : 5127 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0), 5128 seq(0), handled(false) { 5129 } 5130 5131 InputDispatcher::CommandEntry::~CommandEntry() { 5132 } 5133 5134 // --- InputDispatcher::TouchedMonitor --- 5135 InputDispatcher::TouchedMonitor::TouchedMonitor(const Monitor& monitor, float xOffset, 5136 float yOffset) : monitor(monitor), xOffset(xOffset), yOffset(yOffset) { 5137 } 5138 5139 // --- InputDispatcher::TouchState --- 5140 5141 InputDispatcher::TouchState::TouchState() : 5142 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) { 5143 } 5144 5145 InputDispatcher::TouchState::~TouchState() { 5146 } 5147 5148 void InputDispatcher::TouchState::reset() { 5149 down = false; 5150 split = false; 5151 deviceId = -1; 5152 source = 0; 5153 displayId = ADISPLAY_ID_NONE; 5154 windows.clear(); 5155 portalWindows.clear(); 5156 gestureMonitors.clear(); 5157 } 5158 5159 void InputDispatcher::TouchState::copyFrom(const TouchState& other) { 5160 down = other.down; 5161 split = other.split; 5162 deviceId = other.deviceId; 5163 source = other.source; 5164 displayId = other.displayId; 5165 windows = other.windows; 5166 portalWindows = other.portalWindows; 5167 gestureMonitors = other.gestureMonitors; 5168 } 5169 5170 void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle, 5171 int32_t targetFlags, BitSet32 pointerIds) { 5172 if (targetFlags & InputTarget::FLAG_SPLIT) { 5173 split = true; 5174 } 5175 5176 for (size_t i = 0; i < windows.size(); i++) { 5177 TouchedWindow& touchedWindow = windows[i]; 5178 if (touchedWindow.windowHandle == windowHandle) { 5179 touchedWindow.targetFlags |= targetFlags; 5180 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { 5181 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS; 5182 } 5183 touchedWindow.pointerIds.value |= pointerIds.value; 5184 return; 5185 } 5186 } 5187 5188 TouchedWindow touchedWindow; 5189 touchedWindow.windowHandle = windowHandle; 5190 touchedWindow.targetFlags = targetFlags; 5191 touchedWindow.pointerIds = pointerIds; 5192 windows.push_back(touchedWindow); 5193 } 5194 5195 void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) { 5196 size_t numWindows = portalWindows.size(); 5197 for (size_t i = 0; i < numWindows; i++) { 5198 if (portalWindows[i] == windowHandle) { 5199 return; 5200 } 5201 } 5202 portalWindows.push_back(windowHandle); 5203 } 5204 5205 void InputDispatcher::TouchState::addGestureMonitors( 5206 const std::vector<TouchedMonitor>& newMonitors) { 5207 const size_t newSize = gestureMonitors.size() + newMonitors.size(); 5208 gestureMonitors.reserve(newSize); 5209 gestureMonitors.insert(std::end(gestureMonitors), 5210 std::begin(newMonitors), std::end(newMonitors)); 5211 } 5212 5213 void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) { 5214 for (size_t i = 0; i < windows.size(); i++) { 5215 if (windows[i].windowHandle == windowHandle) { 5216 windows.erase(windows.begin() + i); 5217 return; 5218 } 5219 } 5220 } 5221 5222 void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) { 5223 for (size_t i = 0; i < windows.size(); i++) { 5224 if (windows[i].windowHandle->getToken() == token) { 5225 windows.erase(windows.begin() + i); 5226 return; 5227 } 5228 } 5229 } 5230 5231 void InputDispatcher::TouchState::filterNonAsIsTouchWindows() { 5232 for (size_t i = 0 ; i < windows.size(); ) { 5233 TouchedWindow& window = windows[i]; 5234 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS 5235 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) { 5236 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK; 5237 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS; 5238 i += 1; 5239 } else { 5240 windows.erase(windows.begin() + i); 5241 } 5242 } 5243 } 5244 5245 void InputDispatcher::TouchState::filterNonMonitors() { 5246 windows.clear(); 5247 portalWindows.clear(); 5248 } 5249 5250 sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const { 5251 for (size_t i = 0; i < windows.size(); i++) { 5252 const TouchedWindow& window = windows[i]; 5253 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { 5254 return window.windowHandle; 5255 } 5256 } 5257 return nullptr; 5258 } 5259 5260 bool InputDispatcher::TouchState::isSlippery() const { 5261 // Must have exactly one foreground window. 5262 bool haveSlipperyForegroundWindow = false; 5263 for (const TouchedWindow& window : windows) { 5264 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { 5265 if (haveSlipperyForegroundWindow 5266 || !(window.windowHandle->getInfo()->layoutParamsFlags 5267 & InputWindowInfo::FLAG_SLIPPERY)) { 5268 return false; 5269 } 5270 haveSlipperyForegroundWindow = true; 5271 } 5272 } 5273 return haveSlipperyForegroundWindow; 5274 } 5275 5276 5277 // --- InputDispatcherThread --- 5278 5279 InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) : 5280 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) { 5281 } 5282 5283 InputDispatcherThread::~InputDispatcherThread() { 5284 } 5285 5286 bool InputDispatcherThread::threadLoop() { 5287 mDispatcher->dispatchOnce(); 5288 return true; 5289 } 5290 5291 } // namespace android 5292