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