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