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