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