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