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