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