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