InputDispatcher.cpp revision 278b525d25b852554015ec4f92862f9297b502fd
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 int32_t keyCode = args->keyCode; 2370 if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) { 2371 int32_t newKeyCode = AKEYCODE_UNKNOWN; 2372 if (keyCode == AKEYCODE_DEL) { 2373 newKeyCode = AKEYCODE_BACK; 2374 } else if (keyCode == AKEYCODE_ENTER) { 2375 newKeyCode = AKEYCODE_HOME; 2376 } 2377 if (newKeyCode != AKEYCODE_UNKNOWN) { 2378 AutoMutex _l(mLock); 2379 struct KeyReplacement replacement = {keyCode, args->deviceId}; 2380 mReplacedKeys.add(replacement, newKeyCode); 2381 keyCode = newKeyCode; 2382 metaState &= ~AMETA_META_ON; 2383 } 2384 } else if (args->action == AKEY_EVENT_ACTION_UP) { 2385 // In order to maintain a consistent stream of up and down events, check to see if the key 2386 // going up is one we've replaced in a down event and haven't yet replaced in an up event, 2387 // even if the modifier was released between the down and the up events. 2388 AutoMutex _l(mLock); 2389 struct KeyReplacement replacement = {keyCode, args->deviceId}; 2390 ssize_t index = mReplacedKeys.indexOfKey(replacement); 2391 keyCode = mReplacedKeys.valueAt(index); 2392 mReplacedKeys.removeItemsAt(index); 2393 metaState &= ~AMETA_META_ON; 2394 } 2395 2396 KeyEvent event; 2397 event.initialize(args->deviceId, args->source, args->action, 2398 flags, keyCode, args->scanCode, metaState, 0, 2399 args->downTime, args->eventTime); 2400 2401 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags); 2402 2403 bool needWake; 2404 { // acquire lock 2405 mLock.lock(); 2406 2407 if (shouldSendKeyToInputFilterLocked(args)) { 2408 mLock.unlock(); 2409 2410 policyFlags |= POLICY_FLAG_FILTERED; 2411 if (!mPolicy->filterInputEvent(&event, policyFlags)) { 2412 return; // event was consumed by the filter 2413 } 2414 2415 mLock.lock(); 2416 } 2417 2418 int32_t repeatCount = 0; 2419 KeyEntry* newEntry = new KeyEntry(args->eventTime, 2420 args->deviceId, args->source, policyFlags, 2421 args->action, flags, keyCode, args->scanCode, 2422 metaState, repeatCount, args->downTime); 2423 2424 needWake = enqueueInboundEventLocked(newEntry); 2425 mLock.unlock(); 2426 } // release lock 2427 2428 if (needWake) { 2429 mLooper->wake(); 2430 } 2431} 2432 2433bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) { 2434 return mInputFilterEnabled; 2435} 2436 2437void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) { 2438#if DEBUG_INBOUND_EVENT_DETAILS 2439 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, " 2440 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, " 2441 "xPrecision=%f, yPrecision=%f, downTime=%lld", 2442 args->eventTime, args->deviceId, args->source, args->policyFlags, 2443 args->action, args->flags, args->metaState, args->buttonState, 2444 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime); 2445 for (uint32_t i = 0; i < args->pointerCount; i++) { 2446 ALOGD(" Pointer %d: id=%d, toolType=%d, " 2447 "x=%f, y=%f, pressure=%f, size=%f, " 2448 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, " 2449 "orientation=%f", 2450 i, args->pointerProperties[i].id, 2451 args->pointerProperties[i].toolType, 2452 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X), 2453 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y), 2454 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), 2455 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE), 2456 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), 2457 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), 2458 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), 2459 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), 2460 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION)); 2461 } 2462#endif 2463 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) { 2464 return; 2465 } 2466 2467 uint32_t policyFlags = args->policyFlags; 2468 policyFlags |= POLICY_FLAG_TRUSTED; 2469 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags); 2470 2471 bool needWake; 2472 { // acquire lock 2473 mLock.lock(); 2474 2475 if (shouldSendMotionToInputFilterLocked(args)) { 2476 mLock.unlock(); 2477 2478 MotionEvent event; 2479 event.initialize(args->deviceId, args->source, args->action, args->flags, 2480 args->edgeFlags, args->metaState, args->buttonState, 0, 0, 2481 args->xPrecision, args->yPrecision, 2482 args->downTime, args->eventTime, 2483 args->pointerCount, args->pointerProperties, args->pointerCoords); 2484 2485 policyFlags |= POLICY_FLAG_FILTERED; 2486 if (!mPolicy->filterInputEvent(&event, policyFlags)) { 2487 return; // event was consumed by the filter 2488 } 2489 2490 mLock.lock(); 2491 } 2492 2493 // Just enqueue a new motion event. 2494 MotionEntry* newEntry = new MotionEntry(args->eventTime, 2495 args->deviceId, args->source, policyFlags, 2496 args->action, args->flags, args->metaState, args->buttonState, 2497 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime, 2498 args->displayId, 2499 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0); 2500 2501 needWake = enqueueInboundEventLocked(newEntry); 2502 mLock.unlock(); 2503 } // release lock 2504 2505 if (needWake) { 2506 mLooper->wake(); 2507 } 2508} 2509 2510bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) { 2511 // TODO: support sending secondary display events to input filter 2512 return mInputFilterEnabled && isMainDisplay(args->displayId); 2513} 2514 2515void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) { 2516#if DEBUG_INBOUND_EVENT_DETAILS 2517 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x", 2518 args->eventTime, args->policyFlags, 2519 args->switchValues, args->switchMask); 2520#endif 2521 2522 uint32_t policyFlags = args->policyFlags; 2523 policyFlags |= POLICY_FLAG_TRUSTED; 2524 mPolicy->notifySwitch(args->eventTime, 2525 args->switchValues, args->switchMask, policyFlags); 2526} 2527 2528void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) { 2529#if DEBUG_INBOUND_EVENT_DETAILS 2530 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d", 2531 args->eventTime, args->deviceId); 2532#endif 2533 2534 bool needWake; 2535 { // acquire lock 2536 AutoMutex _l(mLock); 2537 2538 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId); 2539 needWake = enqueueInboundEventLocked(newEntry); 2540 } // release lock 2541 2542 if (needWake) { 2543 mLooper->wake(); 2544 } 2545} 2546 2547int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId, 2548 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis, 2549 uint32_t policyFlags) { 2550#if DEBUG_INBOUND_EVENT_DETAILS 2551 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, " 2552 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x", 2553 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags); 2554#endif 2555 2556 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis); 2557 2558 policyFlags |= POLICY_FLAG_INJECTED; 2559 if (hasInjectionPermission(injectorPid, injectorUid)) { 2560 policyFlags |= POLICY_FLAG_TRUSTED; 2561 } 2562 2563 EventEntry* firstInjectedEntry; 2564 EventEntry* lastInjectedEntry; 2565 switch (event->getType()) { 2566 case AINPUT_EVENT_TYPE_KEY: { 2567 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event); 2568 int32_t action = keyEvent->getAction(); 2569 if (! validateKeyEvent(action)) { 2570 return INPUT_EVENT_INJECTION_FAILED; 2571 } 2572 2573 int32_t flags = keyEvent->getFlags(); 2574 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) { 2575 policyFlags |= POLICY_FLAG_VIRTUAL; 2576 } 2577 2578 if (!(policyFlags & POLICY_FLAG_FILTERED)) { 2579 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags); 2580 } 2581 2582 mLock.lock(); 2583 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(), 2584 keyEvent->getDeviceId(), keyEvent->getSource(), 2585 policyFlags, action, flags, 2586 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(), 2587 keyEvent->getRepeatCount(), keyEvent->getDownTime()); 2588 lastInjectedEntry = firstInjectedEntry; 2589 break; 2590 } 2591 2592 case AINPUT_EVENT_TYPE_MOTION: { 2593 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event); 2594 int32_t action = motionEvent->getAction(); 2595 size_t pointerCount = motionEvent->getPointerCount(); 2596 const PointerProperties* pointerProperties = motionEvent->getPointerProperties(); 2597 if (! validateMotionEvent(action, pointerCount, pointerProperties)) { 2598 return INPUT_EVENT_INJECTION_FAILED; 2599 } 2600 2601 if (!(policyFlags & POLICY_FLAG_FILTERED)) { 2602 nsecs_t eventTime = motionEvent->getEventTime(); 2603 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags); 2604 } 2605 2606 mLock.lock(); 2607 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes(); 2608 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords(); 2609 firstInjectedEntry = new MotionEntry(*sampleEventTimes, 2610 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags, 2611 action, motionEvent->getFlags(), 2612 motionEvent->getMetaState(), motionEvent->getButtonState(), 2613 motionEvent->getEdgeFlags(), 2614 motionEvent->getXPrecision(), motionEvent->getYPrecision(), 2615 motionEvent->getDownTime(), displayId, 2616 uint32_t(pointerCount), pointerProperties, samplePointerCoords, 2617 motionEvent->getXOffset(), motionEvent->getYOffset()); 2618 lastInjectedEntry = firstInjectedEntry; 2619 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) { 2620 sampleEventTimes += 1; 2621 samplePointerCoords += pointerCount; 2622 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes, 2623 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags, 2624 action, motionEvent->getFlags(), 2625 motionEvent->getMetaState(), motionEvent->getButtonState(), 2626 motionEvent->getEdgeFlags(), 2627 motionEvent->getXPrecision(), motionEvent->getYPrecision(), 2628 motionEvent->getDownTime(), displayId, 2629 uint32_t(pointerCount), pointerProperties, samplePointerCoords, 2630 motionEvent->getXOffset(), motionEvent->getYOffset()); 2631 lastInjectedEntry->next = nextInjectedEntry; 2632 lastInjectedEntry = nextInjectedEntry; 2633 } 2634 break; 2635 } 2636 2637 default: 2638 ALOGW("Cannot inject event of type %d", event->getType()); 2639 return INPUT_EVENT_INJECTION_FAILED; 2640 } 2641 2642 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid); 2643 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) { 2644 injectionState->injectionIsAsync = true; 2645 } 2646 2647 injectionState->refCount += 1; 2648 lastInjectedEntry->injectionState = injectionState; 2649 2650 bool needWake = false; 2651 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) { 2652 EventEntry* nextEntry = entry->next; 2653 needWake |= enqueueInboundEventLocked(entry); 2654 entry = nextEntry; 2655 } 2656 2657 mLock.unlock(); 2658 2659 if (needWake) { 2660 mLooper->wake(); 2661 } 2662 2663 int32_t injectionResult; 2664 { // acquire lock 2665 AutoMutex _l(mLock); 2666 2667 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) { 2668 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; 2669 } else { 2670 for (;;) { 2671 injectionResult = injectionState->injectionResult; 2672 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) { 2673 break; 2674 } 2675 2676 nsecs_t remainingTimeout = endTime - now(); 2677 if (remainingTimeout <= 0) { 2678#if DEBUG_INJECTION 2679 ALOGD("injectInputEvent - Timed out waiting for injection result " 2680 "to become available."); 2681#endif 2682 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT; 2683 break; 2684 } 2685 2686 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout); 2687 } 2688 2689 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED 2690 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) { 2691 while (injectionState->pendingForegroundDispatches != 0) { 2692#if DEBUG_INJECTION 2693 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.", 2694 injectionState->pendingForegroundDispatches); 2695#endif 2696 nsecs_t remainingTimeout = endTime - now(); 2697 if (remainingTimeout <= 0) { 2698#if DEBUG_INJECTION 2699 ALOGD("injectInputEvent - Timed out waiting for pending foreground " 2700 "dispatches to finish."); 2701#endif 2702 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT; 2703 break; 2704 } 2705 2706 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout); 2707 } 2708 } 2709 } 2710 2711 injectionState->release(); 2712 } // release lock 2713 2714#if DEBUG_INJECTION 2715 ALOGD("injectInputEvent - Finished with result %d. " 2716 "injectorPid=%d, injectorUid=%d", 2717 injectionResult, injectorPid, injectorUid); 2718#endif 2719 2720 return injectionResult; 2721} 2722 2723bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) { 2724 return injectorUid == 0 2725 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid); 2726} 2727 2728void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) { 2729 InjectionState* injectionState = entry->injectionState; 2730 if (injectionState) { 2731#if DEBUG_INJECTION 2732 ALOGD("Setting input event injection result to %d. " 2733 "injectorPid=%d, injectorUid=%d", 2734 injectionResult, injectionState->injectorPid, injectionState->injectorUid); 2735#endif 2736 2737 if (injectionState->injectionIsAsync 2738 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) { 2739 // Log the outcome since the injector did not wait for the injection result. 2740 switch (injectionResult) { 2741 case INPUT_EVENT_INJECTION_SUCCEEDED: 2742 ALOGV("Asynchronous input event injection succeeded."); 2743 break; 2744 case INPUT_EVENT_INJECTION_FAILED: 2745 ALOGW("Asynchronous input event injection failed."); 2746 break; 2747 case INPUT_EVENT_INJECTION_PERMISSION_DENIED: 2748 ALOGW("Asynchronous input event injection permission denied."); 2749 break; 2750 case INPUT_EVENT_INJECTION_TIMED_OUT: 2751 ALOGW("Asynchronous input event injection timed out."); 2752 break; 2753 } 2754 } 2755 2756 injectionState->injectionResult = injectionResult; 2757 mInjectionResultAvailableCondition.broadcast(); 2758 } 2759} 2760 2761void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) { 2762 InjectionState* injectionState = entry->injectionState; 2763 if (injectionState) { 2764 injectionState->pendingForegroundDispatches += 1; 2765 } 2766} 2767 2768void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) { 2769 InjectionState* injectionState = entry->injectionState; 2770 if (injectionState) { 2771 injectionState->pendingForegroundDispatches -= 1; 2772 2773 if (injectionState->pendingForegroundDispatches == 0) { 2774 mInjectionSyncFinishedCondition.broadcast(); 2775 } 2776 } 2777} 2778 2779sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked( 2780 const sp<InputChannel>& inputChannel) const { 2781 size_t numWindows = mWindowHandles.size(); 2782 for (size_t i = 0; i < numWindows; i++) { 2783 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i); 2784 if (windowHandle->getInputChannel() == inputChannel) { 2785 return windowHandle; 2786 } 2787 } 2788 return NULL; 2789} 2790 2791bool InputDispatcher::hasWindowHandleLocked( 2792 const sp<InputWindowHandle>& windowHandle) const { 2793 size_t numWindows = mWindowHandles.size(); 2794 for (size_t i = 0; i < numWindows; i++) { 2795 if (mWindowHandles.itemAt(i) == windowHandle) { 2796 return true; 2797 } 2798 } 2799 return false; 2800} 2801 2802void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) { 2803#if DEBUG_FOCUS 2804 ALOGD("setInputWindows"); 2805#endif 2806 { // acquire lock 2807 AutoMutex _l(mLock); 2808 2809 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles; 2810 mWindowHandles = inputWindowHandles; 2811 2812 sp<InputWindowHandle> newFocusedWindowHandle; 2813 bool foundHoveredWindow = false; 2814 for (size_t i = 0; i < mWindowHandles.size(); i++) { 2815 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i); 2816 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) { 2817 mWindowHandles.removeAt(i--); 2818 continue; 2819 } 2820 if (windowHandle->getInfo()->hasFocus) { 2821 newFocusedWindowHandle = windowHandle; 2822 } 2823 if (windowHandle == mLastHoverWindowHandle) { 2824 foundHoveredWindow = true; 2825 } 2826 } 2827 2828 if (!foundHoveredWindow) { 2829 mLastHoverWindowHandle = NULL; 2830 } 2831 2832 if (mFocusedWindowHandle != newFocusedWindowHandle) { 2833 if (mFocusedWindowHandle != NULL) { 2834#if DEBUG_FOCUS 2835 ALOGD("Focus left window: %s", 2836 mFocusedWindowHandle->getName().string()); 2837#endif 2838 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel(); 2839 if (focusedInputChannel != NULL) { 2840 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, 2841 "focus left window"); 2842 synthesizeCancelationEventsForInputChannelLocked( 2843 focusedInputChannel, options); 2844 } 2845 } 2846 if (newFocusedWindowHandle != NULL) { 2847#if DEBUG_FOCUS 2848 ALOGD("Focus entered window: %s", 2849 newFocusedWindowHandle->getName().string()); 2850#endif 2851 } 2852 mFocusedWindowHandle = newFocusedWindowHandle; 2853 } 2854 2855 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) { 2856 TouchState& state = mTouchStatesByDisplay.editValueAt(d); 2857 for (size_t i = 0; i < state.windows.size(); i++) { 2858 TouchedWindow& touchedWindow = state.windows.editItemAt(i); 2859 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) { 2860#if DEBUG_FOCUS 2861 ALOGD("Touched window was removed: %s", 2862 touchedWindow.windowHandle->getName().string()); 2863#endif 2864 sp<InputChannel> touchedInputChannel = 2865 touchedWindow.windowHandle->getInputChannel(); 2866 if (touchedInputChannel != NULL) { 2867 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, 2868 "touched window was removed"); 2869 synthesizeCancelationEventsForInputChannelLocked( 2870 touchedInputChannel, options); 2871 } 2872 state.windows.removeAt(i--); 2873 } 2874 } 2875 } 2876 2877 // Release information for windows that are no longer present. 2878 // This ensures that unused input channels are released promptly. 2879 // Otherwise, they might stick around until the window handle is destroyed 2880 // which might not happen until the next GC. 2881 for (size_t i = 0; i < oldWindowHandles.size(); i++) { 2882 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i); 2883 if (!hasWindowHandleLocked(oldWindowHandle)) { 2884#if DEBUG_FOCUS 2885 ALOGD("Window went away: %s", oldWindowHandle->getName().string()); 2886#endif 2887 oldWindowHandle->releaseInfo(); 2888 } 2889 } 2890 } // release lock 2891 2892 // Wake up poll loop since it may need to make new input dispatching choices. 2893 mLooper->wake(); 2894} 2895 2896void InputDispatcher::setFocusedApplication( 2897 const sp<InputApplicationHandle>& inputApplicationHandle) { 2898#if DEBUG_FOCUS 2899 ALOGD("setFocusedApplication"); 2900#endif 2901 { // acquire lock 2902 AutoMutex _l(mLock); 2903 2904 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) { 2905 if (mFocusedApplicationHandle != inputApplicationHandle) { 2906 if (mFocusedApplicationHandle != NULL) { 2907 resetANRTimeoutsLocked(); 2908 mFocusedApplicationHandle->releaseInfo(); 2909 } 2910 mFocusedApplicationHandle = inputApplicationHandle; 2911 } 2912 } else if (mFocusedApplicationHandle != NULL) { 2913 resetANRTimeoutsLocked(); 2914 mFocusedApplicationHandle->releaseInfo(); 2915 mFocusedApplicationHandle.clear(); 2916 } 2917 2918#if DEBUG_FOCUS 2919 //logDispatchStateLocked(); 2920#endif 2921 } // release lock 2922 2923 // Wake up poll loop since it may need to make new input dispatching choices. 2924 mLooper->wake(); 2925} 2926 2927void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) { 2928#if DEBUG_FOCUS 2929 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen); 2930#endif 2931 2932 bool changed; 2933 { // acquire lock 2934 AutoMutex _l(mLock); 2935 2936 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) { 2937 if (mDispatchFrozen && !frozen) { 2938 resetANRTimeoutsLocked(); 2939 } 2940 2941 if (mDispatchEnabled && !enabled) { 2942 resetAndDropEverythingLocked("dispatcher is being disabled"); 2943 } 2944 2945 mDispatchEnabled = enabled; 2946 mDispatchFrozen = frozen; 2947 changed = true; 2948 } else { 2949 changed = false; 2950 } 2951 2952#if DEBUG_FOCUS 2953 //logDispatchStateLocked(); 2954#endif 2955 } // release lock 2956 2957 if (changed) { 2958 // Wake up poll loop since it may need to make new input dispatching choices. 2959 mLooper->wake(); 2960 } 2961} 2962 2963void InputDispatcher::setInputFilterEnabled(bool enabled) { 2964#if DEBUG_FOCUS 2965 ALOGD("setInputFilterEnabled: enabled=%d", enabled); 2966#endif 2967 2968 { // acquire lock 2969 AutoMutex _l(mLock); 2970 2971 if (mInputFilterEnabled == enabled) { 2972 return; 2973 } 2974 2975 mInputFilterEnabled = enabled; 2976 resetAndDropEverythingLocked("input filter is being enabled or disabled"); 2977 } // release lock 2978 2979 // Wake up poll loop since there might be work to do to drop everything. 2980 mLooper->wake(); 2981} 2982 2983bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel, 2984 const sp<InputChannel>& toChannel) { 2985#if DEBUG_FOCUS 2986 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s", 2987 fromChannel->getName().string(), toChannel->getName().string()); 2988#endif 2989 { // acquire lock 2990 AutoMutex _l(mLock); 2991 2992 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel); 2993 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel); 2994 if (fromWindowHandle == NULL || toWindowHandle == NULL) { 2995#if DEBUG_FOCUS 2996 ALOGD("Cannot transfer focus because from or to window not found."); 2997#endif 2998 return false; 2999 } 3000 if (fromWindowHandle == toWindowHandle) { 3001#if DEBUG_FOCUS 3002 ALOGD("Trivial transfer to same window."); 3003#endif 3004 return true; 3005 } 3006 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) { 3007#if DEBUG_FOCUS 3008 ALOGD("Cannot transfer focus because windows are on different displays."); 3009#endif 3010 return false; 3011 } 3012 3013 bool found = false; 3014 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) { 3015 TouchState& state = mTouchStatesByDisplay.editValueAt(d); 3016 for (size_t i = 0; i < state.windows.size(); i++) { 3017 const TouchedWindow& touchedWindow = state.windows[i]; 3018 if (touchedWindow.windowHandle == fromWindowHandle) { 3019 int32_t oldTargetFlags = touchedWindow.targetFlags; 3020 BitSet32 pointerIds = touchedWindow.pointerIds; 3021 3022 state.windows.removeAt(i); 3023 3024 int32_t newTargetFlags = oldTargetFlags 3025 & (InputTarget::FLAG_FOREGROUND 3026 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS); 3027 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds); 3028 3029 found = true; 3030 goto Found; 3031 } 3032 } 3033 } 3034Found: 3035 3036 if (! found) { 3037#if DEBUG_FOCUS 3038 ALOGD("Focus transfer failed because from window did not have focus."); 3039#endif 3040 return false; 3041 } 3042 3043 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel); 3044 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel); 3045 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) { 3046 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex); 3047 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex); 3048 3049 fromConnection->inputState.copyPointerStateTo(toConnection->inputState); 3050 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, 3051 "transferring touch focus from this window to another window"); 3052 synthesizeCancelationEventsForConnectionLocked(fromConnection, options); 3053 } 3054 3055#if DEBUG_FOCUS 3056 logDispatchStateLocked(); 3057#endif 3058 } // release lock 3059 3060 // Wake up poll loop since it may need to make new input dispatching choices. 3061 mLooper->wake(); 3062 return true; 3063} 3064 3065void InputDispatcher::resetAndDropEverythingLocked(const char* reason) { 3066#if DEBUG_FOCUS 3067 ALOGD("Resetting and dropping all events (%s).", reason); 3068#endif 3069 3070 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason); 3071 synthesizeCancelationEventsForAllConnectionsLocked(options); 3072 3073 resetKeyRepeatLocked(); 3074 releasePendingEventLocked(); 3075 drainInboundQueueLocked(); 3076 resetANRTimeoutsLocked(); 3077 3078 mTouchStatesByDisplay.clear(); 3079 mLastHoverWindowHandle.clear(); 3080 mReplacedKeys.clear(); 3081} 3082 3083void InputDispatcher::logDispatchStateLocked() { 3084 String8 dump; 3085 dumpDispatchStateLocked(dump); 3086 3087 char* text = dump.lockBuffer(dump.size()); 3088 char* start = text; 3089 while (*start != '\0') { 3090 char* end = strchr(start, '\n'); 3091 if (*end == '\n') { 3092 *(end++) = '\0'; 3093 } 3094 ALOGD("%s", start); 3095 start = end; 3096 } 3097} 3098 3099void InputDispatcher::dumpDispatchStateLocked(String8& dump) { 3100 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled); 3101 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen); 3102 3103 if (mFocusedApplicationHandle != NULL) { 3104 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n", 3105 mFocusedApplicationHandle->getName().string(), 3106 mFocusedApplicationHandle->getDispatchingTimeout( 3107 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0); 3108 } else { 3109 dump.append(INDENT "FocusedApplication: <null>\n"); 3110 } 3111 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n", 3112 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>"); 3113 3114 if (!mTouchStatesByDisplay.isEmpty()) { 3115 dump.appendFormat(INDENT "TouchStatesByDisplay:\n"); 3116 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) { 3117 const TouchState& state = mTouchStatesByDisplay.valueAt(i); 3118 dump.appendFormat(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n", 3119 state.displayId, toString(state.down), toString(state.split), 3120 state.deviceId, state.source); 3121 if (!state.windows.isEmpty()) { 3122 dump.append(INDENT3 "Windows:\n"); 3123 for (size_t i = 0; i < state.windows.size(); i++) { 3124 const TouchedWindow& touchedWindow = state.windows[i]; 3125 dump.appendFormat(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n", 3126 i, touchedWindow.windowHandle->getName().string(), 3127 touchedWindow.pointerIds.value, 3128 touchedWindow.targetFlags); 3129 } 3130 } else { 3131 dump.append(INDENT3 "Windows: <none>\n"); 3132 } 3133 } 3134 } else { 3135 dump.append(INDENT "TouchStates: <no displays touched>\n"); 3136 } 3137 3138 if (!mWindowHandles.isEmpty()) { 3139 dump.append(INDENT "Windows:\n"); 3140 for (size_t i = 0; i < mWindowHandles.size(); i++) { 3141 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i); 3142 const InputWindowInfo* windowInfo = windowHandle->getInfo(); 3143 3144 dump.appendFormat(INDENT2 "%zu: name='%s', displayId=%d, " 3145 "paused=%s, hasFocus=%s, hasWallpaper=%s, " 3146 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, " 3147 "frame=[%d,%d][%d,%d], scale=%f, " 3148 "touchableRegion=", 3149 i, windowInfo->name.string(), windowInfo->displayId, 3150 toString(windowInfo->paused), 3151 toString(windowInfo->hasFocus), 3152 toString(windowInfo->hasWallpaper), 3153 toString(windowInfo->visible), 3154 toString(windowInfo->canReceiveKeys), 3155 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType, 3156 windowInfo->layer, 3157 windowInfo->frameLeft, windowInfo->frameTop, 3158 windowInfo->frameRight, windowInfo->frameBottom, 3159 windowInfo->scaleFactor); 3160 dumpRegion(dump, windowInfo->touchableRegion); 3161 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures); 3162 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n", 3163 windowInfo->ownerPid, windowInfo->ownerUid, 3164 windowInfo->dispatchingTimeout / 1000000.0); 3165 } 3166 } else { 3167 dump.append(INDENT "Windows: <none>\n"); 3168 } 3169 3170 if (!mMonitoringChannels.isEmpty()) { 3171 dump.append(INDENT "MonitoringChannels:\n"); 3172 for (size_t i = 0; i < mMonitoringChannels.size(); i++) { 3173 const sp<InputChannel>& channel = mMonitoringChannels[i]; 3174 dump.appendFormat(INDENT2 "%zu: '%s'\n", i, channel->getName().string()); 3175 } 3176 } else { 3177 dump.append(INDENT "MonitoringChannels: <none>\n"); 3178 } 3179 3180 nsecs_t currentTime = now(); 3181 3182 // Dump recently dispatched or dropped events from oldest to newest. 3183 if (!mRecentQueue.isEmpty()) { 3184 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count()); 3185 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) { 3186 dump.append(INDENT2); 3187 entry->appendDescription(dump); 3188 dump.appendFormat(", age=%0.1fms\n", 3189 (currentTime - entry->eventTime) * 0.000001f); 3190 } 3191 } else { 3192 dump.append(INDENT "RecentQueue: <empty>\n"); 3193 } 3194 3195 // Dump event currently being dispatched. 3196 if (mPendingEvent) { 3197 dump.append(INDENT "PendingEvent:\n"); 3198 dump.append(INDENT2); 3199 mPendingEvent->appendDescription(dump); 3200 dump.appendFormat(", age=%0.1fms\n", 3201 (currentTime - mPendingEvent->eventTime) * 0.000001f); 3202 } else { 3203 dump.append(INDENT "PendingEvent: <none>\n"); 3204 } 3205 3206 // Dump inbound events from oldest to newest. 3207 if (!mInboundQueue.isEmpty()) { 3208 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count()); 3209 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) { 3210 dump.append(INDENT2); 3211 entry->appendDescription(dump); 3212 dump.appendFormat(", age=%0.1fms\n", 3213 (currentTime - entry->eventTime) * 0.000001f); 3214 } 3215 } else { 3216 dump.append(INDENT "InboundQueue: <empty>\n"); 3217 } 3218 3219 if (!mReplacedKeys.isEmpty()) { 3220 dump.append(INDENT "ReplacedKeys:\n"); 3221 for (size_t i = 0; i < mReplacedKeys.size(); i++) { 3222 const KeyReplacement& replacement = mReplacedKeys.keyAt(i); 3223 int32_t newKeyCode = mReplacedKeys.valueAt(i); 3224 dump.appendFormat(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", 3225 i, replacement.keyCode, replacement.deviceId, newKeyCode); 3226 } 3227 } else { 3228 dump.append(INDENT "ReplacedKeys: <empty>\n"); 3229 } 3230 3231 if (!mConnectionsByFd.isEmpty()) { 3232 dump.append(INDENT "Connections:\n"); 3233 for (size_t i = 0; i < mConnectionsByFd.size(); i++) { 3234 const sp<Connection>& connection = mConnectionsByFd.valueAt(i); 3235 dump.appendFormat(INDENT2 "%zu: channelName='%s', windowName='%s', " 3236 "status=%s, monitor=%s, inputPublisherBlocked=%s\n", 3237 i, connection->getInputChannelName(), connection->getWindowName(), 3238 connection->getStatusLabel(), toString(connection->monitor), 3239 toString(connection->inputPublisherBlocked)); 3240 3241 if (!connection->outboundQueue.isEmpty()) { 3242 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n", 3243 connection->outboundQueue.count()); 3244 for (DispatchEntry* entry = connection->outboundQueue.head; entry; 3245 entry = entry->next) { 3246 dump.append(INDENT4); 3247 entry->eventEntry->appendDescription(dump); 3248 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n", 3249 entry->targetFlags, entry->resolvedAction, 3250 (currentTime - entry->eventEntry->eventTime) * 0.000001f); 3251 } 3252 } else { 3253 dump.append(INDENT3 "OutboundQueue: <empty>\n"); 3254 } 3255 3256 if (!connection->waitQueue.isEmpty()) { 3257 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n", 3258 connection->waitQueue.count()); 3259 for (DispatchEntry* entry = connection->waitQueue.head; entry; 3260 entry = entry->next) { 3261 dump.append(INDENT4); 3262 entry->eventEntry->appendDescription(dump); 3263 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, " 3264 "age=%0.1fms, wait=%0.1fms\n", 3265 entry->targetFlags, entry->resolvedAction, 3266 (currentTime - entry->eventEntry->eventTime) * 0.000001f, 3267 (currentTime - entry->deliveryTime) * 0.000001f); 3268 } 3269 } else { 3270 dump.append(INDENT3 "WaitQueue: <empty>\n"); 3271 } 3272 } 3273 } else { 3274 dump.append(INDENT "Connections: <none>\n"); 3275 } 3276 3277 if (isAppSwitchPendingLocked()) { 3278 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n", 3279 (mAppSwitchDueTime - now()) / 1000000.0); 3280 } else { 3281 dump.append(INDENT "AppSwitch: not pending\n"); 3282 } 3283 3284 dump.append(INDENT "Configuration:\n"); 3285 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", 3286 mConfig.keyRepeatDelay * 0.000001f); 3287 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", 3288 mConfig.keyRepeatTimeout * 0.000001f); 3289} 3290 3291status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, 3292 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) { 3293#if DEBUG_REGISTRATION 3294 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(), 3295 toString(monitor)); 3296#endif 3297 3298 { // acquire lock 3299 AutoMutex _l(mLock); 3300 3301 if (getConnectionIndexLocked(inputChannel) >= 0) { 3302 ALOGW("Attempted to register already registered input channel '%s'", 3303 inputChannel->getName().string()); 3304 return BAD_VALUE; 3305 } 3306 3307 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor); 3308 3309 int fd = inputChannel->getFd(); 3310 mConnectionsByFd.add(fd, connection); 3311 3312 if (monitor) { 3313 mMonitoringChannels.push(inputChannel); 3314 } 3315 3316 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this); 3317 } // release lock 3318 3319 // Wake the looper because some connections have changed. 3320 mLooper->wake(); 3321 return OK; 3322} 3323 3324status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) { 3325#if DEBUG_REGISTRATION 3326 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string()); 3327#endif 3328 3329 { // acquire lock 3330 AutoMutex _l(mLock); 3331 3332 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/); 3333 if (status) { 3334 return status; 3335 } 3336 } // release lock 3337 3338 // Wake the poll loop because removing the connection may have changed the current 3339 // synchronization state. 3340 mLooper->wake(); 3341 return OK; 3342} 3343 3344status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, 3345 bool notify) { 3346 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel); 3347 if (connectionIndex < 0) { 3348 ALOGW("Attempted to unregister already unregistered input channel '%s'", 3349 inputChannel->getName().string()); 3350 return BAD_VALUE; 3351 } 3352 3353 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex); 3354 mConnectionsByFd.removeItemsAt(connectionIndex); 3355 3356 if (connection->monitor) { 3357 removeMonitorChannelLocked(inputChannel); 3358 } 3359 3360 mLooper->removeFd(inputChannel->getFd()); 3361 3362 nsecs_t currentTime = now(); 3363 abortBrokenDispatchCycleLocked(currentTime, connection, notify); 3364 3365 connection->status = Connection::STATUS_ZOMBIE; 3366 return OK; 3367} 3368 3369void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) { 3370 for (size_t i = 0; i < mMonitoringChannels.size(); i++) { 3371 if (mMonitoringChannels[i] == inputChannel) { 3372 mMonitoringChannels.removeAt(i); 3373 break; 3374 } 3375 } 3376} 3377 3378ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) { 3379 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd()); 3380 if (connectionIndex >= 0) { 3381 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex); 3382 if (connection->inputChannel.get() == inputChannel.get()) { 3383 return connectionIndex; 3384 } 3385 } 3386 3387 return -1; 3388} 3389 3390void InputDispatcher::onDispatchCycleFinishedLocked( 3391 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) { 3392 CommandEntry* commandEntry = postCommandLocked( 3393 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible); 3394 commandEntry->connection = connection; 3395 commandEntry->eventTime = currentTime; 3396 commandEntry->seq = seq; 3397 commandEntry->handled = handled; 3398} 3399 3400void InputDispatcher::onDispatchCycleBrokenLocked( 3401 nsecs_t currentTime, const sp<Connection>& connection) { 3402 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!", 3403 connection->getInputChannelName()); 3404 3405 CommandEntry* commandEntry = postCommandLocked( 3406 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible); 3407 commandEntry->connection = connection; 3408} 3409 3410void InputDispatcher::onANRLocked( 3411 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle, 3412 const sp<InputWindowHandle>& windowHandle, 3413 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) { 3414 float dispatchLatency = (currentTime - eventTime) * 0.000001f; 3415 float waitDuration = (currentTime - waitStartTime) * 0.000001f; 3416 ALOGI("Application is not responding: %s. " 3417 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s", 3418 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(), 3419 dispatchLatency, waitDuration, reason); 3420 3421 // Capture a record of the InputDispatcher state at the time of the ANR. 3422 time_t t = time(NULL); 3423 struct tm tm; 3424 localtime_r(&t, &tm); 3425 char timestr[64]; 3426 strftime(timestr, sizeof(timestr), "%F %T", &tm); 3427 mLastANRState.clear(); 3428 mLastANRState.append(INDENT "ANR:\n"); 3429 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr); 3430 mLastANRState.appendFormat(INDENT2 "Window: %s\n", 3431 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string()); 3432 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency); 3433 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration); 3434 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason); 3435 dumpDispatchStateLocked(mLastANRState); 3436 3437 CommandEntry* commandEntry = postCommandLocked( 3438 & InputDispatcher::doNotifyANRLockedInterruptible); 3439 commandEntry->inputApplicationHandle = applicationHandle; 3440 commandEntry->inputWindowHandle = windowHandle; 3441 commandEntry->reason = reason; 3442} 3443 3444void InputDispatcher::doNotifyConfigurationChangedInterruptible( 3445 CommandEntry* commandEntry) { 3446 mLock.unlock(); 3447 3448 mPolicy->notifyConfigurationChanged(commandEntry->eventTime); 3449 3450 mLock.lock(); 3451} 3452 3453void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible( 3454 CommandEntry* commandEntry) { 3455 sp<Connection> connection = commandEntry->connection; 3456 3457 if (connection->status != Connection::STATUS_ZOMBIE) { 3458 mLock.unlock(); 3459 3460 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle); 3461 3462 mLock.lock(); 3463 } 3464} 3465 3466void InputDispatcher::doNotifyANRLockedInterruptible( 3467 CommandEntry* commandEntry) { 3468 mLock.unlock(); 3469 3470 nsecs_t newTimeout = mPolicy->notifyANR( 3471 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle, 3472 commandEntry->reason); 3473 3474 mLock.lock(); 3475 3476 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, 3477 commandEntry->inputWindowHandle != NULL 3478 ? commandEntry->inputWindowHandle->getInputChannel() : NULL); 3479} 3480 3481void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible( 3482 CommandEntry* commandEntry) { 3483 KeyEntry* entry = commandEntry->keyEntry; 3484 3485 KeyEvent event; 3486 initializeKeyEvent(&event, entry); 3487 3488 mLock.unlock(); 3489 3490 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle, 3491 &event, entry->policyFlags); 3492 3493 mLock.lock(); 3494 3495 if (delay < 0) { 3496 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP; 3497 } else if (!delay) { 3498 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE; 3499 } else { 3500 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER; 3501 entry->interceptKeyWakeupTime = now() + delay; 3502 } 3503 entry->release(); 3504} 3505 3506void InputDispatcher::doDispatchCycleFinishedLockedInterruptible( 3507 CommandEntry* commandEntry) { 3508 sp<Connection> connection = commandEntry->connection; 3509 nsecs_t finishTime = commandEntry->eventTime; 3510 uint32_t seq = commandEntry->seq; 3511 bool handled = commandEntry->handled; 3512 3513 // Handle post-event policy actions. 3514 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq); 3515 if (dispatchEntry) { 3516 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime; 3517 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) { 3518 String8 msg; 3519 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ", 3520 connection->getWindowName(), eventDuration * 0.000001f); 3521 dispatchEntry->eventEntry->appendDescription(msg); 3522 ALOGI("%s", msg.string()); 3523 } 3524 3525 bool restartEvent; 3526 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) { 3527 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry); 3528 restartEvent = afterKeyEventLockedInterruptible(connection, 3529 dispatchEntry, keyEntry, handled); 3530 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) { 3531 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry); 3532 restartEvent = afterMotionEventLockedInterruptible(connection, 3533 dispatchEntry, motionEntry, handled); 3534 } else { 3535 restartEvent = false; 3536 } 3537 3538 // Dequeue the event and start the next cycle. 3539 // Note that because the lock might have been released, it is possible that the 3540 // contents of the wait queue to have been drained, so we need to double-check 3541 // a few things. 3542 if (dispatchEntry == connection->findWaitQueueEntry(seq)) { 3543 connection->waitQueue.dequeue(dispatchEntry); 3544 traceWaitQueueLengthLocked(connection); 3545 if (restartEvent && connection->status == Connection::STATUS_NORMAL) { 3546 connection->outboundQueue.enqueueAtHead(dispatchEntry); 3547 traceOutboundQueueLengthLocked(connection); 3548 } else { 3549 releaseDispatchEntryLocked(dispatchEntry); 3550 } 3551 } 3552 3553 // Start the next dispatch cycle for this connection. 3554 startDispatchCycleLocked(now(), connection); 3555 } 3556} 3557 3558bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection, 3559 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) { 3560 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) { 3561 // Get the fallback key state. 3562 // Clear it out after dispatching the UP. 3563 int32_t originalKeyCode = keyEntry->keyCode; 3564 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode); 3565 if (keyEntry->action == AKEY_EVENT_ACTION_UP) { 3566 connection->inputState.removeFallbackKey(originalKeyCode); 3567 } 3568 3569 if (handled || !dispatchEntry->hasForegroundTarget()) { 3570 // If the application handles the original key for which we previously 3571 // generated a fallback or if the window is not a foreground window, 3572 // then cancel the associated fallback key, if any. 3573 if (fallbackKeyCode != -1) { 3574 // Dispatch the unhandled key to the policy with the cancel flag. 3575#if DEBUG_OUTBOUND_EVENT_DETAILS 3576 ALOGD("Unhandled key event: Asking policy to cancel fallback action. " 3577 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", 3578 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, 3579 keyEntry->policyFlags); 3580#endif 3581 KeyEvent event; 3582 initializeKeyEvent(&event, keyEntry); 3583 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED); 3584 3585 mLock.unlock(); 3586 3587 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle, 3588 &event, keyEntry->policyFlags, &event); 3589 3590 mLock.lock(); 3591 3592 // Cancel the fallback key. 3593 if (fallbackKeyCode != AKEYCODE_UNKNOWN) { 3594 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS, 3595 "application handled the original non-fallback key " 3596 "or is no longer a foreground target, " 3597 "canceling previously dispatched fallback key"); 3598 options.keyCode = fallbackKeyCode; 3599 synthesizeCancelationEventsForConnectionLocked(connection, options); 3600 } 3601 connection->inputState.removeFallbackKey(originalKeyCode); 3602 } 3603 } else { 3604 // If the application did not handle a non-fallback key, first check 3605 // that we are in a good state to perform unhandled key event processing 3606 // Then ask the policy what to do with it. 3607 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN 3608 && keyEntry->repeatCount == 0; 3609 if (fallbackKeyCode == -1 && !initialDown) { 3610#if DEBUG_OUTBOUND_EVENT_DETAILS 3611 ALOGD("Unhandled key event: Skipping unhandled key event processing " 3612 "since this is not an initial down. " 3613 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", 3614 originalKeyCode, keyEntry->action, keyEntry->repeatCount, 3615 keyEntry->policyFlags); 3616#endif 3617 return false; 3618 } 3619 3620 // Dispatch the unhandled key to the policy. 3621#if DEBUG_OUTBOUND_EVENT_DETAILS 3622 ALOGD("Unhandled key event: Asking policy to perform fallback action. " 3623 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", 3624 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, 3625 keyEntry->policyFlags); 3626#endif 3627 KeyEvent event; 3628 initializeKeyEvent(&event, keyEntry); 3629 3630 mLock.unlock(); 3631 3632 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle, 3633 &event, keyEntry->policyFlags, &event); 3634 3635 mLock.lock(); 3636 3637 if (connection->status != Connection::STATUS_NORMAL) { 3638 connection->inputState.removeFallbackKey(originalKeyCode); 3639 return false; 3640 } 3641 3642 // Latch the fallback keycode for this key on an initial down. 3643 // The fallback keycode cannot change at any other point in the lifecycle. 3644 if (initialDown) { 3645 if (fallback) { 3646 fallbackKeyCode = event.getKeyCode(); 3647 } else { 3648 fallbackKeyCode = AKEYCODE_UNKNOWN; 3649 } 3650 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode); 3651 } 3652 3653 ALOG_ASSERT(fallbackKeyCode != -1); 3654 3655 // Cancel the fallback key if the policy decides not to send it anymore. 3656 // We will continue to dispatch the key to the policy but we will no 3657 // longer dispatch a fallback key to the application. 3658 if (fallbackKeyCode != AKEYCODE_UNKNOWN 3659 && (!fallback || fallbackKeyCode != event.getKeyCode())) { 3660#if DEBUG_OUTBOUND_EVENT_DETAILS 3661 if (fallback) { 3662 ALOGD("Unhandled key event: Policy requested to send key %d" 3663 "as a fallback for %d, but on the DOWN it had requested " 3664 "to send %d instead. Fallback canceled.", 3665 event.getKeyCode(), originalKeyCode, fallbackKeyCode); 3666 } else { 3667 ALOGD("Unhandled key event: Policy did not request fallback for %d, " 3668 "but on the DOWN it had requested to send %d. " 3669 "Fallback canceled.", 3670 originalKeyCode, fallbackKeyCode); 3671 } 3672#endif 3673 3674 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS, 3675 "canceling fallback, policy no longer desires it"); 3676 options.keyCode = fallbackKeyCode; 3677 synthesizeCancelationEventsForConnectionLocked(connection, options); 3678 3679 fallback = false; 3680 fallbackKeyCode = AKEYCODE_UNKNOWN; 3681 if (keyEntry->action != AKEY_EVENT_ACTION_UP) { 3682 connection->inputState.setFallbackKey(originalKeyCode, 3683 fallbackKeyCode); 3684 } 3685 } 3686 3687#if DEBUG_OUTBOUND_EVENT_DETAILS 3688 { 3689 String8 msg; 3690 const KeyedVector<int32_t, int32_t>& fallbackKeys = 3691 connection->inputState.getFallbackKeys(); 3692 for (size_t i = 0; i < fallbackKeys.size(); i++) { 3693 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i), 3694 fallbackKeys.valueAt(i)); 3695 } 3696 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.", 3697 fallbackKeys.size(), msg.string()); 3698 } 3699#endif 3700 3701 if (fallback) { 3702 // Restart the dispatch cycle using the fallback key. 3703 keyEntry->eventTime = event.getEventTime(); 3704 keyEntry->deviceId = event.getDeviceId(); 3705 keyEntry->source = event.getSource(); 3706 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK; 3707 keyEntry->keyCode = fallbackKeyCode; 3708 keyEntry->scanCode = event.getScanCode(); 3709 keyEntry->metaState = event.getMetaState(); 3710 keyEntry->repeatCount = event.getRepeatCount(); 3711 keyEntry->downTime = event.getDownTime(); 3712 keyEntry->syntheticRepeat = false; 3713 3714#if DEBUG_OUTBOUND_EVENT_DETAILS 3715 ALOGD("Unhandled key event: Dispatching fallback key. " 3716 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x", 3717 originalKeyCode, fallbackKeyCode, keyEntry->metaState); 3718#endif 3719 return true; // restart the event 3720 } else { 3721#if DEBUG_OUTBOUND_EVENT_DETAILS 3722 ALOGD("Unhandled key event: No fallback key."); 3723#endif 3724 } 3725 } 3726 } 3727 return false; 3728} 3729 3730bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection, 3731 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) { 3732 return false; 3733} 3734 3735void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) { 3736 mLock.unlock(); 3737 3738 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType); 3739 3740 mLock.lock(); 3741} 3742 3743void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) { 3744 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags, 3745 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount, 3746 entry->downTime, entry->eventTime); 3747} 3748 3749void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry, 3750 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) { 3751 // TODO Write some statistics about how long we spend waiting. 3752} 3753 3754void InputDispatcher::traceInboundQueueLengthLocked() { 3755 if (ATRACE_ENABLED()) { 3756 ATRACE_INT("iq", mInboundQueue.count()); 3757 } 3758} 3759 3760void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) { 3761 if (ATRACE_ENABLED()) { 3762 char counterName[40]; 3763 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName()); 3764 ATRACE_INT(counterName, connection->outboundQueue.count()); 3765 } 3766} 3767 3768void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) { 3769 if (ATRACE_ENABLED()) { 3770 char counterName[40]; 3771 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName()); 3772 ATRACE_INT(counterName, connection->waitQueue.count()); 3773 } 3774} 3775 3776void InputDispatcher::dump(String8& dump) { 3777 AutoMutex _l(mLock); 3778 3779 dump.append("Input Dispatcher State:\n"); 3780 dumpDispatchStateLocked(dump); 3781 3782 if (!mLastANRState.isEmpty()) { 3783 dump.append("\nInput Dispatcher State at time of last ANR:\n"); 3784 dump.append(mLastANRState); 3785 } 3786} 3787 3788void InputDispatcher::monitor() { 3789 // Acquire and release the lock to ensure that the dispatcher has not deadlocked. 3790 mLock.lock(); 3791 mLooper->wake(); 3792 mDispatcherIsAliveCondition.wait(mLock); 3793 mLock.unlock(); 3794} 3795 3796 3797// --- InputDispatcher::Queue --- 3798 3799template <typename T> 3800uint32_t InputDispatcher::Queue<T>::count() const { 3801 uint32_t result = 0; 3802 for (const T* entry = head; entry; entry = entry->next) { 3803 result += 1; 3804 } 3805 return result; 3806} 3807 3808 3809// --- InputDispatcher::InjectionState --- 3810 3811InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) : 3812 refCount(1), 3813 injectorPid(injectorPid), injectorUid(injectorUid), 3814 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false), 3815 pendingForegroundDispatches(0) { 3816} 3817 3818InputDispatcher::InjectionState::~InjectionState() { 3819} 3820 3821void InputDispatcher::InjectionState::release() { 3822 refCount -= 1; 3823 if (refCount == 0) { 3824 delete this; 3825 } else { 3826 ALOG_ASSERT(refCount > 0); 3827 } 3828} 3829 3830 3831// --- InputDispatcher::EventEntry --- 3832 3833InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) : 3834 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags), 3835 injectionState(NULL), dispatchInProgress(false) { 3836} 3837 3838InputDispatcher::EventEntry::~EventEntry() { 3839 releaseInjectionState(); 3840} 3841 3842void InputDispatcher::EventEntry::release() { 3843 refCount -= 1; 3844 if (refCount == 0) { 3845 delete this; 3846 } else { 3847 ALOG_ASSERT(refCount > 0); 3848 } 3849} 3850 3851void InputDispatcher::EventEntry::releaseInjectionState() { 3852 if (injectionState) { 3853 injectionState->release(); 3854 injectionState = NULL; 3855 } 3856} 3857 3858 3859// --- InputDispatcher::ConfigurationChangedEntry --- 3860 3861InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) : 3862 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) { 3863} 3864 3865InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() { 3866} 3867 3868void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const { 3869 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x", 3870 policyFlags); 3871} 3872 3873 3874// --- InputDispatcher::DeviceResetEntry --- 3875 3876InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) : 3877 EventEntry(TYPE_DEVICE_RESET, eventTime, 0), 3878 deviceId(deviceId) { 3879} 3880 3881InputDispatcher::DeviceResetEntry::~DeviceResetEntry() { 3882} 3883 3884void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const { 3885 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x", 3886 deviceId, policyFlags); 3887} 3888 3889 3890// --- InputDispatcher::KeyEntry --- 3891 3892InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime, 3893 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, 3894 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, 3895 int32_t repeatCount, nsecs_t downTime) : 3896 EventEntry(TYPE_KEY, eventTime, policyFlags), 3897 deviceId(deviceId), source(source), action(action), flags(flags), 3898 keyCode(keyCode), scanCode(scanCode), metaState(metaState), 3899 repeatCount(repeatCount), downTime(downTime), 3900 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN), 3901 interceptKeyWakeupTime(0) { 3902} 3903 3904InputDispatcher::KeyEntry::~KeyEntry() { 3905} 3906 3907void InputDispatcher::KeyEntry::appendDescription(String8& msg) const { 3908 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, " 3909 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, " 3910 "repeatCount=%d), policyFlags=0x%08x", 3911 deviceId, source, action, flags, keyCode, scanCode, metaState, 3912 repeatCount, policyFlags); 3913} 3914 3915void InputDispatcher::KeyEntry::recycle() { 3916 releaseInjectionState(); 3917 3918 dispatchInProgress = false; 3919 syntheticRepeat = false; 3920 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN; 3921 interceptKeyWakeupTime = 0; 3922} 3923 3924 3925// --- InputDispatcher::MotionEntry --- 3926 3927InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, 3928 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags, 3929 int32_t metaState, int32_t buttonState, 3930 int32_t edgeFlags, float xPrecision, float yPrecision, 3931 nsecs_t downTime, int32_t displayId, uint32_t pointerCount, 3932 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, 3933 float xOffset, float yOffset) : 3934 EventEntry(TYPE_MOTION, eventTime, policyFlags), 3935 eventTime(eventTime), 3936 deviceId(deviceId), source(source), action(action), flags(flags), 3937 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags), 3938 xPrecision(xPrecision), yPrecision(yPrecision), 3939 downTime(downTime), displayId(displayId), pointerCount(pointerCount) { 3940 for (uint32_t i = 0; i < pointerCount; i++) { 3941 this->pointerProperties[i].copyFrom(pointerProperties[i]); 3942 this->pointerCoords[i].copyFrom(pointerCoords[i]); 3943 if (xOffset || yOffset) { 3944 this->pointerCoords[i].applyOffset(xOffset, yOffset); 3945 } 3946 } 3947} 3948 3949InputDispatcher::MotionEntry::~MotionEntry() { 3950} 3951 3952void InputDispatcher::MotionEntry::appendDescription(String8& msg) const { 3953 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, " 3954 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, edgeFlags=0x%08x, " 3955 "xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[", 3956 deviceId, source, action, flags, metaState, buttonState, edgeFlags, 3957 xPrecision, yPrecision, displayId); 3958 for (uint32_t i = 0; i < pointerCount; i++) { 3959 if (i) { 3960 msg.append(", "); 3961 } 3962 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id, 3963 pointerCoords[i].getX(), pointerCoords[i].getY()); 3964 } 3965 msg.appendFormat("]), policyFlags=0x%08x", policyFlags); 3966} 3967 3968 3969// --- InputDispatcher::DispatchEntry --- 3970 3971volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic; 3972 3973InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry, 3974 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) : 3975 seq(nextSeq()), 3976 eventEntry(eventEntry), targetFlags(targetFlags), 3977 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor), 3978 deliveryTime(0), resolvedAction(0), resolvedFlags(0) { 3979 eventEntry->refCount += 1; 3980} 3981 3982InputDispatcher::DispatchEntry::~DispatchEntry() { 3983 eventEntry->release(); 3984} 3985 3986uint32_t InputDispatcher::DispatchEntry::nextSeq() { 3987 // Sequence number 0 is reserved and will never be returned. 3988 uint32_t seq; 3989 do { 3990 seq = android_atomic_inc(&sNextSeqAtomic); 3991 } while (!seq); 3992 return seq; 3993} 3994 3995 3996// --- InputDispatcher::InputState --- 3997 3998InputDispatcher::InputState::InputState() { 3999} 4000 4001InputDispatcher::InputState::~InputState() { 4002} 4003 4004bool InputDispatcher::InputState::isNeutral() const { 4005 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty(); 4006} 4007 4008bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source, 4009 int32_t displayId) const { 4010 for (size_t i = 0; i < mMotionMementos.size(); i++) { 4011 const MotionMemento& memento = mMotionMementos.itemAt(i); 4012 if (memento.deviceId == deviceId 4013 && memento.source == source 4014 && memento.displayId == displayId 4015 && memento.hovering) { 4016 return true; 4017 } 4018 } 4019 return false; 4020} 4021 4022bool InputDispatcher::InputState::trackKey(const KeyEntry* entry, 4023 int32_t action, int32_t flags) { 4024 switch (action) { 4025 case AKEY_EVENT_ACTION_UP: { 4026 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) { 4027 for (size_t i = 0; i < mFallbackKeys.size(); ) { 4028 if (mFallbackKeys.valueAt(i) == entry->keyCode) { 4029 mFallbackKeys.removeItemsAt(i); 4030 } else { 4031 i += 1; 4032 } 4033 } 4034 } 4035 ssize_t index = findKeyMemento(entry); 4036 if (index >= 0) { 4037 mKeyMementos.removeAt(index); 4038 return true; 4039 } 4040 /* FIXME: We can't just drop the key up event because that prevents creating 4041 * popup windows that are automatically shown when a key is held and then 4042 * dismissed when the key is released. The problem is that the popup will 4043 * not have received the original key down, so the key up will be considered 4044 * to be inconsistent with its observed state. We could perhaps handle this 4045 * by synthesizing a key down but that will cause other problems. 4046 * 4047 * So for now, allow inconsistent key up events to be dispatched. 4048 * 4049#if DEBUG_OUTBOUND_EVENT_DETAILS 4050 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, " 4051 "keyCode=%d, scanCode=%d", 4052 entry->deviceId, entry->source, entry->keyCode, entry->scanCode); 4053#endif 4054 return false; 4055 */ 4056 return true; 4057 } 4058 4059 case AKEY_EVENT_ACTION_DOWN: { 4060 ssize_t index = findKeyMemento(entry); 4061 if (index >= 0) { 4062 mKeyMementos.removeAt(index); 4063 } 4064 addKeyMemento(entry, flags); 4065 return true; 4066 } 4067 4068 default: 4069 return true; 4070 } 4071} 4072 4073bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, 4074 int32_t action, int32_t flags) { 4075 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK; 4076 switch (actionMasked) { 4077 case AMOTION_EVENT_ACTION_UP: 4078 case AMOTION_EVENT_ACTION_CANCEL: { 4079 ssize_t index = findMotionMemento(entry, false /*hovering*/); 4080 if (index >= 0) { 4081 mMotionMementos.removeAt(index); 4082 return true; 4083 } 4084#if DEBUG_OUTBOUND_EVENT_DETAILS 4085 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, " 4086 "actionMasked=%d", 4087 entry->deviceId, entry->source, actionMasked); 4088#endif 4089 return false; 4090 } 4091 4092 case AMOTION_EVENT_ACTION_DOWN: { 4093 ssize_t index = findMotionMemento(entry, false /*hovering*/); 4094 if (index >= 0) { 4095 mMotionMementos.removeAt(index); 4096 } 4097 addMotionMemento(entry, flags, false /*hovering*/); 4098 return true; 4099 } 4100 4101 case AMOTION_EVENT_ACTION_POINTER_UP: 4102 case AMOTION_EVENT_ACTION_POINTER_DOWN: 4103 case AMOTION_EVENT_ACTION_MOVE: { 4104 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) { 4105 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to 4106 // generate cancellation events for these since they're based in relative rather than 4107 // absolute units. 4108 return true; 4109 } 4110 4111 ssize_t index = findMotionMemento(entry, false /*hovering*/); 4112 4113 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) { 4114 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all 4115 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any 4116 // other value and we need to track the motion so we can send cancellation events for 4117 // anything generating fallback events (e.g. DPad keys for joystick movements). 4118 if (index >= 0) { 4119 if (entry->pointerCoords[0].isEmpty()) { 4120 mMotionMementos.removeAt(index); 4121 } else { 4122 MotionMemento& memento = mMotionMementos.editItemAt(index); 4123 memento.setPointers(entry); 4124 } 4125 } else if (!entry->pointerCoords[0].isEmpty()) { 4126 addMotionMemento(entry, flags, false /*hovering*/); 4127 } 4128 4129 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP. 4130 return true; 4131 } 4132 if (index >= 0) { 4133 MotionMemento& memento = mMotionMementos.editItemAt(index); 4134 memento.setPointers(entry); 4135 return true; 4136 } 4137#if DEBUG_OUTBOUND_EVENT_DETAILS 4138 ALOGD("Dropping inconsistent motion pointer up/down or move event: " 4139 "deviceId=%d, source=%08x, actionMasked=%d", 4140 entry->deviceId, entry->source, actionMasked); 4141#endif 4142 return false; 4143 } 4144 4145 case AMOTION_EVENT_ACTION_HOVER_EXIT: { 4146 ssize_t index = findMotionMemento(entry, true /*hovering*/); 4147 if (index >= 0) { 4148 mMotionMementos.removeAt(index); 4149 return true; 4150 } 4151#if DEBUG_OUTBOUND_EVENT_DETAILS 4152 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x", 4153 entry->deviceId, entry->source); 4154#endif 4155 return false; 4156 } 4157 4158 case AMOTION_EVENT_ACTION_HOVER_ENTER: 4159 case AMOTION_EVENT_ACTION_HOVER_MOVE: { 4160 ssize_t index = findMotionMemento(entry, true /*hovering*/); 4161 if (index >= 0) { 4162 mMotionMementos.removeAt(index); 4163 } 4164 addMotionMemento(entry, flags, true /*hovering*/); 4165 return true; 4166 } 4167 4168 default: 4169 return true; 4170 } 4171} 4172 4173ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const { 4174 for (size_t i = 0; i < mKeyMementos.size(); i++) { 4175 const KeyMemento& memento = mKeyMementos.itemAt(i); 4176 if (memento.deviceId == entry->deviceId 4177 && memento.source == entry->source 4178 && memento.keyCode == entry->keyCode 4179 && memento.scanCode == entry->scanCode) { 4180 return i; 4181 } 4182 } 4183 return -1; 4184} 4185 4186ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry, 4187 bool hovering) const { 4188 for (size_t i = 0; i < mMotionMementos.size(); i++) { 4189 const MotionMemento& memento = mMotionMementos.itemAt(i); 4190 if (memento.deviceId == entry->deviceId 4191 && memento.source == entry->source 4192 && memento.displayId == entry->displayId 4193 && memento.hovering == hovering) { 4194 return i; 4195 } 4196 } 4197 return -1; 4198} 4199 4200void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) { 4201 mKeyMementos.push(); 4202 KeyMemento& memento = mKeyMementos.editTop(); 4203 memento.deviceId = entry->deviceId; 4204 memento.source = entry->source; 4205 memento.keyCode = entry->keyCode; 4206 memento.scanCode = entry->scanCode; 4207 memento.metaState = entry->metaState; 4208 memento.flags = flags; 4209 memento.downTime = entry->downTime; 4210 memento.policyFlags = entry->policyFlags; 4211} 4212 4213void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry, 4214 int32_t flags, bool hovering) { 4215 mMotionMementos.push(); 4216 MotionMemento& memento = mMotionMementos.editTop(); 4217 memento.deviceId = entry->deviceId; 4218 memento.source = entry->source; 4219 memento.flags = flags; 4220 memento.xPrecision = entry->xPrecision; 4221 memento.yPrecision = entry->yPrecision; 4222 memento.downTime = entry->downTime; 4223 memento.displayId = entry->displayId; 4224 memento.setPointers(entry); 4225 memento.hovering = hovering; 4226 memento.policyFlags = entry->policyFlags; 4227} 4228 4229void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) { 4230 pointerCount = entry->pointerCount; 4231 for (uint32_t i = 0; i < entry->pointerCount; i++) { 4232 pointerProperties[i].copyFrom(entry->pointerProperties[i]); 4233 pointerCoords[i].copyFrom(entry->pointerCoords[i]); 4234 } 4235} 4236 4237void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime, 4238 Vector<EventEntry*>& outEvents, const CancelationOptions& options) { 4239 for (size_t i = 0; i < mKeyMementos.size(); i++) { 4240 const KeyMemento& memento = mKeyMementos.itemAt(i); 4241 if (shouldCancelKey(memento, options)) { 4242 outEvents.push(new KeyEntry(currentTime, 4243 memento.deviceId, memento.source, memento.policyFlags, 4244 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED, 4245 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime)); 4246 } 4247 } 4248 4249 for (size_t i = 0; i < mMotionMementos.size(); i++) { 4250 const MotionMemento& memento = mMotionMementos.itemAt(i); 4251 if (shouldCancelMotion(memento, options)) { 4252 outEvents.push(new MotionEntry(currentTime, 4253 memento.deviceId, memento.source, memento.policyFlags, 4254 memento.hovering 4255 ? AMOTION_EVENT_ACTION_HOVER_EXIT 4256 : AMOTION_EVENT_ACTION_CANCEL, 4257 memento.flags, 0, 0, 0, 4258 memento.xPrecision, memento.yPrecision, memento.downTime, 4259 memento.displayId, 4260 memento.pointerCount, memento.pointerProperties, memento.pointerCoords, 4261 0, 0)); 4262 } 4263 } 4264} 4265 4266void InputDispatcher::InputState::clear() { 4267 mKeyMementos.clear(); 4268 mMotionMementos.clear(); 4269 mFallbackKeys.clear(); 4270} 4271 4272void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const { 4273 for (size_t i = 0; i < mMotionMementos.size(); i++) { 4274 const MotionMemento& memento = mMotionMementos.itemAt(i); 4275 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) { 4276 for (size_t j = 0; j < other.mMotionMementos.size(); ) { 4277 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j); 4278 if (memento.deviceId == otherMemento.deviceId 4279 && memento.source == otherMemento.source 4280 && memento.displayId == otherMemento.displayId) { 4281 other.mMotionMementos.removeAt(j); 4282 } else { 4283 j += 1; 4284 } 4285 } 4286 other.mMotionMementos.push(memento); 4287 } 4288 } 4289} 4290 4291int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) { 4292 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode); 4293 return index >= 0 ? mFallbackKeys.valueAt(index) : -1; 4294} 4295 4296void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode, 4297 int32_t fallbackKeyCode) { 4298 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode); 4299 if (index >= 0) { 4300 mFallbackKeys.replaceValueAt(index, fallbackKeyCode); 4301 } else { 4302 mFallbackKeys.add(originalKeyCode, fallbackKeyCode); 4303 } 4304} 4305 4306void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) { 4307 mFallbackKeys.removeItem(originalKeyCode); 4308} 4309 4310bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento, 4311 const CancelationOptions& options) { 4312 if (options.keyCode != -1 && memento.keyCode != options.keyCode) { 4313 return false; 4314 } 4315 4316 if (options.deviceId != -1 && memento.deviceId != options.deviceId) { 4317 return false; 4318 } 4319 4320 switch (options.mode) { 4321 case CancelationOptions::CANCEL_ALL_EVENTS: 4322 case CancelationOptions::CANCEL_NON_POINTER_EVENTS: 4323 return true; 4324 case CancelationOptions::CANCEL_FALLBACK_EVENTS: 4325 return memento.flags & AKEY_EVENT_FLAG_FALLBACK; 4326 default: 4327 return false; 4328 } 4329} 4330 4331bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento, 4332 const CancelationOptions& options) { 4333 if (options.deviceId != -1 && memento.deviceId != options.deviceId) { 4334 return false; 4335 } 4336 4337 switch (options.mode) { 4338 case CancelationOptions::CANCEL_ALL_EVENTS: 4339 return true; 4340 case CancelationOptions::CANCEL_POINTER_EVENTS: 4341 return memento.source & AINPUT_SOURCE_CLASS_POINTER; 4342 case CancelationOptions::CANCEL_NON_POINTER_EVENTS: 4343 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER); 4344 default: 4345 return false; 4346 } 4347} 4348 4349 4350// --- InputDispatcher::Connection --- 4351 4352InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, 4353 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) : 4354 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle), 4355 monitor(monitor), 4356 inputPublisher(inputChannel), inputPublisherBlocked(false) { 4357} 4358 4359InputDispatcher::Connection::~Connection() { 4360} 4361 4362const char* InputDispatcher::Connection::getWindowName() const { 4363 if (inputWindowHandle != NULL) { 4364 return inputWindowHandle->getName().string(); 4365 } 4366 if (monitor) { 4367 return "monitor"; 4368 } 4369 return "?"; 4370} 4371 4372const char* InputDispatcher::Connection::getStatusLabel() const { 4373 switch (status) { 4374 case STATUS_NORMAL: 4375 return "NORMAL"; 4376 4377 case STATUS_BROKEN: 4378 return "BROKEN"; 4379 4380 case STATUS_ZOMBIE: 4381 return "ZOMBIE"; 4382 4383 default: 4384 return "UNKNOWN"; 4385 } 4386} 4387 4388InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) { 4389 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) { 4390 if (entry->seq == seq) { 4391 return entry; 4392 } 4393 } 4394 return NULL; 4395} 4396 4397 4398// --- InputDispatcher::CommandEntry --- 4399 4400InputDispatcher::CommandEntry::CommandEntry(Command command) : 4401 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), 4402 seq(0), handled(false) { 4403} 4404 4405InputDispatcher::CommandEntry::~CommandEntry() { 4406} 4407 4408 4409// --- InputDispatcher::TouchState --- 4410 4411InputDispatcher::TouchState::TouchState() : 4412 down(false), split(false), deviceId(-1), source(0), displayId(-1) { 4413} 4414 4415InputDispatcher::TouchState::~TouchState() { 4416} 4417 4418void InputDispatcher::TouchState::reset() { 4419 down = false; 4420 split = false; 4421 deviceId = -1; 4422 source = 0; 4423 displayId = -1; 4424 windows.clear(); 4425} 4426 4427void InputDispatcher::TouchState::copyFrom(const TouchState& other) { 4428 down = other.down; 4429 split = other.split; 4430 deviceId = other.deviceId; 4431 source = other.source; 4432 displayId = other.displayId; 4433 windows = other.windows; 4434} 4435 4436void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle, 4437 int32_t targetFlags, BitSet32 pointerIds) { 4438 if (targetFlags & InputTarget::FLAG_SPLIT) { 4439 split = true; 4440 } 4441 4442 for (size_t i = 0; i < windows.size(); i++) { 4443 TouchedWindow& touchedWindow = windows.editItemAt(i); 4444 if (touchedWindow.windowHandle == windowHandle) { 4445 touchedWindow.targetFlags |= targetFlags; 4446 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { 4447 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS; 4448 } 4449 touchedWindow.pointerIds.value |= pointerIds.value; 4450 return; 4451 } 4452 } 4453 4454 windows.push(); 4455 4456 TouchedWindow& touchedWindow = windows.editTop(); 4457 touchedWindow.windowHandle = windowHandle; 4458 touchedWindow.targetFlags = targetFlags; 4459 touchedWindow.pointerIds = pointerIds; 4460} 4461 4462void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) { 4463 for (size_t i = 0; i < windows.size(); i++) { 4464 if (windows.itemAt(i).windowHandle == windowHandle) { 4465 windows.removeAt(i); 4466 return; 4467 } 4468 } 4469} 4470 4471void InputDispatcher::TouchState::filterNonAsIsTouchWindows() { 4472 for (size_t i = 0 ; i < windows.size(); ) { 4473 TouchedWindow& window = windows.editItemAt(i); 4474 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS 4475 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) { 4476 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK; 4477 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS; 4478 i += 1; 4479 } else { 4480 windows.removeAt(i); 4481 } 4482 } 4483} 4484 4485sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const { 4486 for (size_t i = 0; i < windows.size(); i++) { 4487 const TouchedWindow& window = windows.itemAt(i); 4488 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { 4489 return window.windowHandle; 4490 } 4491 } 4492 return NULL; 4493} 4494 4495bool InputDispatcher::TouchState::isSlippery() const { 4496 // Must have exactly one foreground window. 4497 bool haveSlipperyForegroundWindow = false; 4498 for (size_t i = 0; i < windows.size(); i++) { 4499 const TouchedWindow& window = windows.itemAt(i); 4500 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { 4501 if (haveSlipperyForegroundWindow 4502 || !(window.windowHandle->getInfo()->layoutParamsFlags 4503 & InputWindowInfo::FLAG_SLIPPERY)) { 4504 return false; 4505 } 4506 haveSlipperyForegroundWindow = true; 4507 } 4508 } 4509 return haveSlipperyForegroundWindow; 4510} 4511 4512 4513// --- InputDispatcherThread --- 4514 4515InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) : 4516 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) { 4517} 4518 4519InputDispatcherThread::~InputDispatcherThread() { 4520} 4521 4522bool InputDispatcherThread::threadLoop() { 4523 mDispatcher->dispatchOnce(); 4524 return true; 4525} 4526 4527} // namespace android 4528