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