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