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