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