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