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