InputReader.cpp revision 61c08240585a6186b4bd879d87f238b3efc368f8
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 "InputReader" 18 19//#define LOG_NDEBUG 0 20 21// Log debug messages for each raw event received from the EventHub. 22#define DEBUG_RAW_EVENTS 0 23 24// Log debug messages about touch screen filtering hacks. 25#define DEBUG_HACKS 0 26 27// Log debug messages about virtual key processing. 28#define DEBUG_VIRTUAL_KEYS 0 29 30// Log debug messages about pointers. 31#define DEBUG_POINTERS 0 32 33// Log debug messages about pointer assignment calculations. 34#define DEBUG_POINTER_ASSIGNMENT 0 35 36// Log debug messages about gesture detection. 37#define DEBUG_GESTURES 0 38 39// Log debug messages about the vibrator. 40#define DEBUG_VIBRATOR 0 41 42#include "InputReader.h" 43 44#include <cutils/log.h> 45#include <androidfw/Keyboard.h> 46#include <androidfw/VirtualKeyMap.h> 47 48#include <stddef.h> 49#include <stdlib.h> 50#include <unistd.h> 51#include <errno.h> 52#include <limits.h> 53#include <math.h> 54 55#define INDENT " " 56#define INDENT2 " " 57#define INDENT3 " " 58#define INDENT4 " " 59#define INDENT5 " " 60 61namespace android { 62 63// --- Constants --- 64 65// Maximum number of slots supported when using the slot-based Multitouch Protocol B. 66static const size_t MAX_SLOTS = 32; 67 68// --- Static Functions --- 69 70template<typename T> 71inline static T abs(const T& value) { 72 return value < 0 ? - value : value; 73} 74 75template<typename T> 76inline static T min(const T& a, const T& b) { 77 return a < b ? a : b; 78} 79 80template<typename T> 81inline static void swap(T& a, T& b) { 82 T temp = a; 83 a = b; 84 b = temp; 85} 86 87inline static float avg(float x, float y) { 88 return (x + y) / 2; 89} 90 91inline static float distance(float x1, float y1, float x2, float y2) { 92 return hypotf(x1 - x2, y1 - y2); 93} 94 95inline static int32_t signExtendNybble(int32_t value) { 96 return value >= 8 ? value - 16 : value; 97} 98 99static inline const char* toString(bool value) { 100 return value ? "true" : "false"; 101} 102 103static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation, 104 const int32_t map[][4], size_t mapSize) { 105 if (orientation != DISPLAY_ORIENTATION_0) { 106 for (size_t i = 0; i < mapSize; i++) { 107 if (value == map[i][0]) { 108 return map[i][orientation]; 109 } 110 } 111 } 112 return value; 113} 114 115static const int32_t keyCodeRotationMap[][4] = { 116 // key codes enumerated counter-clockwise with the original (unrotated) key first 117 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation 118 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT }, 119 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN }, 120 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT }, 121 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP }, 122}; 123static const size_t keyCodeRotationMapSize = 124 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]); 125 126static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) { 127 return rotateValueUsingRotationMap(keyCode, orientation, 128 keyCodeRotationMap, keyCodeRotationMapSize); 129} 130 131static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) { 132 float temp; 133 switch (orientation) { 134 case DISPLAY_ORIENTATION_90: 135 temp = *deltaX; 136 *deltaX = *deltaY; 137 *deltaY = -temp; 138 break; 139 140 case DISPLAY_ORIENTATION_180: 141 *deltaX = -*deltaX; 142 *deltaY = -*deltaY; 143 break; 144 145 case DISPLAY_ORIENTATION_270: 146 temp = *deltaX; 147 *deltaX = -*deltaY; 148 *deltaY = temp; 149 break; 150 } 151} 152 153static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) { 154 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0; 155} 156 157// Returns true if the pointer should be reported as being down given the specified 158// button states. This determines whether the event is reported as a touch event. 159static bool isPointerDown(int32_t buttonState) { 160 return buttonState & 161 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY 162 | AMOTION_EVENT_BUTTON_TERTIARY); 163} 164 165static float calculateCommonVector(float a, float b) { 166 if (a > 0 && b > 0) { 167 return a < b ? a : b; 168 } else if (a < 0 && b < 0) { 169 return a > b ? a : b; 170 } else { 171 return 0; 172 } 173} 174 175static void synthesizeButtonKey(InputReaderContext* context, int32_t action, 176 nsecs_t when, int32_t deviceId, uint32_t source, 177 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState, 178 int32_t buttonState, int32_t keyCode) { 179 if ( 180 (action == AKEY_EVENT_ACTION_DOWN 181 && !(lastButtonState & buttonState) 182 && (currentButtonState & buttonState)) 183 || (action == AKEY_EVENT_ACTION_UP 184 && (lastButtonState & buttonState) 185 && !(currentButtonState & buttonState))) { 186 NotifyKeyArgs args(when, deviceId, source, policyFlags, 187 action, 0, keyCode, 0, context->getGlobalMetaState(), when); 188 context->getListener()->notifyKey(&args); 189 } 190} 191 192static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, 193 nsecs_t when, int32_t deviceId, uint32_t source, 194 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) { 195 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, 196 lastButtonState, currentButtonState, 197 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK); 198 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, 199 lastButtonState, currentButtonState, 200 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD); 201} 202 203 204// --- InputReaderConfiguration --- 205 206bool InputReaderConfiguration::getDisplayInfo(int32_t displayId, bool external, 207 int32_t* width, int32_t* height, int32_t* orientation) const { 208 if (displayId == 0) { 209 const DisplayInfo& info = external ? mExternalDisplay : mInternalDisplay; 210 if (info.width > 0 && info.height > 0) { 211 if (width) { 212 *width = info.width; 213 } 214 if (height) { 215 *height = info.height; 216 } 217 if (orientation) { 218 *orientation = info.orientation; 219 } 220 return true; 221 } 222 } 223 return false; 224} 225 226void InputReaderConfiguration::setDisplayInfo(int32_t displayId, bool external, 227 int32_t width, int32_t height, int32_t orientation) { 228 if (displayId == 0) { 229 DisplayInfo& info = external ? mExternalDisplay : mInternalDisplay; 230 info.width = width; 231 info.height = height; 232 info.orientation = orientation; 233 } 234} 235 236 237// --- InputReader --- 238 239InputReader::InputReader(const sp<EventHubInterface>& eventHub, 240 const sp<InputReaderPolicyInterface>& policy, 241 const sp<InputListenerInterface>& listener) : 242 mContext(this), mEventHub(eventHub), mPolicy(policy), 243 mGlobalMetaState(0), mGeneration(1), 244 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX), 245 mConfigurationChangesToRefresh(0) { 246 mQueuedListener = new QueuedInputListener(listener); 247 248 { // acquire lock 249 AutoMutex _l(mLock); 250 251 refreshConfigurationLocked(0); 252 updateGlobalMetaStateLocked(); 253 updateInputConfigurationLocked(); 254 } // release lock 255} 256 257InputReader::~InputReader() { 258 for (size_t i = 0; i < mDevices.size(); i++) { 259 delete mDevices.valueAt(i); 260 } 261} 262 263void InputReader::loopOnce() { 264 int32_t oldGeneration; 265 int32_t timeoutMillis; 266 bool inputDevicesChanged = false; 267 Vector<InputDeviceInfo> inputDevices; 268 { // acquire lock 269 AutoMutex _l(mLock); 270 271 oldGeneration = mGeneration; 272 timeoutMillis = -1; 273 274 uint32_t changes = mConfigurationChangesToRefresh; 275 if (changes) { 276 mConfigurationChangesToRefresh = 0; 277 timeoutMillis = 0; 278 refreshConfigurationLocked(changes); 279 } else if (mNextTimeout != LLONG_MAX) { 280 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); 281 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout); 282 } 283 } // release lock 284 285 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE); 286 287 { // acquire lock 288 AutoMutex _l(mLock); 289 mReaderIsAliveCondition.broadcast(); 290 291 if (count) { 292 processEventsLocked(mEventBuffer, count); 293 } 294 295 if (mNextTimeout != LLONG_MAX) { 296 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); 297 if (now >= mNextTimeout) { 298#if DEBUG_RAW_EVENTS 299 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f); 300#endif 301 mNextTimeout = LLONG_MAX; 302 timeoutExpiredLocked(now); 303 } 304 } 305 306 if (oldGeneration != mGeneration) { 307 inputDevicesChanged = true; 308 getInputDevicesLocked(inputDevices); 309 } 310 } // release lock 311 312 // Send out a message that the describes the changed input devices. 313 if (inputDevicesChanged) { 314 mPolicy->notifyInputDevicesChanged(inputDevices); 315 } 316 317 // Flush queued events out to the listener. 318 // This must happen outside of the lock because the listener could potentially call 319 // back into the InputReader's methods, such as getScanCodeState, or become blocked 320 // on another thread similarly waiting to acquire the InputReader lock thereby 321 // resulting in a deadlock. This situation is actually quite plausible because the 322 // listener is actually the input dispatcher, which calls into the window manager, 323 // which occasionally calls into the input reader. 324 mQueuedListener->flush(); 325} 326 327void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) { 328 for (const RawEvent* rawEvent = rawEvents; count;) { 329 int32_t type = rawEvent->type; 330 size_t batchSize = 1; 331 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) { 332 int32_t deviceId = rawEvent->deviceId; 333 while (batchSize < count) { 334 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT 335 || rawEvent[batchSize].deviceId != deviceId) { 336 break; 337 } 338 batchSize += 1; 339 } 340#if DEBUG_RAW_EVENTS 341 ALOGD("BatchSize: %d Count: %d", batchSize, count); 342#endif 343 processEventsForDeviceLocked(deviceId, rawEvent, batchSize); 344 } else { 345 switch (rawEvent->type) { 346 case EventHubInterface::DEVICE_ADDED: 347 addDeviceLocked(rawEvent->when, rawEvent->deviceId); 348 break; 349 case EventHubInterface::DEVICE_REMOVED: 350 removeDeviceLocked(rawEvent->when, rawEvent->deviceId); 351 break; 352 case EventHubInterface::FINISHED_DEVICE_SCAN: 353 handleConfigurationChangedLocked(rawEvent->when); 354 break; 355 default: 356 ALOG_ASSERT(false); // can't happen 357 break; 358 } 359 } 360 count -= batchSize; 361 rawEvent += batchSize; 362 } 363} 364 365void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) { 366 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 367 if (deviceIndex >= 0) { 368 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId); 369 return; 370 } 371 372 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId); 373 uint32_t classes = mEventHub->getDeviceClasses(deviceId); 374 375 InputDevice* device = createDeviceLocked(deviceId, identifier, classes); 376 device->configure(when, &mConfig, 0); 377 device->reset(when); 378 379 if (device->isIgnored()) { 380 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, 381 identifier.name.string()); 382 } else { 383 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, 384 identifier.name.string(), device->getSources()); 385 } 386 387 mDevices.add(deviceId, device); 388 bumpGenerationLocked(); 389} 390 391void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) { 392 InputDevice* device = NULL; 393 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 394 if (deviceIndex < 0) { 395 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId); 396 return; 397 } 398 399 device = mDevices.valueAt(deviceIndex); 400 mDevices.removeItemsAt(deviceIndex, 1); 401 bumpGenerationLocked(); 402 403 if (device->isIgnored()) { 404 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)", 405 device->getId(), device->getName().string()); 406 } else { 407 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x", 408 device->getId(), device->getName().string(), device->getSources()); 409 } 410 411 device->reset(when); 412 delete device; 413} 414 415InputDevice* InputReader::createDeviceLocked(int32_t deviceId, 416 const InputDeviceIdentifier& identifier, uint32_t classes) { 417 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(), 418 identifier, classes); 419 420 // External devices. 421 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) { 422 device->setExternal(true); 423 } 424 425 // Switch-like devices. 426 if (classes & INPUT_DEVICE_CLASS_SWITCH) { 427 device->addMapper(new SwitchInputMapper(device)); 428 } 429 430 // Vibrator-like devices. 431 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) { 432 device->addMapper(new VibratorInputMapper(device)); 433 } 434 435 // Keyboard-like devices. 436 uint32_t keyboardSource = 0; 437 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC; 438 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) { 439 keyboardSource |= AINPUT_SOURCE_KEYBOARD; 440 } 441 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) { 442 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC; 443 } 444 if (classes & INPUT_DEVICE_CLASS_DPAD) { 445 keyboardSource |= AINPUT_SOURCE_DPAD; 446 } 447 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) { 448 keyboardSource |= AINPUT_SOURCE_GAMEPAD; 449 } 450 451 if (keyboardSource != 0) { 452 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType)); 453 } 454 455 // Cursor-like devices. 456 if (classes & INPUT_DEVICE_CLASS_CURSOR) { 457 device->addMapper(new CursorInputMapper(device)); 458 } 459 460 // Touchscreens and touchpad devices. 461 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) { 462 device->addMapper(new MultiTouchInputMapper(device)); 463 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) { 464 device->addMapper(new SingleTouchInputMapper(device)); 465 } 466 467 // Joystick-like devices. 468 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) { 469 device->addMapper(new JoystickInputMapper(device)); 470 } 471 472 return device; 473} 474 475void InputReader::processEventsForDeviceLocked(int32_t deviceId, 476 const RawEvent* rawEvents, size_t count) { 477 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 478 if (deviceIndex < 0) { 479 ALOGW("Discarding event for unknown deviceId %d.", deviceId); 480 return; 481 } 482 483 InputDevice* device = mDevices.valueAt(deviceIndex); 484 if (device->isIgnored()) { 485 //ALOGD("Discarding event for ignored deviceId %d.", deviceId); 486 return; 487 } 488 489 device->process(rawEvents, count); 490} 491 492void InputReader::timeoutExpiredLocked(nsecs_t when) { 493 for (size_t i = 0; i < mDevices.size(); i++) { 494 InputDevice* device = mDevices.valueAt(i); 495 if (!device->isIgnored()) { 496 device->timeoutExpired(when); 497 } 498 } 499} 500 501void InputReader::handleConfigurationChangedLocked(nsecs_t when) { 502 // Reset global meta state because it depends on the list of all configured devices. 503 updateGlobalMetaStateLocked(); 504 505 // Update input configuration. 506 updateInputConfigurationLocked(); 507 508 // Enqueue configuration changed. 509 NotifyConfigurationChangedArgs args(when); 510 mQueuedListener->notifyConfigurationChanged(&args); 511} 512 513void InputReader::refreshConfigurationLocked(uint32_t changes) { 514 mPolicy->getReaderConfiguration(&mConfig); 515 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames); 516 517 if (changes) { 518 ALOGI("Reconfiguring input devices. changes=0x%08x", changes); 519 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); 520 521 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) { 522 mEventHub->requestReopenDevices(); 523 } else { 524 for (size_t i = 0; i < mDevices.size(); i++) { 525 InputDevice* device = mDevices.valueAt(i); 526 device->configure(now, &mConfig, changes); 527 } 528 } 529 } 530} 531 532void InputReader::updateGlobalMetaStateLocked() { 533 mGlobalMetaState = 0; 534 535 for (size_t i = 0; i < mDevices.size(); i++) { 536 InputDevice* device = mDevices.valueAt(i); 537 mGlobalMetaState |= device->getMetaState(); 538 } 539} 540 541int32_t InputReader::getGlobalMetaStateLocked() { 542 return mGlobalMetaState; 543} 544 545void InputReader::updateInputConfigurationLocked() { 546 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH; 547 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS; 548 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV; 549 InputDeviceInfo deviceInfo; 550 for (size_t i = 0; i < mDevices.size(); i++) { 551 InputDevice* device = mDevices.valueAt(i); 552 if (!(device->getClasses() & INPUT_DEVICE_CLASS_VIRTUAL)) { 553 device->getDeviceInfo(& deviceInfo); 554 uint32_t sources = deviceInfo.getSources(); 555 556 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) { 557 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER; 558 } 559 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) { 560 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL; 561 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) { 562 navigationConfig = InputConfiguration::NAVIGATION_DPAD; 563 } 564 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) { 565 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY; 566 } 567 } 568 } 569 570 mInputConfiguration.touchScreen = touchScreenConfig; 571 mInputConfiguration.keyboard = keyboardConfig; 572 mInputConfiguration.navigation = navigationConfig; 573} 574 575void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) { 576 mDisableVirtualKeysTimeout = time; 577} 578 579bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, 580 InputDevice* device, int32_t keyCode, int32_t scanCode) { 581 if (now < mDisableVirtualKeysTimeout) { 582 ALOGI("Dropping virtual key from device %s because virtual keys are " 583 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d", 584 device->getName().string(), 585 (mDisableVirtualKeysTimeout - now) * 0.000001, 586 keyCode, scanCode); 587 return true; 588 } else { 589 return false; 590 } 591} 592 593void InputReader::fadePointerLocked() { 594 for (size_t i = 0; i < mDevices.size(); i++) { 595 InputDevice* device = mDevices.valueAt(i); 596 device->fadePointer(); 597 } 598} 599 600void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) { 601 if (when < mNextTimeout) { 602 mNextTimeout = when; 603 mEventHub->wake(); 604 } 605} 606 607int32_t InputReader::bumpGenerationLocked() { 608 return ++mGeneration; 609} 610 611void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) { 612 AutoMutex _l(mLock); 613 614 *outConfiguration = mInputConfiguration; 615} 616 617void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) { 618 AutoMutex _l(mLock); 619 getInputDevicesLocked(outInputDevices); 620} 621 622void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) { 623 outInputDevices.clear(); 624 625 size_t numDevices = mDevices.size(); 626 for (size_t i = 0; i < numDevices; i++) { 627 InputDevice* device = mDevices.valueAt(i); 628 if (!device->isIgnored()) { 629 outInputDevices.push(); 630 device->getDeviceInfo(&outInputDevices.editTop()); 631 } 632 } 633} 634 635int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, 636 int32_t keyCode) { 637 AutoMutex _l(mLock); 638 639 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState); 640} 641 642int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, 643 int32_t scanCode) { 644 AutoMutex _l(mLock); 645 646 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState); 647} 648 649int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) { 650 AutoMutex _l(mLock); 651 652 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState); 653} 654 655int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code, 656 GetStateFunc getStateFunc) { 657 int32_t result = AKEY_STATE_UNKNOWN; 658 if (deviceId >= 0) { 659 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 660 if (deviceIndex >= 0) { 661 InputDevice* device = mDevices.valueAt(deviceIndex); 662 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 663 result = (device->*getStateFunc)(sourceMask, code); 664 } 665 } 666 } else { 667 size_t numDevices = mDevices.size(); 668 for (size_t i = 0; i < numDevices; i++) { 669 InputDevice* device = mDevices.valueAt(i); 670 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 671 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that 672 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it. 673 int32_t currentResult = (device->*getStateFunc)(sourceMask, code); 674 if (currentResult >= AKEY_STATE_DOWN) { 675 return currentResult; 676 } else if (currentResult == AKEY_STATE_UP) { 677 result = currentResult; 678 } 679 } 680 } 681 } 682 return result; 683} 684 685bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, 686 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { 687 AutoMutex _l(mLock); 688 689 memset(outFlags, 0, numCodes); 690 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags); 691} 692 693bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask, 694 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { 695 bool result = false; 696 if (deviceId >= 0) { 697 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 698 if (deviceIndex >= 0) { 699 InputDevice* device = mDevices.valueAt(deviceIndex); 700 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 701 result = device->markSupportedKeyCodes(sourceMask, 702 numCodes, keyCodes, outFlags); 703 } 704 } 705 } else { 706 size_t numDevices = mDevices.size(); 707 for (size_t i = 0; i < numDevices; i++) { 708 InputDevice* device = mDevices.valueAt(i); 709 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 710 result |= device->markSupportedKeyCodes(sourceMask, 711 numCodes, keyCodes, outFlags); 712 } 713 } 714 } 715 return result; 716} 717 718void InputReader::requestRefreshConfiguration(uint32_t changes) { 719 AutoMutex _l(mLock); 720 721 if (changes) { 722 bool needWake = !mConfigurationChangesToRefresh; 723 mConfigurationChangesToRefresh |= changes; 724 725 if (needWake) { 726 mEventHub->wake(); 727 } 728 } 729} 730 731void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, 732 ssize_t repeat, int32_t token) { 733 AutoMutex _l(mLock); 734 735 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 736 if (deviceIndex >= 0) { 737 InputDevice* device = mDevices.valueAt(deviceIndex); 738 device->vibrate(pattern, patternSize, repeat, token); 739 } 740} 741 742void InputReader::cancelVibrate(int32_t deviceId, int32_t token) { 743 AutoMutex _l(mLock); 744 745 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 746 if (deviceIndex >= 0) { 747 InputDevice* device = mDevices.valueAt(deviceIndex); 748 device->cancelVibrate(token); 749 } 750} 751 752void InputReader::dump(String8& dump) { 753 AutoMutex _l(mLock); 754 755 mEventHub->dump(dump); 756 dump.append("\n"); 757 758 dump.append("Input Reader State:\n"); 759 760 for (size_t i = 0; i < mDevices.size(); i++) { 761 mDevices.valueAt(i)->dump(dump); 762 } 763 764 dump.append(INDENT "Configuration:\n"); 765 dump.append(INDENT2 "ExcludedDeviceNames: ["); 766 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) { 767 if (i != 0) { 768 dump.append(", "); 769 } 770 dump.append(mConfig.excludedDeviceNames.itemAt(i).string()); 771 } 772 dump.append("]\n"); 773 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n", 774 mConfig.virtualKeyQuietTime * 0.000001f); 775 776 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: " 777 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n", 778 mConfig.pointerVelocityControlParameters.scale, 779 mConfig.pointerVelocityControlParameters.lowThreshold, 780 mConfig.pointerVelocityControlParameters.highThreshold, 781 mConfig.pointerVelocityControlParameters.acceleration); 782 783 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: " 784 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n", 785 mConfig.wheelVelocityControlParameters.scale, 786 mConfig.wheelVelocityControlParameters.lowThreshold, 787 mConfig.wheelVelocityControlParameters.highThreshold, 788 mConfig.wheelVelocityControlParameters.acceleration); 789 790 dump.appendFormat(INDENT2 "PointerGesture:\n"); 791 dump.appendFormat(INDENT3 "Enabled: %s\n", 792 toString(mConfig.pointerGesturesEnabled)); 793 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n", 794 mConfig.pointerGestureQuietInterval * 0.000001f); 795 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n", 796 mConfig.pointerGestureDragMinSwitchSpeed); 797 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n", 798 mConfig.pointerGestureTapInterval * 0.000001f); 799 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n", 800 mConfig.pointerGestureTapDragInterval * 0.000001f); 801 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n", 802 mConfig.pointerGestureTapSlop); 803 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n", 804 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f); 805 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n", 806 mConfig.pointerGestureMultitouchMinDistance); 807 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n", 808 mConfig.pointerGestureSwipeTransitionAngleCosine); 809 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n", 810 mConfig.pointerGestureSwipeMaxWidthRatio); 811 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n", 812 mConfig.pointerGestureMovementSpeedRatio); 813 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n", 814 mConfig.pointerGestureZoomSpeedRatio); 815} 816 817void InputReader::monitor() { 818 // Acquire and release the lock to ensure that the reader has not deadlocked. 819 mLock.lock(); 820 mEventHub->wake(); 821 mReaderIsAliveCondition.wait(mLock); 822 mLock.unlock(); 823 824 // Check the EventHub 825 mEventHub->monitor(); 826} 827 828 829// --- InputReader::ContextImpl --- 830 831InputReader::ContextImpl::ContextImpl(InputReader* reader) : 832 mReader(reader) { 833} 834 835void InputReader::ContextImpl::updateGlobalMetaState() { 836 // lock is already held by the input loop 837 mReader->updateGlobalMetaStateLocked(); 838} 839 840int32_t InputReader::ContextImpl::getGlobalMetaState() { 841 // lock is already held by the input loop 842 return mReader->getGlobalMetaStateLocked(); 843} 844 845void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) { 846 // lock is already held by the input loop 847 mReader->disableVirtualKeysUntilLocked(time); 848} 849 850bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, 851 InputDevice* device, int32_t keyCode, int32_t scanCode) { 852 // lock is already held by the input loop 853 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode); 854} 855 856void InputReader::ContextImpl::fadePointer() { 857 // lock is already held by the input loop 858 mReader->fadePointerLocked(); 859} 860 861void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) { 862 // lock is already held by the input loop 863 mReader->requestTimeoutAtTimeLocked(when); 864} 865 866int32_t InputReader::ContextImpl::bumpGeneration() { 867 // lock is already held by the input loop 868 return mReader->bumpGenerationLocked(); 869} 870 871InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() { 872 return mReader->mPolicy.get(); 873} 874 875InputListenerInterface* InputReader::ContextImpl::getListener() { 876 return mReader->mQueuedListener.get(); 877} 878 879EventHubInterface* InputReader::ContextImpl::getEventHub() { 880 return mReader->mEventHub.get(); 881} 882 883 884// --- InputReaderThread --- 885 886InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) : 887 Thread(/*canCallJava*/ true), mReader(reader) { 888} 889 890InputReaderThread::~InputReaderThread() { 891} 892 893bool InputReaderThread::threadLoop() { 894 mReader->loopOnce(); 895 return true; 896} 897 898 899// --- InputDevice --- 900 901InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation, 902 const InputDeviceIdentifier& identifier, uint32_t classes) : 903 mContext(context), mId(id), mGeneration(generation), 904 mIdentifier(identifier), mClasses(classes), 905 mSources(0), mIsExternal(false), mDropUntilNextSync(false) { 906} 907 908InputDevice::~InputDevice() { 909 size_t numMappers = mMappers.size(); 910 for (size_t i = 0; i < numMappers; i++) { 911 delete mMappers[i]; 912 } 913 mMappers.clear(); 914} 915 916void InputDevice::dump(String8& dump) { 917 InputDeviceInfo deviceInfo; 918 getDeviceInfo(& deviceInfo); 919 920 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(), 921 deviceInfo.getName().string()); 922 dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration); 923 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal)); 924 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources()); 925 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType()); 926 927 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges(); 928 if (!ranges.isEmpty()) { 929 dump.append(INDENT2 "Motion Ranges:\n"); 930 for (size_t i = 0; i < ranges.size(); i++) { 931 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i); 932 const char* label = getAxisLabel(range.axis); 933 char name[32]; 934 if (label) { 935 strncpy(name, label, sizeof(name)); 936 name[sizeof(name) - 1] = '\0'; 937 } else { 938 snprintf(name, sizeof(name), "%d", range.axis); 939 } 940 dump.appendFormat(INDENT3 "%s: source=0x%08x, " 941 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n", 942 name, range.source, range.min, range.max, range.flat, range.fuzz); 943 } 944 } 945 946 size_t numMappers = mMappers.size(); 947 for (size_t i = 0; i < numMappers; i++) { 948 InputMapper* mapper = mMappers[i]; 949 mapper->dump(dump); 950 } 951} 952 953void InputDevice::addMapper(InputMapper* mapper) { 954 mMappers.add(mapper); 955} 956 957void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { 958 mSources = 0; 959 960 if (!isIgnored()) { 961 if (!changes) { // first time only 962 mContext->getEventHub()->getConfiguration(mId, &mConfiguration); 963 } 964 965 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) { 966 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) { 967 sp<KeyCharacterMap> keyboardLayout = 968 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier.descriptor); 969 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) { 970 bumpGeneration(); 971 } 972 } 973 } 974 975 size_t numMappers = mMappers.size(); 976 for (size_t i = 0; i < numMappers; i++) { 977 InputMapper* mapper = mMappers[i]; 978 mapper->configure(when, config, changes); 979 mSources |= mapper->getSources(); 980 } 981 } 982} 983 984void InputDevice::reset(nsecs_t when) { 985 size_t numMappers = mMappers.size(); 986 for (size_t i = 0; i < numMappers; i++) { 987 InputMapper* mapper = mMappers[i]; 988 mapper->reset(when); 989 } 990 991 mContext->updateGlobalMetaState(); 992 993 notifyReset(when); 994} 995 996void InputDevice::process(const RawEvent* rawEvents, size_t count) { 997 // Process all of the events in order for each mapper. 998 // We cannot simply ask each mapper to process them in bulk because mappers may 999 // have side-effects that must be interleaved. For example, joystick movement events and 1000 // gamepad button presses are handled by different mappers but they should be dispatched 1001 // in the order received. 1002 size_t numMappers = mMappers.size(); 1003 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) { 1004#if DEBUG_RAW_EVENTS 1005 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x", 1006 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value); 1007#endif 1008 1009 if (mDropUntilNextSync) { 1010 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { 1011 mDropUntilNextSync = false; 1012#if DEBUG_RAW_EVENTS 1013 ALOGD("Recovered from input event buffer overrun."); 1014#endif 1015 } else { 1016#if DEBUG_RAW_EVENTS 1017 ALOGD("Dropped input event while waiting for next input sync."); 1018#endif 1019 } 1020 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) { 1021 ALOGI("Detected input event buffer overrun for device %s.", getName().string()); 1022 mDropUntilNextSync = true; 1023 reset(rawEvent->when); 1024 } else { 1025 for (size_t i = 0; i < numMappers; i++) { 1026 InputMapper* mapper = mMappers[i]; 1027 mapper->process(rawEvent); 1028 } 1029 } 1030 } 1031} 1032 1033void InputDevice::timeoutExpired(nsecs_t when) { 1034 size_t numMappers = mMappers.size(); 1035 for (size_t i = 0; i < numMappers; i++) { 1036 InputMapper* mapper = mMappers[i]; 1037 mapper->timeoutExpired(when); 1038 } 1039} 1040 1041void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) { 1042 outDeviceInfo->initialize(mId, mGeneration, mIdentifier.name, mIdentifier.descriptor); 1043 1044 size_t numMappers = mMappers.size(); 1045 for (size_t i = 0; i < numMappers; i++) { 1046 InputMapper* mapper = mMappers[i]; 1047 mapper->populateDeviceInfo(outDeviceInfo); 1048 } 1049} 1050 1051int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 1052 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState); 1053} 1054 1055int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 1056 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState); 1057} 1058 1059int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 1060 return getState(sourceMask, switchCode, & InputMapper::getSwitchState); 1061} 1062 1063int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { 1064 int32_t result = AKEY_STATE_UNKNOWN; 1065 size_t numMappers = mMappers.size(); 1066 for (size_t i = 0; i < numMappers; i++) { 1067 InputMapper* mapper = mMappers[i]; 1068 if (sourcesMatchMask(mapper->getSources(), sourceMask)) { 1069 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that 1070 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it. 1071 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code); 1072 if (currentResult >= AKEY_STATE_DOWN) { 1073 return currentResult; 1074 } else if (currentResult == AKEY_STATE_UP) { 1075 result = currentResult; 1076 } 1077 } 1078 } 1079 return result; 1080} 1081 1082bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 1083 const int32_t* keyCodes, uint8_t* outFlags) { 1084 bool result = false; 1085 size_t numMappers = mMappers.size(); 1086 for (size_t i = 0; i < numMappers; i++) { 1087 InputMapper* mapper = mMappers[i]; 1088 if (sourcesMatchMask(mapper->getSources(), sourceMask)) { 1089 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); 1090 } 1091 } 1092 return result; 1093} 1094 1095void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, 1096 int32_t token) { 1097 size_t numMappers = mMappers.size(); 1098 for (size_t i = 0; i < numMappers; i++) { 1099 InputMapper* mapper = mMappers[i]; 1100 mapper->vibrate(pattern, patternSize, repeat, token); 1101 } 1102} 1103 1104void InputDevice::cancelVibrate(int32_t token) { 1105 size_t numMappers = mMappers.size(); 1106 for (size_t i = 0; i < numMappers; i++) { 1107 InputMapper* mapper = mMappers[i]; 1108 mapper->cancelVibrate(token); 1109 } 1110} 1111 1112int32_t InputDevice::getMetaState() { 1113 int32_t result = 0; 1114 size_t numMappers = mMappers.size(); 1115 for (size_t i = 0; i < numMappers; i++) { 1116 InputMapper* mapper = mMappers[i]; 1117 result |= mapper->getMetaState(); 1118 } 1119 return result; 1120} 1121 1122void InputDevice::fadePointer() { 1123 size_t numMappers = mMappers.size(); 1124 for (size_t i = 0; i < numMappers; i++) { 1125 InputMapper* mapper = mMappers[i]; 1126 mapper->fadePointer(); 1127 } 1128} 1129 1130void InputDevice::bumpGeneration() { 1131 mGeneration = mContext->bumpGeneration(); 1132} 1133 1134void InputDevice::notifyReset(nsecs_t when) { 1135 NotifyDeviceResetArgs args(when, mId); 1136 mContext->getListener()->notifyDeviceReset(&args); 1137} 1138 1139 1140// --- CursorButtonAccumulator --- 1141 1142CursorButtonAccumulator::CursorButtonAccumulator() { 1143 clearButtons(); 1144} 1145 1146void CursorButtonAccumulator::reset(InputDevice* device) { 1147 mBtnLeft = device->isKeyPressed(BTN_LEFT); 1148 mBtnRight = device->isKeyPressed(BTN_RIGHT); 1149 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE); 1150 mBtnBack = device->isKeyPressed(BTN_BACK); 1151 mBtnSide = device->isKeyPressed(BTN_SIDE); 1152 mBtnForward = device->isKeyPressed(BTN_FORWARD); 1153 mBtnExtra = device->isKeyPressed(BTN_EXTRA); 1154 mBtnTask = device->isKeyPressed(BTN_TASK); 1155} 1156 1157void CursorButtonAccumulator::clearButtons() { 1158 mBtnLeft = 0; 1159 mBtnRight = 0; 1160 mBtnMiddle = 0; 1161 mBtnBack = 0; 1162 mBtnSide = 0; 1163 mBtnForward = 0; 1164 mBtnExtra = 0; 1165 mBtnTask = 0; 1166} 1167 1168void CursorButtonAccumulator::process(const RawEvent* rawEvent) { 1169 if (rawEvent->type == EV_KEY) { 1170 switch (rawEvent->code) { 1171 case BTN_LEFT: 1172 mBtnLeft = rawEvent->value; 1173 break; 1174 case BTN_RIGHT: 1175 mBtnRight = rawEvent->value; 1176 break; 1177 case BTN_MIDDLE: 1178 mBtnMiddle = rawEvent->value; 1179 break; 1180 case BTN_BACK: 1181 mBtnBack = rawEvent->value; 1182 break; 1183 case BTN_SIDE: 1184 mBtnSide = rawEvent->value; 1185 break; 1186 case BTN_FORWARD: 1187 mBtnForward = rawEvent->value; 1188 break; 1189 case BTN_EXTRA: 1190 mBtnExtra = rawEvent->value; 1191 break; 1192 case BTN_TASK: 1193 mBtnTask = rawEvent->value; 1194 break; 1195 } 1196 } 1197} 1198 1199uint32_t CursorButtonAccumulator::getButtonState() const { 1200 uint32_t result = 0; 1201 if (mBtnLeft) { 1202 result |= AMOTION_EVENT_BUTTON_PRIMARY; 1203 } 1204 if (mBtnRight) { 1205 result |= AMOTION_EVENT_BUTTON_SECONDARY; 1206 } 1207 if (mBtnMiddle) { 1208 result |= AMOTION_EVENT_BUTTON_TERTIARY; 1209 } 1210 if (mBtnBack || mBtnSide) { 1211 result |= AMOTION_EVENT_BUTTON_BACK; 1212 } 1213 if (mBtnForward || mBtnExtra) { 1214 result |= AMOTION_EVENT_BUTTON_FORWARD; 1215 } 1216 return result; 1217} 1218 1219 1220// --- CursorMotionAccumulator --- 1221 1222CursorMotionAccumulator::CursorMotionAccumulator() { 1223 clearRelativeAxes(); 1224} 1225 1226void CursorMotionAccumulator::reset(InputDevice* device) { 1227 clearRelativeAxes(); 1228} 1229 1230void CursorMotionAccumulator::clearRelativeAxes() { 1231 mRelX = 0; 1232 mRelY = 0; 1233} 1234 1235void CursorMotionAccumulator::process(const RawEvent* rawEvent) { 1236 if (rawEvent->type == EV_REL) { 1237 switch (rawEvent->code) { 1238 case REL_X: 1239 mRelX = rawEvent->value; 1240 break; 1241 case REL_Y: 1242 mRelY = rawEvent->value; 1243 break; 1244 } 1245 } 1246} 1247 1248void CursorMotionAccumulator::finishSync() { 1249 clearRelativeAxes(); 1250} 1251 1252 1253// --- CursorScrollAccumulator --- 1254 1255CursorScrollAccumulator::CursorScrollAccumulator() : 1256 mHaveRelWheel(false), mHaveRelHWheel(false) { 1257 clearRelativeAxes(); 1258} 1259 1260void CursorScrollAccumulator::configure(InputDevice* device) { 1261 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL); 1262 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL); 1263} 1264 1265void CursorScrollAccumulator::reset(InputDevice* device) { 1266 clearRelativeAxes(); 1267} 1268 1269void CursorScrollAccumulator::clearRelativeAxes() { 1270 mRelWheel = 0; 1271 mRelHWheel = 0; 1272} 1273 1274void CursorScrollAccumulator::process(const RawEvent* rawEvent) { 1275 if (rawEvent->type == EV_REL) { 1276 switch (rawEvent->code) { 1277 case REL_WHEEL: 1278 mRelWheel = rawEvent->value; 1279 break; 1280 case REL_HWHEEL: 1281 mRelHWheel = rawEvent->value; 1282 break; 1283 } 1284 } 1285} 1286 1287void CursorScrollAccumulator::finishSync() { 1288 clearRelativeAxes(); 1289} 1290 1291 1292// --- TouchButtonAccumulator --- 1293 1294TouchButtonAccumulator::TouchButtonAccumulator() : 1295 mHaveBtnTouch(false) { 1296 clearButtons(); 1297} 1298 1299void TouchButtonAccumulator::configure(InputDevice* device) { 1300 mHaveBtnTouch = device->hasKey(BTN_TOUCH); 1301} 1302 1303void TouchButtonAccumulator::reset(InputDevice* device) { 1304 mBtnTouch = device->isKeyPressed(BTN_TOUCH); 1305 mBtnStylus = device->isKeyPressed(BTN_STYLUS); 1306 mBtnStylus2 = device->isKeyPressed(BTN_STYLUS); 1307 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER); 1308 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN); 1309 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER); 1310 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH); 1311 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL); 1312 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH); 1313 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE); 1314 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS); 1315 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP); 1316 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP); 1317 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP); 1318} 1319 1320void TouchButtonAccumulator::clearButtons() { 1321 mBtnTouch = 0; 1322 mBtnStylus = 0; 1323 mBtnStylus2 = 0; 1324 mBtnToolFinger = 0; 1325 mBtnToolPen = 0; 1326 mBtnToolRubber = 0; 1327 mBtnToolBrush = 0; 1328 mBtnToolPencil = 0; 1329 mBtnToolAirbrush = 0; 1330 mBtnToolMouse = 0; 1331 mBtnToolLens = 0; 1332 mBtnToolDoubleTap = 0; 1333 mBtnToolTripleTap = 0; 1334 mBtnToolQuadTap = 0; 1335} 1336 1337void TouchButtonAccumulator::process(const RawEvent* rawEvent) { 1338 if (rawEvent->type == EV_KEY) { 1339 switch (rawEvent->code) { 1340 case BTN_TOUCH: 1341 mBtnTouch = rawEvent->value; 1342 break; 1343 case BTN_STYLUS: 1344 mBtnStylus = rawEvent->value; 1345 break; 1346 case BTN_STYLUS2: 1347 mBtnStylus2 = rawEvent->value; 1348 break; 1349 case BTN_TOOL_FINGER: 1350 mBtnToolFinger = rawEvent->value; 1351 break; 1352 case BTN_TOOL_PEN: 1353 mBtnToolPen = rawEvent->value; 1354 break; 1355 case BTN_TOOL_RUBBER: 1356 mBtnToolRubber = rawEvent->value; 1357 break; 1358 case BTN_TOOL_BRUSH: 1359 mBtnToolBrush = rawEvent->value; 1360 break; 1361 case BTN_TOOL_PENCIL: 1362 mBtnToolPencil = rawEvent->value; 1363 break; 1364 case BTN_TOOL_AIRBRUSH: 1365 mBtnToolAirbrush = rawEvent->value; 1366 break; 1367 case BTN_TOOL_MOUSE: 1368 mBtnToolMouse = rawEvent->value; 1369 break; 1370 case BTN_TOOL_LENS: 1371 mBtnToolLens = rawEvent->value; 1372 break; 1373 case BTN_TOOL_DOUBLETAP: 1374 mBtnToolDoubleTap = rawEvent->value; 1375 break; 1376 case BTN_TOOL_TRIPLETAP: 1377 mBtnToolTripleTap = rawEvent->value; 1378 break; 1379 case BTN_TOOL_QUADTAP: 1380 mBtnToolQuadTap = rawEvent->value; 1381 break; 1382 } 1383 } 1384} 1385 1386uint32_t TouchButtonAccumulator::getButtonState() const { 1387 uint32_t result = 0; 1388 if (mBtnStylus) { 1389 result |= AMOTION_EVENT_BUTTON_SECONDARY; 1390 } 1391 if (mBtnStylus2) { 1392 result |= AMOTION_EVENT_BUTTON_TERTIARY; 1393 } 1394 return result; 1395} 1396 1397int32_t TouchButtonAccumulator::getToolType() const { 1398 if (mBtnToolMouse || mBtnToolLens) { 1399 return AMOTION_EVENT_TOOL_TYPE_MOUSE; 1400 } 1401 if (mBtnToolRubber) { 1402 return AMOTION_EVENT_TOOL_TYPE_ERASER; 1403 } 1404 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) { 1405 return AMOTION_EVENT_TOOL_TYPE_STYLUS; 1406 } 1407 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) { 1408 return AMOTION_EVENT_TOOL_TYPE_FINGER; 1409 } 1410 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN; 1411} 1412 1413bool TouchButtonAccumulator::isToolActive() const { 1414 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber 1415 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush 1416 || mBtnToolMouse || mBtnToolLens 1417 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap; 1418} 1419 1420bool TouchButtonAccumulator::isHovering() const { 1421 return mHaveBtnTouch && !mBtnTouch; 1422} 1423 1424 1425// --- RawPointerAxes --- 1426 1427RawPointerAxes::RawPointerAxes() { 1428 clear(); 1429} 1430 1431void RawPointerAxes::clear() { 1432 x.clear(); 1433 y.clear(); 1434 pressure.clear(); 1435 touchMajor.clear(); 1436 touchMinor.clear(); 1437 toolMajor.clear(); 1438 toolMinor.clear(); 1439 orientation.clear(); 1440 distance.clear(); 1441 tiltX.clear(); 1442 tiltY.clear(); 1443 trackingId.clear(); 1444 slot.clear(); 1445} 1446 1447 1448// --- RawPointerData --- 1449 1450RawPointerData::RawPointerData() { 1451 clear(); 1452} 1453 1454void RawPointerData::clear() { 1455 pointerCount = 0; 1456 clearIdBits(); 1457} 1458 1459void RawPointerData::copyFrom(const RawPointerData& other) { 1460 pointerCount = other.pointerCount; 1461 hoveringIdBits = other.hoveringIdBits; 1462 touchingIdBits = other.touchingIdBits; 1463 1464 for (uint32_t i = 0; i < pointerCount; i++) { 1465 pointers[i] = other.pointers[i]; 1466 1467 int id = pointers[i].id; 1468 idToIndex[id] = other.idToIndex[id]; 1469 } 1470} 1471 1472void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const { 1473 float x = 0, y = 0; 1474 uint32_t count = touchingIdBits.count(); 1475 if (count) { 1476 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) { 1477 uint32_t id = idBits.clearFirstMarkedBit(); 1478 const Pointer& pointer = pointerForId(id); 1479 x += pointer.x; 1480 y += pointer.y; 1481 } 1482 x /= count; 1483 y /= count; 1484 } 1485 *outX = x; 1486 *outY = y; 1487} 1488 1489 1490// --- CookedPointerData --- 1491 1492CookedPointerData::CookedPointerData() { 1493 clear(); 1494} 1495 1496void CookedPointerData::clear() { 1497 pointerCount = 0; 1498 hoveringIdBits.clear(); 1499 touchingIdBits.clear(); 1500} 1501 1502void CookedPointerData::copyFrom(const CookedPointerData& other) { 1503 pointerCount = other.pointerCount; 1504 hoveringIdBits = other.hoveringIdBits; 1505 touchingIdBits = other.touchingIdBits; 1506 1507 for (uint32_t i = 0; i < pointerCount; i++) { 1508 pointerProperties[i].copyFrom(other.pointerProperties[i]); 1509 pointerCoords[i].copyFrom(other.pointerCoords[i]); 1510 1511 int id = pointerProperties[i].id; 1512 idToIndex[id] = other.idToIndex[id]; 1513 } 1514} 1515 1516 1517// --- SingleTouchMotionAccumulator --- 1518 1519SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() { 1520 clearAbsoluteAxes(); 1521} 1522 1523void SingleTouchMotionAccumulator::reset(InputDevice* device) { 1524 mAbsX = device->getAbsoluteAxisValue(ABS_X); 1525 mAbsY = device->getAbsoluteAxisValue(ABS_Y); 1526 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE); 1527 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH); 1528 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE); 1529 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X); 1530 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y); 1531} 1532 1533void SingleTouchMotionAccumulator::clearAbsoluteAxes() { 1534 mAbsX = 0; 1535 mAbsY = 0; 1536 mAbsPressure = 0; 1537 mAbsToolWidth = 0; 1538 mAbsDistance = 0; 1539 mAbsTiltX = 0; 1540 mAbsTiltY = 0; 1541} 1542 1543void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) { 1544 if (rawEvent->type == EV_ABS) { 1545 switch (rawEvent->code) { 1546 case ABS_X: 1547 mAbsX = rawEvent->value; 1548 break; 1549 case ABS_Y: 1550 mAbsY = rawEvent->value; 1551 break; 1552 case ABS_PRESSURE: 1553 mAbsPressure = rawEvent->value; 1554 break; 1555 case ABS_TOOL_WIDTH: 1556 mAbsToolWidth = rawEvent->value; 1557 break; 1558 case ABS_DISTANCE: 1559 mAbsDistance = rawEvent->value; 1560 break; 1561 case ABS_TILT_X: 1562 mAbsTiltX = rawEvent->value; 1563 break; 1564 case ABS_TILT_Y: 1565 mAbsTiltY = rawEvent->value; 1566 break; 1567 } 1568 } 1569} 1570 1571 1572// --- MultiTouchMotionAccumulator --- 1573 1574MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() : 1575 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false) { 1576} 1577 1578MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() { 1579 delete[] mSlots; 1580} 1581 1582void MultiTouchMotionAccumulator::configure(size_t slotCount, bool usingSlotsProtocol) { 1583 mSlotCount = slotCount; 1584 mUsingSlotsProtocol = usingSlotsProtocol; 1585 1586 delete[] mSlots; 1587 mSlots = new Slot[slotCount]; 1588} 1589 1590void MultiTouchMotionAccumulator::reset(InputDevice* device) { 1591 // Unfortunately there is no way to read the initial contents of the slots. 1592 // So when we reset the accumulator, we must assume they are all zeroes. 1593 if (mUsingSlotsProtocol) { 1594 // Query the driver for the current slot index and use it as the initial slot 1595 // before we start reading events from the device. It is possible that the 1596 // current slot index will not be the same as it was when the first event was 1597 // written into the evdev buffer, which means the input mapper could start 1598 // out of sync with the initial state of the events in the evdev buffer. 1599 // In the extremely unlikely case that this happens, the data from 1600 // two slots will be confused until the next ABS_MT_SLOT event is received. 1601 // This can cause the touch point to "jump", but at least there will be 1602 // no stuck touches. 1603 int32_t initialSlot; 1604 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(), 1605 ABS_MT_SLOT, &initialSlot); 1606 if (status) { 1607 ALOGD("Could not retrieve current multitouch slot index. status=%d", status); 1608 initialSlot = -1; 1609 } 1610 clearSlots(initialSlot); 1611 } else { 1612 clearSlots(-1); 1613 } 1614} 1615 1616void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) { 1617 if (mSlots) { 1618 for (size_t i = 0; i < mSlotCount; i++) { 1619 mSlots[i].clear(); 1620 } 1621 } 1622 mCurrentSlot = initialSlot; 1623} 1624 1625void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) { 1626 if (rawEvent->type == EV_ABS) { 1627 bool newSlot = false; 1628 if (mUsingSlotsProtocol) { 1629 if (rawEvent->code == ABS_MT_SLOT) { 1630 mCurrentSlot = rawEvent->value; 1631 newSlot = true; 1632 } 1633 } else if (mCurrentSlot < 0) { 1634 mCurrentSlot = 0; 1635 } 1636 1637 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) { 1638#if DEBUG_POINTERS 1639 if (newSlot) { 1640 ALOGW("MultiTouch device emitted invalid slot index %d but it " 1641 "should be between 0 and %d; ignoring this slot.", 1642 mCurrentSlot, mSlotCount - 1); 1643 } 1644#endif 1645 } else { 1646 Slot* slot = &mSlots[mCurrentSlot]; 1647 1648 switch (rawEvent->code) { 1649 case ABS_MT_POSITION_X: 1650 slot->mInUse = true; 1651 slot->mAbsMTPositionX = rawEvent->value; 1652 break; 1653 case ABS_MT_POSITION_Y: 1654 slot->mInUse = true; 1655 slot->mAbsMTPositionY = rawEvent->value; 1656 break; 1657 case ABS_MT_TOUCH_MAJOR: 1658 slot->mInUse = true; 1659 slot->mAbsMTTouchMajor = rawEvent->value; 1660 break; 1661 case ABS_MT_TOUCH_MINOR: 1662 slot->mInUse = true; 1663 slot->mAbsMTTouchMinor = rawEvent->value; 1664 slot->mHaveAbsMTTouchMinor = true; 1665 break; 1666 case ABS_MT_WIDTH_MAJOR: 1667 slot->mInUse = true; 1668 slot->mAbsMTWidthMajor = rawEvent->value; 1669 break; 1670 case ABS_MT_WIDTH_MINOR: 1671 slot->mInUse = true; 1672 slot->mAbsMTWidthMinor = rawEvent->value; 1673 slot->mHaveAbsMTWidthMinor = true; 1674 break; 1675 case ABS_MT_ORIENTATION: 1676 slot->mInUse = true; 1677 slot->mAbsMTOrientation = rawEvent->value; 1678 break; 1679 case ABS_MT_TRACKING_ID: 1680 if (mUsingSlotsProtocol && rawEvent->value < 0) { 1681 // The slot is no longer in use but it retains its previous contents, 1682 // which may be reused for subsequent touches. 1683 slot->mInUse = false; 1684 } else { 1685 slot->mInUse = true; 1686 slot->mAbsMTTrackingId = rawEvent->value; 1687 } 1688 break; 1689 case ABS_MT_PRESSURE: 1690 slot->mInUse = true; 1691 slot->mAbsMTPressure = rawEvent->value; 1692 break; 1693 case ABS_MT_DISTANCE: 1694 slot->mInUse = true; 1695 slot->mAbsMTDistance = rawEvent->value; 1696 break; 1697 case ABS_MT_TOOL_TYPE: 1698 slot->mInUse = true; 1699 slot->mAbsMTToolType = rawEvent->value; 1700 slot->mHaveAbsMTToolType = true; 1701 break; 1702 } 1703 } 1704 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) { 1705 // MultiTouch Sync: The driver has returned all data for *one* of the pointers. 1706 mCurrentSlot += 1; 1707 } 1708} 1709 1710void MultiTouchMotionAccumulator::finishSync() { 1711 if (!mUsingSlotsProtocol) { 1712 clearSlots(-1); 1713 } 1714} 1715 1716 1717// --- MultiTouchMotionAccumulator::Slot --- 1718 1719MultiTouchMotionAccumulator::Slot::Slot() { 1720 clear(); 1721} 1722 1723void MultiTouchMotionAccumulator::Slot::clear() { 1724 mInUse = false; 1725 mHaveAbsMTTouchMinor = false; 1726 mHaveAbsMTWidthMinor = false; 1727 mHaveAbsMTToolType = false; 1728 mAbsMTPositionX = 0; 1729 mAbsMTPositionY = 0; 1730 mAbsMTTouchMajor = 0; 1731 mAbsMTTouchMinor = 0; 1732 mAbsMTWidthMajor = 0; 1733 mAbsMTWidthMinor = 0; 1734 mAbsMTOrientation = 0; 1735 mAbsMTTrackingId = -1; 1736 mAbsMTPressure = 0; 1737 mAbsMTDistance = 0; 1738 mAbsMTToolType = 0; 1739} 1740 1741int32_t MultiTouchMotionAccumulator::Slot::getToolType() const { 1742 if (mHaveAbsMTToolType) { 1743 switch (mAbsMTToolType) { 1744 case MT_TOOL_FINGER: 1745 return AMOTION_EVENT_TOOL_TYPE_FINGER; 1746 case MT_TOOL_PEN: 1747 return AMOTION_EVENT_TOOL_TYPE_STYLUS; 1748 } 1749 } 1750 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN; 1751} 1752 1753 1754// --- InputMapper --- 1755 1756InputMapper::InputMapper(InputDevice* device) : 1757 mDevice(device), mContext(device->getContext()) { 1758} 1759 1760InputMapper::~InputMapper() { 1761} 1762 1763void InputMapper::populateDeviceInfo(InputDeviceInfo* info) { 1764 info->addSource(getSources()); 1765} 1766 1767void InputMapper::dump(String8& dump) { 1768} 1769 1770void InputMapper::configure(nsecs_t when, 1771 const InputReaderConfiguration* config, uint32_t changes) { 1772} 1773 1774void InputMapper::reset(nsecs_t when) { 1775} 1776 1777void InputMapper::timeoutExpired(nsecs_t when) { 1778} 1779 1780int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 1781 return AKEY_STATE_UNKNOWN; 1782} 1783 1784int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 1785 return AKEY_STATE_UNKNOWN; 1786} 1787 1788int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 1789 return AKEY_STATE_UNKNOWN; 1790} 1791 1792bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 1793 const int32_t* keyCodes, uint8_t* outFlags) { 1794 return false; 1795} 1796 1797void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, 1798 int32_t token) { 1799} 1800 1801void InputMapper::cancelVibrate(int32_t token) { 1802} 1803 1804int32_t InputMapper::getMetaState() { 1805 return 0; 1806} 1807 1808void InputMapper::fadePointer() { 1809} 1810 1811status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) { 1812 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo); 1813} 1814 1815void InputMapper::bumpGeneration() { 1816 mDevice->bumpGeneration(); 1817} 1818 1819void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump, 1820 const RawAbsoluteAxisInfo& axis, const char* name) { 1821 if (axis.valid) { 1822 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n", 1823 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution); 1824 } else { 1825 dump.appendFormat(INDENT4 "%s: unknown range\n", name); 1826 } 1827} 1828 1829 1830// --- SwitchInputMapper --- 1831 1832SwitchInputMapper::SwitchInputMapper(InputDevice* device) : 1833 InputMapper(device) { 1834} 1835 1836SwitchInputMapper::~SwitchInputMapper() { 1837} 1838 1839uint32_t SwitchInputMapper::getSources() { 1840 return AINPUT_SOURCE_SWITCH; 1841} 1842 1843void SwitchInputMapper::process(const RawEvent* rawEvent) { 1844 switch (rawEvent->type) { 1845 case EV_SW: 1846 processSwitch(rawEvent->when, rawEvent->code, rawEvent->value); 1847 break; 1848 } 1849} 1850 1851void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) { 1852 NotifySwitchArgs args(when, 0, switchCode, switchValue); 1853 getListener()->notifySwitch(&args); 1854} 1855 1856int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 1857 return getEventHub()->getSwitchState(getDeviceId(), switchCode); 1858} 1859 1860 1861// --- VibratorInputMapper --- 1862 1863VibratorInputMapper::VibratorInputMapper(InputDevice* device) : 1864 InputMapper(device), mVibrating(false) { 1865} 1866 1867VibratorInputMapper::~VibratorInputMapper() { 1868} 1869 1870uint32_t VibratorInputMapper::getSources() { 1871 return 0; 1872} 1873 1874void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 1875 InputMapper::populateDeviceInfo(info); 1876 1877 info->setVibrator(true); 1878} 1879 1880void VibratorInputMapper::process(const RawEvent* rawEvent) { 1881 // TODO: Handle FF_STATUS, although it does not seem to be widely supported. 1882} 1883 1884void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, 1885 int32_t token) { 1886#if DEBUG_VIBRATOR 1887 String8 patternStr; 1888 for (size_t i = 0; i < patternSize; i++) { 1889 if (i != 0) { 1890 patternStr.append(", "); 1891 } 1892 patternStr.appendFormat("%lld", pattern[i]); 1893 } 1894 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d", 1895 getDeviceId(), patternStr.string(), repeat, token); 1896#endif 1897 1898 mVibrating = true; 1899 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t)); 1900 mPatternSize = patternSize; 1901 mRepeat = repeat; 1902 mToken = token; 1903 mIndex = -1; 1904 1905 nextStep(); 1906} 1907 1908void VibratorInputMapper::cancelVibrate(int32_t token) { 1909#if DEBUG_VIBRATOR 1910 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token); 1911#endif 1912 1913 if (mVibrating && mToken == token) { 1914 stopVibrating(); 1915 } 1916} 1917 1918void VibratorInputMapper::timeoutExpired(nsecs_t when) { 1919 if (mVibrating) { 1920 if (when >= mNextStepTime) { 1921 nextStep(); 1922 } else { 1923 getContext()->requestTimeoutAtTime(mNextStepTime); 1924 } 1925 } 1926} 1927 1928void VibratorInputMapper::nextStep() { 1929 mIndex += 1; 1930 if (size_t(mIndex) >= mPatternSize) { 1931 if (mRepeat < 0) { 1932 // We are done. 1933 stopVibrating(); 1934 return; 1935 } 1936 mIndex = mRepeat; 1937 } 1938 1939 bool vibratorOn = mIndex & 1; 1940 nsecs_t duration = mPattern[mIndex]; 1941 if (vibratorOn) { 1942#if DEBUG_VIBRATOR 1943 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld", 1944 getDeviceId(), duration); 1945#endif 1946 getEventHub()->vibrate(getDeviceId(), duration); 1947 } else { 1948#if DEBUG_VIBRATOR 1949 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId()); 1950#endif 1951 getEventHub()->cancelVibrate(getDeviceId()); 1952 } 1953 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); 1954 mNextStepTime = now + duration; 1955 getContext()->requestTimeoutAtTime(mNextStepTime); 1956#if DEBUG_VIBRATOR 1957 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f); 1958#endif 1959} 1960 1961void VibratorInputMapper::stopVibrating() { 1962 mVibrating = false; 1963#if DEBUG_VIBRATOR 1964 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId()); 1965#endif 1966 getEventHub()->cancelVibrate(getDeviceId()); 1967} 1968 1969void VibratorInputMapper::dump(String8& dump) { 1970 dump.append(INDENT2 "Vibrator Input Mapper:\n"); 1971 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating)); 1972} 1973 1974 1975// --- KeyboardInputMapper --- 1976 1977KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, 1978 uint32_t source, int32_t keyboardType) : 1979 InputMapper(device), mSource(source), 1980 mKeyboardType(keyboardType) { 1981} 1982 1983KeyboardInputMapper::~KeyboardInputMapper() { 1984} 1985 1986uint32_t KeyboardInputMapper::getSources() { 1987 return mSource; 1988} 1989 1990void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 1991 InputMapper::populateDeviceInfo(info); 1992 1993 info->setKeyboardType(mKeyboardType); 1994 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId())); 1995} 1996 1997void KeyboardInputMapper::dump(String8& dump) { 1998 dump.append(INDENT2 "Keyboard Input Mapper:\n"); 1999 dumpParameters(dump); 2000 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType); 2001 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation); 2002 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mKeyDowns.size()); 2003 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState); 2004 dump.appendFormat(INDENT3 "DownTime: %lld\n", mDownTime); 2005} 2006 2007 2008void KeyboardInputMapper::configure(nsecs_t when, 2009 const InputReaderConfiguration* config, uint32_t changes) { 2010 InputMapper::configure(when, config, changes); 2011 2012 if (!changes) { // first time only 2013 // Configure basic parameters. 2014 configureParameters(); 2015 } 2016 2017 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { 2018 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) { 2019 if (!config->getDisplayInfo(mParameters.associatedDisplayId, 2020 false /*external*/, NULL, NULL, &mOrientation)) { 2021 mOrientation = DISPLAY_ORIENTATION_0; 2022 } 2023 } else { 2024 mOrientation = DISPLAY_ORIENTATION_0; 2025 } 2026 } 2027} 2028 2029void KeyboardInputMapper::configureParameters() { 2030 mParameters.orientationAware = false; 2031 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"), 2032 mParameters.orientationAware); 2033 2034 mParameters.associatedDisplayId = -1; 2035 if (mParameters.orientationAware) { 2036 mParameters.associatedDisplayId = 0; 2037 } 2038} 2039 2040void KeyboardInputMapper::dumpParameters(String8& dump) { 2041 dump.append(INDENT3 "Parameters:\n"); 2042 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 2043 mParameters.associatedDisplayId); 2044 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 2045 toString(mParameters.orientationAware)); 2046} 2047 2048void KeyboardInputMapper::reset(nsecs_t when) { 2049 mMetaState = AMETA_NONE; 2050 mDownTime = 0; 2051 mKeyDowns.clear(); 2052 mCurrentHidUsage = 0; 2053 2054 resetLedState(); 2055 2056 InputMapper::reset(when); 2057} 2058 2059void KeyboardInputMapper::process(const RawEvent* rawEvent) { 2060 switch (rawEvent->type) { 2061 case EV_KEY: { 2062 int32_t scanCode = rawEvent->code; 2063 int32_t usageCode = mCurrentHidUsage; 2064 mCurrentHidUsage = 0; 2065 2066 if (isKeyboardOrGamepadKey(scanCode)) { 2067 int32_t keyCode; 2068 uint32_t flags; 2069 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, &keyCode, &flags)) { 2070 keyCode = AKEYCODE_UNKNOWN; 2071 flags = 0; 2072 } 2073 processKey(rawEvent->when, rawEvent->value != 0, keyCode, scanCode, flags); 2074 } 2075 break; 2076 } 2077 case EV_MSC: { 2078 if (rawEvent->code == MSC_SCAN) { 2079 mCurrentHidUsage = rawEvent->value; 2080 } 2081 break; 2082 } 2083 case EV_SYN: { 2084 if (rawEvent->code == SYN_REPORT) { 2085 mCurrentHidUsage = 0; 2086 } 2087 } 2088 } 2089} 2090 2091bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) { 2092 return scanCode < BTN_MOUSE 2093 || scanCode >= KEY_OK 2094 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE) 2095 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI); 2096} 2097 2098void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode, 2099 int32_t scanCode, uint32_t policyFlags) { 2100 2101 if (down) { 2102 // Rotate key codes according to orientation if needed. 2103 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) { 2104 keyCode = rotateKeyCode(keyCode, mOrientation); 2105 } 2106 2107 // Add key down. 2108 ssize_t keyDownIndex = findKeyDown(scanCode); 2109 if (keyDownIndex >= 0) { 2110 // key repeat, be sure to use same keycode as before in case of rotation 2111 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; 2112 } else { 2113 // key down 2114 if ((policyFlags & POLICY_FLAG_VIRTUAL) 2115 && mContext->shouldDropVirtualKey(when, 2116 getDevice(), keyCode, scanCode)) { 2117 return; 2118 } 2119 2120 mKeyDowns.push(); 2121 KeyDown& keyDown = mKeyDowns.editTop(); 2122 keyDown.keyCode = keyCode; 2123 keyDown.scanCode = scanCode; 2124 } 2125 2126 mDownTime = when; 2127 } else { 2128 // Remove key down. 2129 ssize_t keyDownIndex = findKeyDown(scanCode); 2130 if (keyDownIndex >= 0) { 2131 // key up, be sure to use same keycode as before in case of rotation 2132 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; 2133 mKeyDowns.removeAt(size_t(keyDownIndex)); 2134 } else { 2135 // key was not actually down 2136 ALOGI("Dropping key up from device %s because the key was not down. " 2137 "keyCode=%d, scanCode=%d", 2138 getDeviceName().string(), keyCode, scanCode); 2139 return; 2140 } 2141 } 2142 2143 bool metaStateChanged = false; 2144 int32_t oldMetaState = mMetaState; 2145 int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState); 2146 if (oldMetaState != newMetaState) { 2147 mMetaState = newMetaState; 2148 metaStateChanged = true; 2149 updateLedState(false); 2150 } 2151 2152 nsecs_t downTime = mDownTime; 2153 2154 // Key down on external an keyboard should wake the device. 2155 // We don't do this for internal keyboards to prevent them from waking up in your pocket. 2156 // For internal keyboards, the key layout file should specify the policy flags for 2157 // each wake key individually. 2158 // TODO: Use the input device configuration to control this behavior more finely. 2159 if (down && getDevice()->isExternal() 2160 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) { 2161 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 2162 } 2163 2164 if (metaStateChanged) { 2165 getContext()->updateGlobalMetaState(); 2166 } 2167 2168 if (down && !isMetaKey(keyCode)) { 2169 getContext()->fadePointer(); 2170 } 2171 2172 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags, 2173 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, 2174 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime); 2175 getListener()->notifyKey(&args); 2176} 2177 2178ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) { 2179 size_t n = mKeyDowns.size(); 2180 for (size_t i = 0; i < n; i++) { 2181 if (mKeyDowns[i].scanCode == scanCode) { 2182 return i; 2183 } 2184 } 2185 return -1; 2186} 2187 2188int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 2189 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode); 2190} 2191 2192int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 2193 return getEventHub()->getScanCodeState(getDeviceId(), scanCode); 2194} 2195 2196bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 2197 const int32_t* keyCodes, uint8_t* outFlags) { 2198 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags); 2199} 2200 2201int32_t KeyboardInputMapper::getMetaState() { 2202 return mMetaState; 2203} 2204 2205void KeyboardInputMapper::resetLedState() { 2206 initializeLedState(mCapsLockLedState, LED_CAPSL); 2207 initializeLedState(mNumLockLedState, LED_NUML); 2208 initializeLedState(mScrollLockLedState, LED_SCROLLL); 2209 2210 updateLedState(true); 2211} 2212 2213void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) { 2214 ledState.avail = getEventHub()->hasLed(getDeviceId(), led); 2215 ledState.on = false; 2216} 2217 2218void KeyboardInputMapper::updateLedState(bool reset) { 2219 updateLedStateForModifier(mCapsLockLedState, LED_CAPSL, 2220 AMETA_CAPS_LOCK_ON, reset); 2221 updateLedStateForModifier(mNumLockLedState, LED_NUML, 2222 AMETA_NUM_LOCK_ON, reset); 2223 updateLedStateForModifier(mScrollLockLedState, LED_SCROLLL, 2224 AMETA_SCROLL_LOCK_ON, reset); 2225} 2226 2227void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState, 2228 int32_t led, int32_t modifier, bool reset) { 2229 if (ledState.avail) { 2230 bool desiredState = (mMetaState & modifier) != 0; 2231 if (reset || ledState.on != desiredState) { 2232 getEventHub()->setLedState(getDeviceId(), led, desiredState); 2233 ledState.on = desiredState; 2234 } 2235 } 2236} 2237 2238 2239// --- CursorInputMapper --- 2240 2241CursorInputMapper::CursorInputMapper(InputDevice* device) : 2242 InputMapper(device) { 2243} 2244 2245CursorInputMapper::~CursorInputMapper() { 2246} 2247 2248uint32_t CursorInputMapper::getSources() { 2249 return mSource; 2250} 2251 2252void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 2253 InputMapper::populateDeviceInfo(info); 2254 2255 if (mParameters.mode == Parameters::MODE_POINTER) { 2256 float minX, minY, maxX, maxY; 2257 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) { 2258 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f); 2259 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f); 2260 } 2261 } else { 2262 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale); 2263 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale); 2264 } 2265 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f); 2266 2267 if (mCursorScrollAccumulator.haveRelativeVWheel()) { 2268 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f); 2269 } 2270 if (mCursorScrollAccumulator.haveRelativeHWheel()) { 2271 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f); 2272 } 2273} 2274 2275void CursorInputMapper::dump(String8& dump) { 2276 dump.append(INDENT2 "Cursor Input Mapper:\n"); 2277 dumpParameters(dump); 2278 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale); 2279 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale); 2280 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision); 2281 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision); 2282 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", 2283 toString(mCursorScrollAccumulator.haveRelativeVWheel())); 2284 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", 2285 toString(mCursorScrollAccumulator.haveRelativeHWheel())); 2286 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale); 2287 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale); 2288 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation); 2289 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState); 2290 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState))); 2291 dump.appendFormat(INDENT3 "DownTime: %lld\n", mDownTime); 2292} 2293 2294void CursorInputMapper::configure(nsecs_t when, 2295 const InputReaderConfiguration* config, uint32_t changes) { 2296 InputMapper::configure(when, config, changes); 2297 2298 if (!changes) { // first time only 2299 mCursorScrollAccumulator.configure(getDevice()); 2300 2301 // Configure basic parameters. 2302 configureParameters(); 2303 2304 // Configure device mode. 2305 switch (mParameters.mode) { 2306 case Parameters::MODE_POINTER: 2307 mSource = AINPUT_SOURCE_MOUSE; 2308 mXPrecision = 1.0f; 2309 mYPrecision = 1.0f; 2310 mXScale = 1.0f; 2311 mYScale = 1.0f; 2312 mPointerController = getPolicy()->obtainPointerController(getDeviceId()); 2313 break; 2314 case Parameters::MODE_NAVIGATION: 2315 mSource = AINPUT_SOURCE_TRACKBALL; 2316 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD; 2317 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD; 2318 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; 2319 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; 2320 break; 2321 } 2322 2323 mVWheelScale = 1.0f; 2324 mHWheelScale = 1.0f; 2325 } 2326 2327 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) { 2328 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters); 2329 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters); 2330 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters); 2331 } 2332 2333 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { 2334 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) { 2335 if (!config->getDisplayInfo(mParameters.associatedDisplayId, 2336 false /*external*/, NULL, NULL, &mOrientation)) { 2337 mOrientation = DISPLAY_ORIENTATION_0; 2338 } 2339 } else { 2340 mOrientation = DISPLAY_ORIENTATION_0; 2341 } 2342 bumpGeneration(); 2343 } 2344} 2345 2346void CursorInputMapper::configureParameters() { 2347 mParameters.mode = Parameters::MODE_POINTER; 2348 String8 cursorModeString; 2349 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) { 2350 if (cursorModeString == "navigation") { 2351 mParameters.mode = Parameters::MODE_NAVIGATION; 2352 } else if (cursorModeString != "pointer" && cursorModeString != "default") { 2353 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string()); 2354 } 2355 } 2356 2357 mParameters.orientationAware = false; 2358 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"), 2359 mParameters.orientationAware); 2360 2361 mParameters.associatedDisplayId = -1; 2362 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) { 2363 mParameters.associatedDisplayId = 0; 2364 } 2365} 2366 2367void CursorInputMapper::dumpParameters(String8& dump) { 2368 dump.append(INDENT3 "Parameters:\n"); 2369 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 2370 mParameters.associatedDisplayId); 2371 2372 switch (mParameters.mode) { 2373 case Parameters::MODE_POINTER: 2374 dump.append(INDENT4 "Mode: pointer\n"); 2375 break; 2376 case Parameters::MODE_NAVIGATION: 2377 dump.append(INDENT4 "Mode: navigation\n"); 2378 break; 2379 default: 2380 ALOG_ASSERT(false); 2381 } 2382 2383 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 2384 toString(mParameters.orientationAware)); 2385} 2386 2387void CursorInputMapper::reset(nsecs_t when) { 2388 mButtonState = 0; 2389 mDownTime = 0; 2390 2391 mPointerVelocityControl.reset(); 2392 mWheelXVelocityControl.reset(); 2393 mWheelYVelocityControl.reset(); 2394 2395 mCursorButtonAccumulator.reset(getDevice()); 2396 mCursorMotionAccumulator.reset(getDevice()); 2397 mCursorScrollAccumulator.reset(getDevice()); 2398 2399 InputMapper::reset(when); 2400} 2401 2402void CursorInputMapper::process(const RawEvent* rawEvent) { 2403 mCursorButtonAccumulator.process(rawEvent); 2404 mCursorMotionAccumulator.process(rawEvent); 2405 mCursorScrollAccumulator.process(rawEvent); 2406 2407 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { 2408 sync(rawEvent->when); 2409 } 2410} 2411 2412void CursorInputMapper::sync(nsecs_t when) { 2413 int32_t lastButtonState = mButtonState; 2414 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState(); 2415 mButtonState = currentButtonState; 2416 2417 bool wasDown = isPointerDown(lastButtonState); 2418 bool down = isPointerDown(currentButtonState); 2419 bool downChanged; 2420 if (!wasDown && down) { 2421 mDownTime = when; 2422 downChanged = true; 2423 } else if (wasDown && !down) { 2424 downChanged = true; 2425 } else { 2426 downChanged = false; 2427 } 2428 nsecs_t downTime = mDownTime; 2429 bool buttonsChanged = currentButtonState != lastButtonState; 2430 bool buttonsPressed = currentButtonState & ~lastButtonState; 2431 2432 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale; 2433 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale; 2434 bool moved = deltaX != 0 || deltaY != 0; 2435 2436 // Rotate delta according to orientation if needed. 2437 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0 2438 && (deltaX != 0.0f || deltaY != 0.0f)) { 2439 rotateDelta(mOrientation, &deltaX, &deltaY); 2440 } 2441 2442 // Move the pointer. 2443 PointerProperties pointerProperties; 2444 pointerProperties.clear(); 2445 pointerProperties.id = 0; 2446 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE; 2447 2448 PointerCoords pointerCoords; 2449 pointerCoords.clear(); 2450 2451 float vscroll = mCursorScrollAccumulator.getRelativeVWheel(); 2452 float hscroll = mCursorScrollAccumulator.getRelativeHWheel(); 2453 bool scrolled = vscroll != 0 || hscroll != 0; 2454 2455 mWheelYVelocityControl.move(when, NULL, &vscroll); 2456 mWheelXVelocityControl.move(when, &hscroll, NULL); 2457 2458 mPointerVelocityControl.move(when, &deltaX, &deltaY); 2459 2460 if (mPointerController != NULL) { 2461 if (moved || scrolled || buttonsChanged) { 2462 mPointerController->setPresentation( 2463 PointerControllerInterface::PRESENTATION_POINTER); 2464 2465 if (moved) { 2466 mPointerController->move(deltaX, deltaY); 2467 } 2468 2469 if (buttonsChanged) { 2470 mPointerController->setButtonState(currentButtonState); 2471 } 2472 2473 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); 2474 } 2475 2476 float x, y; 2477 mPointerController->getPosition(&x, &y); 2478 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); 2479 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 2480 } else { 2481 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); 2482 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); 2483 } 2484 2485 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f); 2486 2487 // Moving an external trackball or mouse should wake the device. 2488 // We don't do this for internal cursor devices to prevent them from waking up 2489 // the device in your pocket. 2490 // TODO: Use the input device configuration to control this behavior more finely. 2491 uint32_t policyFlags = 0; 2492 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) { 2493 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 2494 } 2495 2496 // Synthesize key down from buttons if needed. 2497 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, 2498 policyFlags, lastButtonState, currentButtonState); 2499 2500 // Send motion event. 2501 if (downChanged || moved || scrolled || buttonsChanged) { 2502 int32_t metaState = mContext->getGlobalMetaState(); 2503 int32_t motionEventAction; 2504 if (downChanged) { 2505 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP; 2506 } else if (down || mPointerController == NULL) { 2507 motionEventAction = AMOTION_EVENT_ACTION_MOVE; 2508 } else { 2509 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE; 2510 } 2511 2512 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 2513 motionEventAction, 0, metaState, currentButtonState, 0, 2514 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); 2515 getListener()->notifyMotion(&args); 2516 2517 // Send hover move after UP to tell the application that the mouse is hovering now. 2518 if (motionEventAction == AMOTION_EVENT_ACTION_UP 2519 && mPointerController != NULL) { 2520 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags, 2521 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 2522 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, 2523 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); 2524 getListener()->notifyMotion(&hoverArgs); 2525 } 2526 2527 // Send scroll events. 2528 if (scrolled) { 2529 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); 2530 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); 2531 2532 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags, 2533 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, currentButtonState, 2534 AMOTION_EVENT_EDGE_FLAG_NONE, 2535 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); 2536 getListener()->notifyMotion(&scrollArgs); 2537 } 2538 } 2539 2540 // Synthesize key up from buttons if needed. 2541 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, 2542 policyFlags, lastButtonState, currentButtonState); 2543 2544 mCursorMotionAccumulator.finishSync(); 2545 mCursorScrollAccumulator.finishSync(); 2546} 2547 2548int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 2549 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) { 2550 return getEventHub()->getScanCodeState(getDeviceId(), scanCode); 2551 } else { 2552 return AKEY_STATE_UNKNOWN; 2553 } 2554} 2555 2556void CursorInputMapper::fadePointer() { 2557 if (mPointerController != NULL) { 2558 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); 2559 } 2560} 2561 2562 2563// --- TouchInputMapper --- 2564 2565TouchInputMapper::TouchInputMapper(InputDevice* device) : 2566 InputMapper(device), 2567 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED), 2568 mSurfaceOrientation(-1), mSurfaceWidth(-1), mSurfaceHeight(-1) { 2569} 2570 2571TouchInputMapper::~TouchInputMapper() { 2572} 2573 2574uint32_t TouchInputMapper::getSources() { 2575 return mSource; 2576} 2577 2578void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 2579 InputMapper::populateDeviceInfo(info); 2580 2581 if (mDeviceMode != DEVICE_MODE_DISABLED) { 2582 info->addMotionRange(mOrientedRanges.x); 2583 info->addMotionRange(mOrientedRanges.y); 2584 info->addMotionRange(mOrientedRanges.pressure); 2585 2586 if (mOrientedRanges.haveSize) { 2587 info->addMotionRange(mOrientedRanges.size); 2588 } 2589 2590 if (mOrientedRanges.haveTouchSize) { 2591 info->addMotionRange(mOrientedRanges.touchMajor); 2592 info->addMotionRange(mOrientedRanges.touchMinor); 2593 } 2594 2595 if (mOrientedRanges.haveToolSize) { 2596 info->addMotionRange(mOrientedRanges.toolMajor); 2597 info->addMotionRange(mOrientedRanges.toolMinor); 2598 } 2599 2600 if (mOrientedRanges.haveOrientation) { 2601 info->addMotionRange(mOrientedRanges.orientation); 2602 } 2603 2604 if (mOrientedRanges.haveDistance) { 2605 info->addMotionRange(mOrientedRanges.distance); 2606 } 2607 2608 if (mOrientedRanges.haveTilt) { 2609 info->addMotionRange(mOrientedRanges.tilt); 2610 } 2611 2612 if (mCursorScrollAccumulator.haveRelativeVWheel()) { 2613 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f); 2614 } 2615 if (mCursorScrollAccumulator.haveRelativeHWheel()) { 2616 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f); 2617 } 2618 } 2619} 2620 2621void TouchInputMapper::dump(String8& dump) { 2622 dump.append(INDENT2 "Touch Input Mapper:\n"); 2623 dumpParameters(dump); 2624 dumpVirtualKeys(dump); 2625 dumpRawPointerAxes(dump); 2626 dumpCalibration(dump); 2627 dumpSurface(dump); 2628 2629 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n"); 2630 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale); 2631 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale); 2632 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision); 2633 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision); 2634 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale); 2635 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale); 2636 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale); 2637 dump.appendFormat(INDENT4 "OrientationCenter: %0.3f\n", mOrientationCenter); 2638 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale); 2639 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale); 2640 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt)); 2641 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter); 2642 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale); 2643 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter); 2644 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale); 2645 2646 dump.appendFormat(INDENT3 "Last Button State: 0x%08x\n", mLastButtonState); 2647 2648 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n", 2649 mLastRawPointerData.pointerCount); 2650 for (uint32_t i = 0; i < mLastRawPointerData.pointerCount; i++) { 2651 const RawPointerData::Pointer& pointer = mLastRawPointerData.pointers[i]; 2652 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, " 2653 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, " 2654 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, " 2655 "toolType=%d, isHovering=%s\n", i, 2656 pointer.id, pointer.x, pointer.y, pointer.pressure, 2657 pointer.touchMajor, pointer.touchMinor, 2658 pointer.toolMajor, pointer.toolMinor, 2659 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance, 2660 pointer.toolType, toString(pointer.isHovering)); 2661 } 2662 2663 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n", 2664 mLastCookedPointerData.pointerCount); 2665 for (uint32_t i = 0; i < mLastCookedPointerData.pointerCount; i++) { 2666 const PointerProperties& pointerProperties = mLastCookedPointerData.pointerProperties[i]; 2667 const PointerCoords& pointerCoords = mLastCookedPointerData.pointerCoords[i]; 2668 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, " 2669 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, " 2670 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, " 2671 "toolType=%d, isHovering=%s\n", i, 2672 pointerProperties.id, 2673 pointerCoords.getX(), 2674 pointerCoords.getY(), 2675 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), 2676 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), 2677 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), 2678 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), 2679 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), 2680 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION), 2681 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT), 2682 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE), 2683 pointerProperties.toolType, 2684 toString(mLastCookedPointerData.isHovering(i))); 2685 } 2686 2687 if (mDeviceMode == DEVICE_MODE_POINTER) { 2688 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n"); 2689 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n", 2690 mPointerXMovementScale); 2691 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n", 2692 mPointerYMovementScale); 2693 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n", 2694 mPointerXZoomScale); 2695 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n", 2696 mPointerYZoomScale); 2697 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n", 2698 mPointerGestureMaxSwipeWidth); 2699 } 2700} 2701 2702void TouchInputMapper::configure(nsecs_t when, 2703 const InputReaderConfiguration* config, uint32_t changes) { 2704 InputMapper::configure(when, config, changes); 2705 2706 mConfig = *config; 2707 2708 if (!changes) { // first time only 2709 // Configure basic parameters. 2710 configureParameters(); 2711 2712 // Configure common accumulators. 2713 mCursorScrollAccumulator.configure(getDevice()); 2714 mTouchButtonAccumulator.configure(getDevice()); 2715 2716 // Configure absolute axis information. 2717 configureRawPointerAxes(); 2718 2719 // Prepare input device calibration. 2720 parseCalibration(); 2721 resolveCalibration(); 2722 } 2723 2724 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) { 2725 // Update pointer speed. 2726 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters); 2727 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters); 2728 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters); 2729 } 2730 2731 bool resetNeeded = false; 2732 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO 2733 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT 2734 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES))) { 2735 // Configure device sources, surface dimensions, orientation and 2736 // scaling factors. 2737 configureSurface(when, &resetNeeded); 2738 } 2739 2740 if (changes && resetNeeded) { 2741 // Send reset, unless this is the first time the device has been configured, 2742 // in which case the reader will call reset itself after all mappers are ready. 2743 getDevice()->notifyReset(when); 2744 } 2745} 2746 2747void TouchInputMapper::configureParameters() { 2748 // Use the pointer presentation mode for devices that do not support distinct 2749 // multitouch. The spot-based presentation relies on being able to accurately 2750 // locate two or more fingers on the touch pad. 2751 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT) 2752 ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS; 2753 2754 String8 gestureModeString; 2755 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"), 2756 gestureModeString)) { 2757 if (gestureModeString == "pointer") { 2758 mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER; 2759 } else if (gestureModeString == "spots") { 2760 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS; 2761 } else if (gestureModeString != "default") { 2762 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string()); 2763 } 2764 } 2765 2766 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) { 2767 // The device is a touch screen. 2768 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; 2769 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) { 2770 // The device is a pointing device like a track pad. 2771 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; 2772 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X) 2773 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) { 2774 // The device is a cursor device with a touch pad attached. 2775 // By default don't use the touch pad to move the pointer. 2776 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; 2777 } else { 2778 // The device is a touch pad of unknown purpose. 2779 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; 2780 } 2781 2782 String8 deviceTypeString; 2783 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"), 2784 deviceTypeString)) { 2785 if (deviceTypeString == "touchScreen") { 2786 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; 2787 } else if (deviceTypeString == "touchPad") { 2788 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; 2789 } else if (deviceTypeString == "pointer") { 2790 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; 2791 } else if (deviceTypeString != "default") { 2792 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string()); 2793 } 2794 } 2795 2796 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN; 2797 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"), 2798 mParameters.orientationAware); 2799 2800 mParameters.associatedDisplayId = -1; 2801 mParameters.associatedDisplayIsExternal = false; 2802 if (mParameters.orientationAware 2803 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN 2804 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) { 2805 mParameters.associatedDisplayIsExternal = 2806 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN 2807 && getDevice()->isExternal(); 2808 mParameters.associatedDisplayId = 0; 2809 } 2810} 2811 2812void TouchInputMapper::dumpParameters(String8& dump) { 2813 dump.append(INDENT3 "Parameters:\n"); 2814 2815 switch (mParameters.gestureMode) { 2816 case Parameters::GESTURE_MODE_POINTER: 2817 dump.append(INDENT4 "GestureMode: pointer\n"); 2818 break; 2819 case Parameters::GESTURE_MODE_SPOTS: 2820 dump.append(INDENT4 "GestureMode: spots\n"); 2821 break; 2822 default: 2823 assert(false); 2824 } 2825 2826 switch (mParameters.deviceType) { 2827 case Parameters::DEVICE_TYPE_TOUCH_SCREEN: 2828 dump.append(INDENT4 "DeviceType: touchScreen\n"); 2829 break; 2830 case Parameters::DEVICE_TYPE_TOUCH_PAD: 2831 dump.append(INDENT4 "DeviceType: touchPad\n"); 2832 break; 2833 case Parameters::DEVICE_TYPE_POINTER: 2834 dump.append(INDENT4 "DeviceType: pointer\n"); 2835 break; 2836 default: 2837 ALOG_ASSERT(false); 2838 } 2839 2840 dump.appendFormat(INDENT4 "AssociatedDisplay: id=%d, isExternal=%s\n", 2841 mParameters.associatedDisplayId, toString(mParameters.associatedDisplayIsExternal)); 2842 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 2843 toString(mParameters.orientationAware)); 2844} 2845 2846void TouchInputMapper::configureRawPointerAxes() { 2847 mRawPointerAxes.clear(); 2848} 2849 2850void TouchInputMapper::dumpRawPointerAxes(String8& dump) { 2851 dump.append(INDENT3 "Raw Touch Axes:\n"); 2852 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X"); 2853 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y"); 2854 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure"); 2855 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor"); 2856 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor"); 2857 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor"); 2858 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor"); 2859 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation"); 2860 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance"); 2861 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX"); 2862 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY"); 2863 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId"); 2864 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot"); 2865} 2866 2867void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { 2868 int32_t oldDeviceMode = mDeviceMode; 2869 2870 // Determine device mode. 2871 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER 2872 && mConfig.pointerGesturesEnabled) { 2873 mSource = AINPUT_SOURCE_MOUSE; 2874 mDeviceMode = DEVICE_MODE_POINTER; 2875 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN 2876 && mParameters.associatedDisplayId >= 0) { 2877 mSource = AINPUT_SOURCE_TOUCHSCREEN; 2878 mDeviceMode = DEVICE_MODE_DIRECT; 2879 } else { 2880 mSource = AINPUT_SOURCE_TOUCHPAD; 2881 mDeviceMode = DEVICE_MODE_UNSCALED; 2882 } 2883 2884 // Ensure we have valid X and Y axes. 2885 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) { 2886 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! " 2887 "The device will be inoperable.", getDeviceName().string()); 2888 mDeviceMode = DEVICE_MODE_DISABLED; 2889 return; 2890 } 2891 2892 // Get associated display dimensions. 2893 if (mParameters.associatedDisplayId >= 0) { 2894 if (!mConfig.getDisplayInfo(mParameters.associatedDisplayId, 2895 mParameters.associatedDisplayIsExternal, 2896 &mAssociatedDisplayWidth, &mAssociatedDisplayHeight, 2897 &mAssociatedDisplayOrientation)) { 2898 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated " 2899 "display %d. The device will be inoperable until the display size " 2900 "becomes available.", 2901 getDeviceName().string(), mParameters.associatedDisplayId); 2902 mDeviceMode = DEVICE_MODE_DISABLED; 2903 return; 2904 } 2905 } 2906 2907 // Configure dimensions. 2908 int32_t width, height, orientation; 2909 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) { 2910 width = mAssociatedDisplayWidth; 2911 height = mAssociatedDisplayHeight; 2912 orientation = mParameters.orientationAware ? 2913 mAssociatedDisplayOrientation : DISPLAY_ORIENTATION_0; 2914 } else { 2915 width = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; 2916 height = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; 2917 orientation = DISPLAY_ORIENTATION_0; 2918 } 2919 2920 // If moving between pointer modes, need to reset some state. 2921 bool deviceModeChanged; 2922 if (mDeviceMode != oldDeviceMode) { 2923 deviceModeChanged = true; 2924 mOrientedRanges.clear(); 2925 } 2926 2927 // Create pointer controller if needed. 2928 if (mDeviceMode == DEVICE_MODE_POINTER || 2929 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) { 2930 if (mPointerController == NULL) { 2931 mPointerController = getPolicy()->obtainPointerController(getDeviceId()); 2932 } 2933 } else { 2934 mPointerController.clear(); 2935 } 2936 2937 bool orientationChanged = mSurfaceOrientation != orientation; 2938 if (orientationChanged) { 2939 mSurfaceOrientation = orientation; 2940 } 2941 2942 bool sizeChanged = mSurfaceWidth != width || mSurfaceHeight != height; 2943 if (sizeChanged || deviceModeChanged) { 2944 ALOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d, mode is %d", 2945 getDeviceId(), getDeviceName().string(), width, height, mDeviceMode); 2946 2947 mSurfaceWidth = width; 2948 mSurfaceHeight = height; 2949 2950 // Configure X and Y factors. 2951 mXScale = float(width) / (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1); 2952 mYScale = float(height) / (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1); 2953 mXPrecision = 1.0f / mXScale; 2954 mYPrecision = 1.0f / mYScale; 2955 2956 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X; 2957 mOrientedRanges.x.source = mSource; 2958 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y; 2959 mOrientedRanges.y.source = mSource; 2960 2961 configureVirtualKeys(); 2962 2963 // Scale factor for terms that are not oriented in a particular axis. 2964 // If the pixels are square then xScale == yScale otherwise we fake it 2965 // by choosing an average. 2966 mGeometricScale = avg(mXScale, mYScale); 2967 2968 // Size of diagonal axis. 2969 float diagonalSize = hypotf(width, height); 2970 2971 // Size factors. 2972 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) { 2973 if (mRawPointerAxes.touchMajor.valid 2974 && mRawPointerAxes.touchMajor.maxValue != 0) { 2975 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue; 2976 } else if (mRawPointerAxes.toolMajor.valid 2977 && mRawPointerAxes.toolMajor.maxValue != 0) { 2978 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue; 2979 } else { 2980 mSizeScale = 0.0f; 2981 } 2982 2983 mOrientedRanges.haveTouchSize = true; 2984 mOrientedRanges.haveToolSize = true; 2985 mOrientedRanges.haveSize = true; 2986 2987 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR; 2988 mOrientedRanges.touchMajor.source = mSource; 2989 mOrientedRanges.touchMajor.min = 0; 2990 mOrientedRanges.touchMajor.max = diagonalSize; 2991 mOrientedRanges.touchMajor.flat = 0; 2992 mOrientedRanges.touchMajor.fuzz = 0; 2993 2994 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor; 2995 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR; 2996 2997 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR; 2998 mOrientedRanges.toolMajor.source = mSource; 2999 mOrientedRanges.toolMajor.min = 0; 3000 mOrientedRanges.toolMajor.max = diagonalSize; 3001 mOrientedRanges.toolMajor.flat = 0; 3002 mOrientedRanges.toolMajor.fuzz = 0; 3003 3004 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor; 3005 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR; 3006 3007 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE; 3008 mOrientedRanges.size.source = mSource; 3009 mOrientedRanges.size.min = 0; 3010 mOrientedRanges.size.max = 1.0; 3011 mOrientedRanges.size.flat = 0; 3012 mOrientedRanges.size.fuzz = 0; 3013 } else { 3014 mSizeScale = 0.0f; 3015 } 3016 3017 // Pressure factors. 3018 mPressureScale = 0; 3019 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL 3020 || mCalibration.pressureCalibration 3021 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) { 3022 if (mCalibration.havePressureScale) { 3023 mPressureScale = mCalibration.pressureScale; 3024 } else if (mRawPointerAxes.pressure.valid 3025 && mRawPointerAxes.pressure.maxValue != 0) { 3026 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue; 3027 } 3028 } 3029 3030 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE; 3031 mOrientedRanges.pressure.source = mSource; 3032 mOrientedRanges.pressure.min = 0; 3033 mOrientedRanges.pressure.max = 1.0; 3034 mOrientedRanges.pressure.flat = 0; 3035 mOrientedRanges.pressure.fuzz = 0; 3036 3037 // Tilt 3038 mTiltXCenter = 0; 3039 mTiltXScale = 0; 3040 mTiltYCenter = 0; 3041 mTiltYScale = 0; 3042 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid; 3043 if (mHaveTilt) { 3044 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, 3045 mRawPointerAxes.tiltX.maxValue); 3046 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, 3047 mRawPointerAxes.tiltY.maxValue); 3048 mTiltXScale = M_PI / 180; 3049 mTiltYScale = M_PI / 180; 3050 3051 mOrientedRanges.haveTilt = true; 3052 3053 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT; 3054 mOrientedRanges.tilt.source = mSource; 3055 mOrientedRanges.tilt.min = 0; 3056 mOrientedRanges.tilt.max = M_PI_2; 3057 mOrientedRanges.tilt.flat = 0; 3058 mOrientedRanges.tilt.fuzz = 0; 3059 } 3060 3061 // Orientation 3062 mOrientationCenter = 0; 3063 mOrientationScale = 0; 3064 if (mHaveTilt) { 3065 mOrientedRanges.haveOrientation = true; 3066 3067 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION; 3068 mOrientedRanges.orientation.source = mSource; 3069 mOrientedRanges.orientation.min = -M_PI; 3070 mOrientedRanges.orientation.max = M_PI; 3071 mOrientedRanges.orientation.flat = 0; 3072 mOrientedRanges.orientation.fuzz = 0; 3073 } else if (mCalibration.orientationCalibration != 3074 Calibration::ORIENTATION_CALIBRATION_NONE) { 3075 if (mCalibration.orientationCalibration 3076 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) { 3077 if (mRawPointerAxes.orientation.valid) { 3078 mOrientationCenter = avg(mRawPointerAxes.orientation.minValue, 3079 mRawPointerAxes.orientation.maxValue); 3080 mOrientationScale = M_PI / (mRawPointerAxes.orientation.maxValue - 3081 mRawPointerAxes.orientation.minValue); 3082 } 3083 } 3084 3085 mOrientedRanges.haveOrientation = true; 3086 3087 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION; 3088 mOrientedRanges.orientation.source = mSource; 3089 mOrientedRanges.orientation.min = -M_PI_2; 3090 mOrientedRanges.orientation.max = M_PI_2; 3091 mOrientedRanges.orientation.flat = 0; 3092 mOrientedRanges.orientation.fuzz = 0; 3093 } 3094 3095 // Distance 3096 mDistanceScale = 0; 3097 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) { 3098 if (mCalibration.distanceCalibration 3099 == Calibration::DISTANCE_CALIBRATION_SCALED) { 3100 if (mCalibration.haveDistanceScale) { 3101 mDistanceScale = mCalibration.distanceScale; 3102 } else { 3103 mDistanceScale = 1.0f; 3104 } 3105 } 3106 3107 mOrientedRanges.haveDistance = true; 3108 3109 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE; 3110 mOrientedRanges.distance.source = mSource; 3111 mOrientedRanges.distance.min = 3112 mRawPointerAxes.distance.minValue * mDistanceScale; 3113 mOrientedRanges.distance.max = 3114 mRawPointerAxes.distance.minValue * mDistanceScale; 3115 mOrientedRanges.distance.flat = 0; 3116 mOrientedRanges.distance.fuzz = 3117 mRawPointerAxes.distance.fuzz * mDistanceScale; 3118 } 3119 } 3120 3121 if (orientationChanged || sizeChanged || deviceModeChanged) { 3122 // Compute oriented surface dimensions, precision, scales and ranges. 3123 // Note that the maximum value reported is an inclusive maximum value so it is one 3124 // unit less than the total width or height of surface. 3125 switch (mSurfaceOrientation) { 3126 case DISPLAY_ORIENTATION_90: 3127 case DISPLAY_ORIENTATION_270: 3128 mOrientedSurfaceWidth = mSurfaceHeight; 3129 mOrientedSurfaceHeight = mSurfaceWidth; 3130 3131 mOrientedXPrecision = mYPrecision; 3132 mOrientedYPrecision = mXPrecision; 3133 3134 mOrientedRanges.x.min = 0; 3135 mOrientedRanges.x.max = (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue) 3136 * mYScale; 3137 mOrientedRanges.x.flat = 0; 3138 mOrientedRanges.x.fuzz = mYScale; 3139 3140 mOrientedRanges.y.min = 0; 3141 mOrientedRanges.y.max = (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue) 3142 * mXScale; 3143 mOrientedRanges.y.flat = 0; 3144 mOrientedRanges.y.fuzz = mXScale; 3145 break; 3146 3147 default: 3148 mOrientedSurfaceWidth = mSurfaceWidth; 3149 mOrientedSurfaceHeight = mSurfaceHeight; 3150 3151 mOrientedXPrecision = mXPrecision; 3152 mOrientedYPrecision = mYPrecision; 3153 3154 mOrientedRanges.x.min = 0; 3155 mOrientedRanges.x.max = (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue) 3156 * mXScale; 3157 mOrientedRanges.x.flat = 0; 3158 mOrientedRanges.x.fuzz = mXScale; 3159 3160 mOrientedRanges.y.min = 0; 3161 mOrientedRanges.y.max = (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue) 3162 * mYScale; 3163 mOrientedRanges.y.flat = 0; 3164 mOrientedRanges.y.fuzz = mYScale; 3165 break; 3166 } 3167 3168 // Compute pointer gesture detection parameters. 3169 if (mDeviceMode == DEVICE_MODE_POINTER) { 3170 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; 3171 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; 3172 float rawDiagonal = hypotf(rawWidth, rawHeight); 3173 float displayDiagonal = hypotf(mAssociatedDisplayWidth, 3174 mAssociatedDisplayHeight); 3175 3176 // Scale movements such that one whole swipe of the touch pad covers a 3177 // given area relative to the diagonal size of the display when no acceleration 3178 // is applied. 3179 // Assume that the touch pad has a square aspect ratio such that movements in 3180 // X and Y of the same number of raw units cover the same physical distance. 3181 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio 3182 * displayDiagonal / rawDiagonal; 3183 mPointerYMovementScale = mPointerXMovementScale; 3184 3185 // Scale zooms to cover a smaller range of the display than movements do. 3186 // This value determines the area around the pointer that is affected by freeform 3187 // pointer gestures. 3188 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio 3189 * displayDiagonal / rawDiagonal; 3190 mPointerYZoomScale = mPointerXZoomScale; 3191 3192 // Max width between pointers to detect a swipe gesture is more than some fraction 3193 // of the diagonal axis of the touch pad. Touches that are wider than this are 3194 // translated into freeform gestures. 3195 mPointerGestureMaxSwipeWidth = 3196 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal; 3197 } 3198 3199 // Abort current pointer usages because the state has changed. 3200 abortPointerUsage(when, 0 /*policyFlags*/); 3201 3202 // Inform the dispatcher about the changes. 3203 *outResetNeeded = true; 3204 bumpGeneration(); 3205 } 3206} 3207 3208void TouchInputMapper::dumpSurface(String8& dump) { 3209 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth); 3210 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight); 3211 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation); 3212} 3213 3214void TouchInputMapper::configureVirtualKeys() { 3215 Vector<VirtualKeyDefinition> virtualKeyDefinitions; 3216 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions); 3217 3218 mVirtualKeys.clear(); 3219 3220 if (virtualKeyDefinitions.size() == 0) { 3221 return; 3222 } 3223 3224 mVirtualKeys.setCapacity(virtualKeyDefinitions.size()); 3225 3226 int32_t touchScreenLeft = mRawPointerAxes.x.minValue; 3227 int32_t touchScreenTop = mRawPointerAxes.y.minValue; 3228 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; 3229 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; 3230 3231 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) { 3232 const VirtualKeyDefinition& virtualKeyDefinition = 3233 virtualKeyDefinitions[i]; 3234 3235 mVirtualKeys.add(); 3236 VirtualKey& virtualKey = mVirtualKeys.editTop(); 3237 3238 virtualKey.scanCode = virtualKeyDefinition.scanCode; 3239 int32_t keyCode; 3240 uint32_t flags; 3241 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, &keyCode, &flags)) { 3242 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", 3243 virtualKey.scanCode); 3244 mVirtualKeys.pop(); // drop the key 3245 continue; 3246 } 3247 3248 virtualKey.keyCode = keyCode; 3249 virtualKey.flags = flags; 3250 3251 // convert the key definition's display coordinates into touch coordinates for a hit box 3252 int32_t halfWidth = virtualKeyDefinition.width / 2; 3253 int32_t halfHeight = virtualKeyDefinition.height / 2; 3254 3255 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) 3256 * touchScreenWidth / mSurfaceWidth + touchScreenLeft; 3257 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth) 3258 * touchScreenWidth / mSurfaceWidth + touchScreenLeft; 3259 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) 3260 * touchScreenHeight / mSurfaceHeight + touchScreenTop; 3261 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) 3262 * touchScreenHeight / mSurfaceHeight + touchScreenTop; 3263 } 3264} 3265 3266void TouchInputMapper::dumpVirtualKeys(String8& dump) { 3267 if (!mVirtualKeys.isEmpty()) { 3268 dump.append(INDENT3 "Virtual Keys:\n"); 3269 3270 for (size_t i = 0; i < mVirtualKeys.size(); i++) { 3271 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i); 3272 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, " 3273 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n", 3274 i, virtualKey.scanCode, virtualKey.keyCode, 3275 virtualKey.hitLeft, virtualKey.hitRight, 3276 virtualKey.hitTop, virtualKey.hitBottom); 3277 } 3278 } 3279} 3280 3281void TouchInputMapper::parseCalibration() { 3282 const PropertyMap& in = getDevice()->getConfiguration(); 3283 Calibration& out = mCalibration; 3284 3285 // Size 3286 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT; 3287 String8 sizeCalibrationString; 3288 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) { 3289 if (sizeCalibrationString == "none") { 3290 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; 3291 } else if (sizeCalibrationString == "geometric") { 3292 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC; 3293 } else if (sizeCalibrationString == "diameter") { 3294 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER; 3295 } else if (sizeCalibrationString == "area") { 3296 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA; 3297 } else if (sizeCalibrationString != "default") { 3298 ALOGW("Invalid value for touch.size.calibration: '%s'", 3299 sizeCalibrationString.string()); 3300 } 3301 } 3302 3303 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), 3304 out.sizeScale); 3305 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), 3306 out.sizeBias); 3307 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), 3308 out.sizeIsSummed); 3309 3310 // Pressure 3311 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT; 3312 String8 pressureCalibrationString; 3313 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) { 3314 if (pressureCalibrationString == "none") { 3315 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; 3316 } else if (pressureCalibrationString == "physical") { 3317 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; 3318 } else if (pressureCalibrationString == "amplitude") { 3319 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE; 3320 } else if (pressureCalibrationString != "default") { 3321 ALOGW("Invalid value for touch.pressure.calibration: '%s'", 3322 pressureCalibrationString.string()); 3323 } 3324 } 3325 3326 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), 3327 out.pressureScale); 3328 3329 // Orientation 3330 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT; 3331 String8 orientationCalibrationString; 3332 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) { 3333 if (orientationCalibrationString == "none") { 3334 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; 3335 } else if (orientationCalibrationString == "interpolated") { 3336 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; 3337 } else if (orientationCalibrationString == "vector") { 3338 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR; 3339 } else if (orientationCalibrationString != "default") { 3340 ALOGW("Invalid value for touch.orientation.calibration: '%s'", 3341 orientationCalibrationString.string()); 3342 } 3343 } 3344 3345 // Distance 3346 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT; 3347 String8 distanceCalibrationString; 3348 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) { 3349 if (distanceCalibrationString == "none") { 3350 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE; 3351 } else if (distanceCalibrationString == "scaled") { 3352 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED; 3353 } else if (distanceCalibrationString != "default") { 3354 ALOGW("Invalid value for touch.distance.calibration: '%s'", 3355 distanceCalibrationString.string()); 3356 } 3357 } 3358 3359 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), 3360 out.distanceScale); 3361} 3362 3363void TouchInputMapper::resolveCalibration() { 3364 // Size 3365 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) { 3366 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) { 3367 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC; 3368 } 3369 } else { 3370 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; 3371 } 3372 3373 // Pressure 3374 if (mRawPointerAxes.pressure.valid) { 3375 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) { 3376 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; 3377 } 3378 } else { 3379 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; 3380 } 3381 3382 // Orientation 3383 if (mRawPointerAxes.orientation.valid) { 3384 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) { 3385 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; 3386 } 3387 } else { 3388 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; 3389 } 3390 3391 // Distance 3392 if (mRawPointerAxes.distance.valid) { 3393 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) { 3394 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED; 3395 } 3396 } else { 3397 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE; 3398 } 3399} 3400 3401void TouchInputMapper::dumpCalibration(String8& dump) { 3402 dump.append(INDENT3 "Calibration:\n"); 3403 3404 // Size 3405 switch (mCalibration.sizeCalibration) { 3406 case Calibration::SIZE_CALIBRATION_NONE: 3407 dump.append(INDENT4 "touch.size.calibration: none\n"); 3408 break; 3409 case Calibration::SIZE_CALIBRATION_GEOMETRIC: 3410 dump.append(INDENT4 "touch.size.calibration: geometric\n"); 3411 break; 3412 case Calibration::SIZE_CALIBRATION_DIAMETER: 3413 dump.append(INDENT4 "touch.size.calibration: diameter\n"); 3414 break; 3415 case Calibration::SIZE_CALIBRATION_AREA: 3416 dump.append(INDENT4 "touch.size.calibration: area\n"); 3417 break; 3418 default: 3419 ALOG_ASSERT(false); 3420 } 3421 3422 if (mCalibration.haveSizeScale) { 3423 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n", 3424 mCalibration.sizeScale); 3425 } 3426 3427 if (mCalibration.haveSizeBias) { 3428 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n", 3429 mCalibration.sizeBias); 3430 } 3431 3432 if (mCalibration.haveSizeIsSummed) { 3433 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n", 3434 toString(mCalibration.sizeIsSummed)); 3435 } 3436 3437 // Pressure 3438 switch (mCalibration.pressureCalibration) { 3439 case Calibration::PRESSURE_CALIBRATION_NONE: 3440 dump.append(INDENT4 "touch.pressure.calibration: none\n"); 3441 break; 3442 case Calibration::PRESSURE_CALIBRATION_PHYSICAL: 3443 dump.append(INDENT4 "touch.pressure.calibration: physical\n"); 3444 break; 3445 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: 3446 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n"); 3447 break; 3448 default: 3449 ALOG_ASSERT(false); 3450 } 3451 3452 if (mCalibration.havePressureScale) { 3453 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n", 3454 mCalibration.pressureScale); 3455 } 3456 3457 // Orientation 3458 switch (mCalibration.orientationCalibration) { 3459 case Calibration::ORIENTATION_CALIBRATION_NONE: 3460 dump.append(INDENT4 "touch.orientation.calibration: none\n"); 3461 break; 3462 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: 3463 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n"); 3464 break; 3465 case Calibration::ORIENTATION_CALIBRATION_VECTOR: 3466 dump.append(INDENT4 "touch.orientation.calibration: vector\n"); 3467 break; 3468 default: 3469 ALOG_ASSERT(false); 3470 } 3471 3472 // Distance 3473 switch (mCalibration.distanceCalibration) { 3474 case Calibration::DISTANCE_CALIBRATION_NONE: 3475 dump.append(INDENT4 "touch.distance.calibration: none\n"); 3476 break; 3477 case Calibration::DISTANCE_CALIBRATION_SCALED: 3478 dump.append(INDENT4 "touch.distance.calibration: scaled\n"); 3479 break; 3480 default: 3481 ALOG_ASSERT(false); 3482 } 3483 3484 if (mCalibration.haveDistanceScale) { 3485 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n", 3486 mCalibration.distanceScale); 3487 } 3488} 3489 3490void TouchInputMapper::reset(nsecs_t when) { 3491 mCursorButtonAccumulator.reset(getDevice()); 3492 mCursorScrollAccumulator.reset(getDevice()); 3493 mTouchButtonAccumulator.reset(getDevice()); 3494 3495 mPointerVelocityControl.reset(); 3496 mWheelXVelocityControl.reset(); 3497 mWheelYVelocityControl.reset(); 3498 3499 mCurrentRawPointerData.clear(); 3500 mLastRawPointerData.clear(); 3501 mCurrentCookedPointerData.clear(); 3502 mLastCookedPointerData.clear(); 3503 mCurrentButtonState = 0; 3504 mLastButtonState = 0; 3505 mCurrentRawVScroll = 0; 3506 mCurrentRawHScroll = 0; 3507 mCurrentFingerIdBits.clear(); 3508 mLastFingerIdBits.clear(); 3509 mCurrentStylusIdBits.clear(); 3510 mLastStylusIdBits.clear(); 3511 mCurrentMouseIdBits.clear(); 3512 mLastMouseIdBits.clear(); 3513 mPointerUsage = POINTER_USAGE_NONE; 3514 mSentHoverEnter = false; 3515 mDownTime = 0; 3516 3517 mCurrentVirtualKey.down = false; 3518 3519 mPointerGesture.reset(); 3520 mPointerSimple.reset(); 3521 3522 if (mPointerController != NULL) { 3523 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); 3524 mPointerController->clearSpots(); 3525 } 3526 3527 InputMapper::reset(when); 3528} 3529 3530void TouchInputMapper::process(const RawEvent* rawEvent) { 3531 mCursorButtonAccumulator.process(rawEvent); 3532 mCursorScrollAccumulator.process(rawEvent); 3533 mTouchButtonAccumulator.process(rawEvent); 3534 3535 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { 3536 sync(rawEvent->when); 3537 } 3538} 3539 3540void TouchInputMapper::sync(nsecs_t when) { 3541 // Sync button state. 3542 mCurrentButtonState = mTouchButtonAccumulator.getButtonState() 3543 | mCursorButtonAccumulator.getButtonState(); 3544 3545 // Sync scroll state. 3546 mCurrentRawVScroll = mCursorScrollAccumulator.getRelativeVWheel(); 3547 mCurrentRawHScroll = mCursorScrollAccumulator.getRelativeHWheel(); 3548 mCursorScrollAccumulator.finishSync(); 3549 3550 // Sync touch state. 3551 bool havePointerIds = true; 3552 mCurrentRawPointerData.clear(); 3553 syncTouch(when, &havePointerIds); 3554 3555#if DEBUG_RAW_EVENTS 3556 if (!havePointerIds) { 3557 ALOGD("syncTouch: pointerCount %d -> %d, no pointer ids", 3558 mLastRawPointerData.pointerCount, 3559 mCurrentRawPointerData.pointerCount); 3560 } else { 3561 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, " 3562 "hovering ids 0x%08x -> 0x%08x", 3563 mLastRawPointerData.pointerCount, 3564 mCurrentRawPointerData.pointerCount, 3565 mLastRawPointerData.touchingIdBits.value, 3566 mCurrentRawPointerData.touchingIdBits.value, 3567 mLastRawPointerData.hoveringIdBits.value, 3568 mCurrentRawPointerData.hoveringIdBits.value); 3569 } 3570#endif 3571 3572 // Reset state that we will compute below. 3573 mCurrentFingerIdBits.clear(); 3574 mCurrentStylusIdBits.clear(); 3575 mCurrentMouseIdBits.clear(); 3576 mCurrentCookedPointerData.clear(); 3577 3578 if (mDeviceMode == DEVICE_MODE_DISABLED) { 3579 // Drop all input if the device is disabled. 3580 mCurrentRawPointerData.clear(); 3581 mCurrentButtonState = 0; 3582 } else { 3583 // Preprocess pointer data. 3584 if (!havePointerIds) { 3585 assignPointerIds(); 3586 } 3587 3588 // Handle policy on initial down or hover events. 3589 uint32_t policyFlags = 0; 3590 bool initialDown = mLastRawPointerData.pointerCount == 0 3591 && mCurrentRawPointerData.pointerCount != 0; 3592 bool buttonsPressed = mCurrentButtonState & ~mLastButtonState; 3593 if (initialDown || buttonsPressed) { 3594 // If this is a touch screen, hide the pointer on an initial down. 3595 if (mDeviceMode == DEVICE_MODE_DIRECT) { 3596 getContext()->fadePointer(); 3597 } 3598 3599 // Initial downs on external touch devices should wake the device. 3600 // We don't do this for internal touch screens to prevent them from waking 3601 // up in your pocket. 3602 // TODO: Use the input device configuration to control this behavior more finely. 3603 if (getDevice()->isExternal()) { 3604 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 3605 } 3606 } 3607 3608 // Synthesize key down from raw buttons if needed. 3609 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, 3610 policyFlags, mLastButtonState, mCurrentButtonState); 3611 3612 // Consume raw off-screen touches before cooking pointer data. 3613 // If touches are consumed, subsequent code will not receive any pointer data. 3614 if (consumeRawTouches(when, policyFlags)) { 3615 mCurrentRawPointerData.clear(); 3616 } 3617 3618 // Cook pointer data. This call populates the mCurrentCookedPointerData structure 3619 // with cooked pointer data that has the same ids and indices as the raw data. 3620 // The following code can use either the raw or cooked data, as needed. 3621 cookPointerData(); 3622 3623 // Dispatch the touches either directly or by translation through a pointer on screen. 3624 if (mDeviceMode == DEVICE_MODE_POINTER) { 3625 for (BitSet32 idBits(mCurrentRawPointerData.touchingIdBits); !idBits.isEmpty(); ) { 3626 uint32_t id = idBits.clearFirstMarkedBit(); 3627 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); 3628 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS 3629 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { 3630 mCurrentStylusIdBits.markBit(id); 3631 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER 3632 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { 3633 mCurrentFingerIdBits.markBit(id); 3634 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { 3635 mCurrentMouseIdBits.markBit(id); 3636 } 3637 } 3638 for (BitSet32 idBits(mCurrentRawPointerData.hoveringIdBits); !idBits.isEmpty(); ) { 3639 uint32_t id = idBits.clearFirstMarkedBit(); 3640 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); 3641 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS 3642 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { 3643 mCurrentStylusIdBits.markBit(id); 3644 } 3645 } 3646 3647 // Stylus takes precedence over all tools, then mouse, then finger. 3648 PointerUsage pointerUsage = mPointerUsage; 3649 if (!mCurrentStylusIdBits.isEmpty()) { 3650 mCurrentMouseIdBits.clear(); 3651 mCurrentFingerIdBits.clear(); 3652 pointerUsage = POINTER_USAGE_STYLUS; 3653 } else if (!mCurrentMouseIdBits.isEmpty()) { 3654 mCurrentFingerIdBits.clear(); 3655 pointerUsage = POINTER_USAGE_MOUSE; 3656 } else if (!mCurrentFingerIdBits.isEmpty() || isPointerDown(mCurrentButtonState)) { 3657 pointerUsage = POINTER_USAGE_GESTURES; 3658 } 3659 3660 dispatchPointerUsage(when, policyFlags, pointerUsage); 3661 } else { 3662 if (mDeviceMode == DEVICE_MODE_DIRECT 3663 && mConfig.showTouches && mPointerController != NULL) { 3664 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT); 3665 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); 3666 3667 mPointerController->setButtonState(mCurrentButtonState); 3668 mPointerController->setSpots(mCurrentCookedPointerData.pointerCoords, 3669 mCurrentCookedPointerData.idToIndex, 3670 mCurrentCookedPointerData.touchingIdBits); 3671 } 3672 3673 dispatchHoverExit(when, policyFlags); 3674 dispatchTouches(when, policyFlags); 3675 dispatchHoverEnterAndMove(when, policyFlags); 3676 } 3677 3678 // Synthesize key up from raw buttons if needed. 3679 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, 3680 policyFlags, mLastButtonState, mCurrentButtonState); 3681 } 3682 3683 // Copy current touch to last touch in preparation for the next cycle. 3684 mLastRawPointerData.copyFrom(mCurrentRawPointerData); 3685 mLastCookedPointerData.copyFrom(mCurrentCookedPointerData); 3686 mLastButtonState = mCurrentButtonState; 3687 mLastFingerIdBits = mCurrentFingerIdBits; 3688 mLastStylusIdBits = mCurrentStylusIdBits; 3689 mLastMouseIdBits = mCurrentMouseIdBits; 3690 3691 // Clear some transient state. 3692 mCurrentRawVScroll = 0; 3693 mCurrentRawHScroll = 0; 3694} 3695 3696void TouchInputMapper::timeoutExpired(nsecs_t when) { 3697 if (mDeviceMode == DEVICE_MODE_POINTER) { 3698 if (mPointerUsage == POINTER_USAGE_GESTURES) { 3699 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/); 3700 } 3701 } 3702} 3703 3704bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) { 3705 // Check for release of a virtual key. 3706 if (mCurrentVirtualKey.down) { 3707 if (mCurrentRawPointerData.touchingIdBits.isEmpty()) { 3708 // Pointer went up while virtual key was down. 3709 mCurrentVirtualKey.down = false; 3710 if (!mCurrentVirtualKey.ignored) { 3711#if DEBUG_VIRTUAL_KEYS 3712 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d", 3713 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); 3714#endif 3715 dispatchVirtualKey(when, policyFlags, 3716 AKEY_EVENT_ACTION_UP, 3717 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY); 3718 } 3719 return true; 3720 } 3721 3722 if (mCurrentRawPointerData.touchingIdBits.count() == 1) { 3723 uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit(); 3724 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); 3725 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y); 3726 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) { 3727 // Pointer is still within the space of the virtual key. 3728 return true; 3729 } 3730 } 3731 3732 // Pointer left virtual key area or another pointer also went down. 3733 // Send key cancellation but do not consume the touch yet. 3734 // This is useful when the user swipes through from the virtual key area 3735 // into the main display surface. 3736 mCurrentVirtualKey.down = false; 3737 if (!mCurrentVirtualKey.ignored) { 3738#if DEBUG_VIRTUAL_KEYS 3739 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", 3740 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); 3741#endif 3742 dispatchVirtualKey(when, policyFlags, 3743 AKEY_EVENT_ACTION_UP, 3744 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY 3745 | AKEY_EVENT_FLAG_CANCELED); 3746 } 3747 } 3748 3749 if (mLastRawPointerData.touchingIdBits.isEmpty() 3750 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) { 3751 // Pointer just went down. Check for virtual key press or off-screen touches. 3752 uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit(); 3753 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); 3754 if (!isPointInsideSurface(pointer.x, pointer.y)) { 3755 // If exactly one pointer went down, check for virtual key hit. 3756 // Otherwise we will drop the entire stroke. 3757 if (mCurrentRawPointerData.touchingIdBits.count() == 1) { 3758 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y); 3759 if (virtualKey) { 3760 mCurrentVirtualKey.down = true; 3761 mCurrentVirtualKey.downTime = when; 3762 mCurrentVirtualKey.keyCode = virtualKey->keyCode; 3763 mCurrentVirtualKey.scanCode = virtualKey->scanCode; 3764 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey( 3765 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode); 3766 3767 if (!mCurrentVirtualKey.ignored) { 3768#if DEBUG_VIRTUAL_KEYS 3769 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d", 3770 mCurrentVirtualKey.keyCode, 3771 mCurrentVirtualKey.scanCode); 3772#endif 3773 dispatchVirtualKey(when, policyFlags, 3774 AKEY_EVENT_ACTION_DOWN, 3775 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY); 3776 } 3777 } 3778 } 3779 return true; 3780 } 3781 } 3782 3783 // Disable all virtual key touches that happen within a short time interval of the 3784 // most recent touch within the screen area. The idea is to filter out stray 3785 // virtual key presses when interacting with the touch screen. 3786 // 3787 // Problems we're trying to solve: 3788 // 3789 // 1. While scrolling a list or dragging the window shade, the user swipes down into a 3790 // virtual key area that is implemented by a separate touch panel and accidentally 3791 // triggers a virtual key. 3792 // 3793 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen 3794 // area and accidentally triggers a virtual key. This often happens when virtual keys 3795 // are layed out below the screen near to where the on screen keyboard's space bar 3796 // is displayed. 3797 if (mConfig.virtualKeyQuietTime > 0 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) { 3798 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime); 3799 } 3800 return false; 3801} 3802 3803void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags, 3804 int32_t keyEventAction, int32_t keyEventFlags) { 3805 int32_t keyCode = mCurrentVirtualKey.keyCode; 3806 int32_t scanCode = mCurrentVirtualKey.scanCode; 3807 nsecs_t downTime = mCurrentVirtualKey.downTime; 3808 int32_t metaState = mContext->getGlobalMetaState(); 3809 policyFlags |= POLICY_FLAG_VIRTUAL; 3810 3811 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags, 3812 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); 3813 getListener()->notifyKey(&args); 3814} 3815 3816void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) { 3817 BitSet32 currentIdBits = mCurrentCookedPointerData.touchingIdBits; 3818 BitSet32 lastIdBits = mLastCookedPointerData.touchingIdBits; 3819 int32_t metaState = getContext()->getGlobalMetaState(); 3820 int32_t buttonState = mCurrentButtonState; 3821 3822 if (currentIdBits == lastIdBits) { 3823 if (!currentIdBits.isEmpty()) { 3824 // No pointer id changes so this is a move event. 3825 // The listener takes care of batching moves so we don't have to deal with that here. 3826 dispatchMotion(when, policyFlags, mSource, 3827 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 3828 AMOTION_EVENT_EDGE_FLAG_NONE, 3829 mCurrentCookedPointerData.pointerProperties, 3830 mCurrentCookedPointerData.pointerCoords, 3831 mCurrentCookedPointerData.idToIndex, 3832 currentIdBits, -1, 3833 mOrientedXPrecision, mOrientedYPrecision, mDownTime); 3834 } 3835 } else { 3836 // There may be pointers going up and pointers going down and pointers moving 3837 // all at the same time. 3838 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value); 3839 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value); 3840 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value); 3841 BitSet32 dispatchedIdBits(lastIdBits.value); 3842 3843 // Update last coordinates of pointers that have moved so that we observe the new 3844 // pointer positions at the same time as other pointers that have just gone up. 3845 bool moveNeeded = updateMovedPointers( 3846 mCurrentCookedPointerData.pointerProperties, 3847 mCurrentCookedPointerData.pointerCoords, 3848 mCurrentCookedPointerData.idToIndex, 3849 mLastCookedPointerData.pointerProperties, 3850 mLastCookedPointerData.pointerCoords, 3851 mLastCookedPointerData.idToIndex, 3852 moveIdBits); 3853 if (buttonState != mLastButtonState) { 3854 moveNeeded = true; 3855 } 3856 3857 // Dispatch pointer up events. 3858 while (!upIdBits.isEmpty()) { 3859 uint32_t upId = upIdBits.clearFirstMarkedBit(); 3860 3861 dispatchMotion(when, policyFlags, mSource, 3862 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0, 3863 mLastCookedPointerData.pointerProperties, 3864 mLastCookedPointerData.pointerCoords, 3865 mLastCookedPointerData.idToIndex, 3866 dispatchedIdBits, upId, 3867 mOrientedXPrecision, mOrientedYPrecision, mDownTime); 3868 dispatchedIdBits.clearBit(upId); 3869 } 3870 3871 // Dispatch move events if any of the remaining pointers moved from their old locations. 3872 // Although applications receive new locations as part of individual pointer up 3873 // events, they do not generally handle them except when presented in a move event. 3874 if (moveNeeded) { 3875 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value); 3876 dispatchMotion(when, policyFlags, mSource, 3877 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0, 3878 mCurrentCookedPointerData.pointerProperties, 3879 mCurrentCookedPointerData.pointerCoords, 3880 mCurrentCookedPointerData.idToIndex, 3881 dispatchedIdBits, -1, 3882 mOrientedXPrecision, mOrientedYPrecision, mDownTime); 3883 } 3884 3885 // Dispatch pointer down events using the new pointer locations. 3886 while (!downIdBits.isEmpty()) { 3887 uint32_t downId = downIdBits.clearFirstMarkedBit(); 3888 dispatchedIdBits.markBit(downId); 3889 3890 if (dispatchedIdBits.count() == 1) { 3891 // First pointer is going down. Set down time. 3892 mDownTime = when; 3893 } 3894 3895 dispatchMotion(when, policyFlags, mSource, 3896 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0, 3897 mCurrentCookedPointerData.pointerProperties, 3898 mCurrentCookedPointerData.pointerCoords, 3899 mCurrentCookedPointerData.idToIndex, 3900 dispatchedIdBits, downId, 3901 mOrientedXPrecision, mOrientedYPrecision, mDownTime); 3902 } 3903 } 3904} 3905 3906void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) { 3907 if (mSentHoverEnter && 3908 (mCurrentCookedPointerData.hoveringIdBits.isEmpty() 3909 || !mCurrentCookedPointerData.touchingIdBits.isEmpty())) { 3910 int32_t metaState = getContext()->getGlobalMetaState(); 3911 dispatchMotion(when, policyFlags, mSource, 3912 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0, 3913 mLastCookedPointerData.pointerProperties, 3914 mLastCookedPointerData.pointerCoords, 3915 mLastCookedPointerData.idToIndex, 3916 mLastCookedPointerData.hoveringIdBits, -1, 3917 mOrientedXPrecision, mOrientedYPrecision, mDownTime); 3918 mSentHoverEnter = false; 3919 } 3920} 3921 3922void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) { 3923 if (mCurrentCookedPointerData.touchingIdBits.isEmpty() 3924 && !mCurrentCookedPointerData.hoveringIdBits.isEmpty()) { 3925 int32_t metaState = getContext()->getGlobalMetaState(); 3926 if (!mSentHoverEnter) { 3927 dispatchMotion(when, policyFlags, mSource, 3928 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0, 3929 mCurrentCookedPointerData.pointerProperties, 3930 mCurrentCookedPointerData.pointerCoords, 3931 mCurrentCookedPointerData.idToIndex, 3932 mCurrentCookedPointerData.hoveringIdBits, -1, 3933 mOrientedXPrecision, mOrientedYPrecision, mDownTime); 3934 mSentHoverEnter = true; 3935 } 3936 3937 dispatchMotion(when, policyFlags, mSource, 3938 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0, 3939 mCurrentCookedPointerData.pointerProperties, 3940 mCurrentCookedPointerData.pointerCoords, 3941 mCurrentCookedPointerData.idToIndex, 3942 mCurrentCookedPointerData.hoveringIdBits, -1, 3943 mOrientedXPrecision, mOrientedYPrecision, mDownTime); 3944 } 3945} 3946 3947void TouchInputMapper::cookPointerData() { 3948 uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount; 3949 3950 mCurrentCookedPointerData.clear(); 3951 mCurrentCookedPointerData.pointerCount = currentPointerCount; 3952 mCurrentCookedPointerData.hoveringIdBits = mCurrentRawPointerData.hoveringIdBits; 3953 mCurrentCookedPointerData.touchingIdBits = mCurrentRawPointerData.touchingIdBits; 3954 3955 // Walk through the the active pointers and map device coordinates onto 3956 // surface coordinates and adjust for display orientation. 3957 for (uint32_t i = 0; i < currentPointerCount; i++) { 3958 const RawPointerData::Pointer& in = mCurrentRawPointerData.pointers[i]; 3959 3960 // Size 3961 float touchMajor, touchMinor, toolMajor, toolMinor, size; 3962 switch (mCalibration.sizeCalibration) { 3963 case Calibration::SIZE_CALIBRATION_GEOMETRIC: 3964 case Calibration::SIZE_CALIBRATION_DIAMETER: 3965 case Calibration::SIZE_CALIBRATION_AREA: 3966 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) { 3967 touchMajor = in.touchMajor; 3968 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor; 3969 toolMajor = in.toolMajor; 3970 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor; 3971 size = mRawPointerAxes.touchMinor.valid 3972 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor; 3973 } else if (mRawPointerAxes.touchMajor.valid) { 3974 toolMajor = touchMajor = in.touchMajor; 3975 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid 3976 ? in.touchMinor : in.touchMajor; 3977 size = mRawPointerAxes.touchMinor.valid 3978 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor; 3979 } else if (mRawPointerAxes.toolMajor.valid) { 3980 touchMajor = toolMajor = in.toolMajor; 3981 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid 3982 ? in.toolMinor : in.toolMajor; 3983 size = mRawPointerAxes.toolMinor.valid 3984 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor; 3985 } else { 3986 ALOG_ASSERT(false, "No touch or tool axes. " 3987 "Size calibration should have been resolved to NONE."); 3988 touchMajor = 0; 3989 touchMinor = 0; 3990 toolMajor = 0; 3991 toolMinor = 0; 3992 size = 0; 3993 } 3994 3995 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) { 3996 uint32_t touchingCount = mCurrentRawPointerData.touchingIdBits.count(); 3997 if (touchingCount > 1) { 3998 touchMajor /= touchingCount; 3999 touchMinor /= touchingCount; 4000 toolMajor /= touchingCount; 4001 toolMinor /= touchingCount; 4002 size /= touchingCount; 4003 } 4004 } 4005 4006 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) { 4007 touchMajor *= mGeometricScale; 4008 touchMinor *= mGeometricScale; 4009 toolMajor *= mGeometricScale; 4010 toolMinor *= mGeometricScale; 4011 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) { 4012 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0; 4013 touchMinor = touchMajor; 4014 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0; 4015 toolMinor = toolMajor; 4016 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) { 4017 touchMinor = touchMajor; 4018 toolMinor = toolMajor; 4019 } 4020 4021 mCalibration.applySizeScaleAndBias(&touchMajor); 4022 mCalibration.applySizeScaleAndBias(&touchMinor); 4023 mCalibration.applySizeScaleAndBias(&toolMajor); 4024 mCalibration.applySizeScaleAndBias(&toolMinor); 4025 size *= mSizeScale; 4026 break; 4027 default: 4028 touchMajor = 0; 4029 touchMinor = 0; 4030 toolMajor = 0; 4031 toolMinor = 0; 4032 size = 0; 4033 break; 4034 } 4035 4036 // Pressure 4037 float pressure; 4038 switch (mCalibration.pressureCalibration) { 4039 case Calibration::PRESSURE_CALIBRATION_PHYSICAL: 4040 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: 4041 pressure = in.pressure * mPressureScale; 4042 break; 4043 default: 4044 pressure = in.isHovering ? 0 : 1; 4045 break; 4046 } 4047 4048 // Tilt and Orientation 4049 float tilt; 4050 float orientation; 4051 if (mHaveTilt) { 4052 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale; 4053 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale; 4054 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)); 4055 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle)); 4056 } else { 4057 tilt = 0; 4058 4059 switch (mCalibration.orientationCalibration) { 4060 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: 4061 orientation = (in.orientation - mOrientationCenter) * mOrientationScale; 4062 break; 4063 case Calibration::ORIENTATION_CALIBRATION_VECTOR: { 4064 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4); 4065 int32_t c2 = signExtendNybble(in.orientation & 0x0f); 4066 if (c1 != 0 || c2 != 0) { 4067 orientation = atan2f(c1, c2) * 0.5f; 4068 float confidence = hypotf(c1, c2); 4069 float scale = 1.0f + confidence / 16.0f; 4070 touchMajor *= scale; 4071 touchMinor /= scale; 4072 toolMajor *= scale; 4073 toolMinor /= scale; 4074 } else { 4075 orientation = 0; 4076 } 4077 break; 4078 } 4079 default: 4080 orientation = 0; 4081 } 4082 } 4083 4084 // Distance 4085 float distance; 4086 switch (mCalibration.distanceCalibration) { 4087 case Calibration::DISTANCE_CALIBRATION_SCALED: 4088 distance = in.distance * mDistanceScale; 4089 break; 4090 default: 4091 distance = 0; 4092 } 4093 4094 // X and Y 4095 // Adjust coords for surface orientation. 4096 float x, y; 4097 switch (mSurfaceOrientation) { 4098 case DISPLAY_ORIENTATION_90: 4099 x = float(in.y - mRawPointerAxes.y.minValue) * mYScale; 4100 y = float(mRawPointerAxes.x.maxValue - in.x) * mXScale; 4101 orientation -= M_PI_2; 4102 if (orientation < - M_PI_2) { 4103 orientation += M_PI; 4104 } 4105 break; 4106 case DISPLAY_ORIENTATION_180: 4107 x = float(mRawPointerAxes.x.maxValue - in.x) * mXScale; 4108 y = float(mRawPointerAxes.y.maxValue - in.y) * mYScale; 4109 break; 4110 case DISPLAY_ORIENTATION_270: 4111 x = float(mRawPointerAxes.y.maxValue - in.y) * mYScale; 4112 y = float(in.x - mRawPointerAxes.x.minValue) * mXScale; 4113 orientation += M_PI_2; 4114 if (orientation > M_PI_2) { 4115 orientation -= M_PI; 4116 } 4117 break; 4118 default: 4119 x = float(in.x - mRawPointerAxes.x.minValue) * mXScale; 4120 y = float(in.y - mRawPointerAxes.y.minValue) * mYScale; 4121 break; 4122 } 4123 4124 // Write output coords. 4125 PointerCoords& out = mCurrentCookedPointerData.pointerCoords[i]; 4126 out.clear(); 4127 out.setAxisValue(AMOTION_EVENT_AXIS_X, x); 4128 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 4129 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure); 4130 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size); 4131 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor); 4132 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor); 4133 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor); 4134 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor); 4135 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation); 4136 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt); 4137 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance); 4138 4139 // Write output properties. 4140 PointerProperties& properties = mCurrentCookedPointerData.pointerProperties[i]; 4141 uint32_t id = in.id; 4142 properties.clear(); 4143 properties.id = id; 4144 properties.toolType = in.toolType; 4145 4146 // Write id index. 4147 mCurrentCookedPointerData.idToIndex[id] = i; 4148 } 4149} 4150 4151void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, 4152 PointerUsage pointerUsage) { 4153 if (pointerUsage != mPointerUsage) { 4154 abortPointerUsage(when, policyFlags); 4155 mPointerUsage = pointerUsage; 4156 } 4157 4158 switch (mPointerUsage) { 4159 case POINTER_USAGE_GESTURES: 4160 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/); 4161 break; 4162 case POINTER_USAGE_STYLUS: 4163 dispatchPointerStylus(when, policyFlags); 4164 break; 4165 case POINTER_USAGE_MOUSE: 4166 dispatchPointerMouse(when, policyFlags); 4167 break; 4168 default: 4169 break; 4170 } 4171} 4172 4173void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) { 4174 switch (mPointerUsage) { 4175 case POINTER_USAGE_GESTURES: 4176 abortPointerGestures(when, policyFlags); 4177 break; 4178 case POINTER_USAGE_STYLUS: 4179 abortPointerStylus(when, policyFlags); 4180 break; 4181 case POINTER_USAGE_MOUSE: 4182 abortPointerMouse(when, policyFlags); 4183 break; 4184 default: 4185 break; 4186 } 4187 4188 mPointerUsage = POINTER_USAGE_NONE; 4189} 4190 4191void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, 4192 bool isTimeout) { 4193 // Update current gesture coordinates. 4194 bool cancelPreviousGesture, finishPreviousGesture; 4195 bool sendEvents = preparePointerGestures(when, 4196 &cancelPreviousGesture, &finishPreviousGesture, isTimeout); 4197 if (!sendEvents) { 4198 return; 4199 } 4200 if (finishPreviousGesture) { 4201 cancelPreviousGesture = false; 4202 } 4203 4204 // Update the pointer presentation and spots. 4205 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) { 4206 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT); 4207 if (finishPreviousGesture || cancelPreviousGesture) { 4208 mPointerController->clearSpots(); 4209 } 4210 mPointerController->setSpots(mPointerGesture.currentGestureCoords, 4211 mPointerGesture.currentGestureIdToIndex, 4212 mPointerGesture.currentGestureIdBits); 4213 } else { 4214 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); 4215 } 4216 4217 // Show or hide the pointer if needed. 4218 switch (mPointerGesture.currentGestureMode) { 4219 case PointerGesture::NEUTRAL: 4220 case PointerGesture::QUIET: 4221 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS 4222 && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE 4223 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) { 4224 // Remind the user of where the pointer is after finishing a gesture with spots. 4225 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL); 4226 } 4227 break; 4228 case PointerGesture::TAP: 4229 case PointerGesture::TAP_DRAG: 4230 case PointerGesture::BUTTON_CLICK_OR_DRAG: 4231 case PointerGesture::HOVER: 4232 case PointerGesture::PRESS: 4233 // Unfade the pointer when the current gesture manipulates the 4234 // area directly under the pointer. 4235 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); 4236 break; 4237 case PointerGesture::SWIPE: 4238 case PointerGesture::FREEFORM: 4239 // Fade the pointer when the current gesture manipulates a different 4240 // area and there are spots to guide the user experience. 4241 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) { 4242 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); 4243 } else { 4244 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); 4245 } 4246 break; 4247 } 4248 4249 // Send events! 4250 int32_t metaState = getContext()->getGlobalMetaState(); 4251 int32_t buttonState = mCurrentButtonState; 4252 4253 // Update last coordinates of pointers that have moved so that we observe the new 4254 // pointer positions at the same time as other pointers that have just gone up. 4255 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP 4256 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG 4257 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG 4258 || mPointerGesture.currentGestureMode == PointerGesture::PRESS 4259 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE 4260 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM; 4261 bool moveNeeded = false; 4262 if (down && !cancelPreviousGesture && !finishPreviousGesture 4263 && !mPointerGesture.lastGestureIdBits.isEmpty() 4264 && !mPointerGesture.currentGestureIdBits.isEmpty()) { 4265 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value 4266 & mPointerGesture.lastGestureIdBits.value); 4267 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties, 4268 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 4269 mPointerGesture.lastGestureProperties, 4270 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, 4271 movedGestureIdBits); 4272 if (buttonState != mLastButtonState) { 4273 moveNeeded = true; 4274 } 4275 } 4276 4277 // Send motion events for all pointers that went up or were canceled. 4278 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits); 4279 if (!dispatchedGestureIdBits.isEmpty()) { 4280 if (cancelPreviousGesture) { 4281 dispatchMotion(when, policyFlags, mSource, 4282 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState, 4283 AMOTION_EVENT_EDGE_FLAG_NONE, 4284 mPointerGesture.lastGestureProperties, 4285 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, 4286 dispatchedGestureIdBits, -1, 4287 0, 0, mPointerGesture.downTime); 4288 4289 dispatchedGestureIdBits.clear(); 4290 } else { 4291 BitSet32 upGestureIdBits; 4292 if (finishPreviousGesture) { 4293 upGestureIdBits = dispatchedGestureIdBits; 4294 } else { 4295 upGestureIdBits.value = dispatchedGestureIdBits.value 4296 & ~mPointerGesture.currentGestureIdBits.value; 4297 } 4298 while (!upGestureIdBits.isEmpty()) { 4299 uint32_t id = upGestureIdBits.clearFirstMarkedBit(); 4300 4301 dispatchMotion(when, policyFlags, mSource, 4302 AMOTION_EVENT_ACTION_POINTER_UP, 0, 4303 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, 4304 mPointerGesture.lastGestureProperties, 4305 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, 4306 dispatchedGestureIdBits, id, 4307 0, 0, mPointerGesture.downTime); 4308 4309 dispatchedGestureIdBits.clearBit(id); 4310 } 4311 } 4312 } 4313 4314 // Send motion events for all pointers that moved. 4315 if (moveNeeded) { 4316 dispatchMotion(when, policyFlags, mSource, 4317 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, 4318 mPointerGesture.currentGestureProperties, 4319 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 4320 dispatchedGestureIdBits, -1, 4321 0, 0, mPointerGesture.downTime); 4322 } 4323 4324 // Send motion events for all pointers that went down. 4325 if (down) { 4326 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value 4327 & ~dispatchedGestureIdBits.value); 4328 while (!downGestureIdBits.isEmpty()) { 4329 uint32_t id = downGestureIdBits.clearFirstMarkedBit(); 4330 dispatchedGestureIdBits.markBit(id); 4331 4332 if (dispatchedGestureIdBits.count() == 1) { 4333 mPointerGesture.downTime = when; 4334 } 4335 4336 dispatchMotion(when, policyFlags, mSource, 4337 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0, 4338 mPointerGesture.currentGestureProperties, 4339 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 4340 dispatchedGestureIdBits, id, 4341 0, 0, mPointerGesture.downTime); 4342 } 4343 } 4344 4345 // Send motion events for hover. 4346 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) { 4347 dispatchMotion(when, policyFlags, mSource, 4348 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 4349 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, 4350 mPointerGesture.currentGestureProperties, 4351 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 4352 mPointerGesture.currentGestureIdBits, -1, 4353 0, 0, mPointerGesture.downTime); 4354 } else if (dispatchedGestureIdBits.isEmpty() 4355 && !mPointerGesture.lastGestureIdBits.isEmpty()) { 4356 // Synthesize a hover move event after all pointers go up to indicate that 4357 // the pointer is hovering again even if the user is not currently touching 4358 // the touch pad. This ensures that a view will receive a fresh hover enter 4359 // event after a tap. 4360 float x, y; 4361 mPointerController->getPosition(&x, &y); 4362 4363 PointerProperties pointerProperties; 4364 pointerProperties.clear(); 4365 pointerProperties.id = 0; 4366 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; 4367 4368 PointerCoords pointerCoords; 4369 pointerCoords.clear(); 4370 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); 4371 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 4372 4373 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 4374 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 4375 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, 4376 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime); 4377 getListener()->notifyMotion(&args); 4378 } 4379 4380 // Update state. 4381 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode; 4382 if (!down) { 4383 mPointerGesture.lastGestureIdBits.clear(); 4384 } else { 4385 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits; 4386 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) { 4387 uint32_t id = idBits.clearFirstMarkedBit(); 4388 uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; 4389 mPointerGesture.lastGestureProperties[index].copyFrom( 4390 mPointerGesture.currentGestureProperties[index]); 4391 mPointerGesture.lastGestureCoords[index].copyFrom( 4392 mPointerGesture.currentGestureCoords[index]); 4393 mPointerGesture.lastGestureIdToIndex[id] = index; 4394 } 4395 } 4396} 4397 4398void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) { 4399 // Cancel previously dispatches pointers. 4400 if (!mPointerGesture.lastGestureIdBits.isEmpty()) { 4401 int32_t metaState = getContext()->getGlobalMetaState(); 4402 int32_t buttonState = mCurrentButtonState; 4403 dispatchMotion(when, policyFlags, mSource, 4404 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState, 4405 AMOTION_EVENT_EDGE_FLAG_NONE, 4406 mPointerGesture.lastGestureProperties, 4407 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, 4408 mPointerGesture.lastGestureIdBits, -1, 4409 0, 0, mPointerGesture.downTime); 4410 } 4411 4412 // Reset the current pointer gesture. 4413 mPointerGesture.reset(); 4414 mPointerVelocityControl.reset(); 4415 4416 // Remove any current spots. 4417 if (mPointerController != NULL) { 4418 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); 4419 mPointerController->clearSpots(); 4420 } 4421} 4422 4423bool TouchInputMapper::preparePointerGestures(nsecs_t when, 4424 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) { 4425 *outCancelPreviousGesture = false; 4426 *outFinishPreviousGesture = false; 4427 4428 // Handle TAP timeout. 4429 if (isTimeout) { 4430#if DEBUG_GESTURES 4431 ALOGD("Gestures: Processing timeout"); 4432#endif 4433 4434 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) { 4435 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) { 4436 // The tap/drag timeout has not yet expired. 4437 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime 4438 + mConfig.pointerGestureTapDragInterval); 4439 } else { 4440 // The tap is finished. 4441#if DEBUG_GESTURES 4442 ALOGD("Gestures: TAP finished"); 4443#endif 4444 *outFinishPreviousGesture = true; 4445 4446 mPointerGesture.activeGestureId = -1; 4447 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL; 4448 mPointerGesture.currentGestureIdBits.clear(); 4449 4450 mPointerVelocityControl.reset(); 4451 return true; 4452 } 4453 } 4454 4455 // We did not handle this timeout. 4456 return false; 4457 } 4458 4459 const uint32_t currentFingerCount = mCurrentFingerIdBits.count(); 4460 const uint32_t lastFingerCount = mLastFingerIdBits.count(); 4461 4462 // Update the velocity tracker. 4463 { 4464 VelocityTracker::Position positions[MAX_POINTERS]; 4465 uint32_t count = 0; 4466 for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); count++) { 4467 uint32_t id = idBits.clearFirstMarkedBit(); 4468 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id); 4469 positions[count].x = pointer.x * mPointerXMovementScale; 4470 positions[count].y = pointer.y * mPointerYMovementScale; 4471 } 4472 mPointerGesture.velocityTracker.addMovement(when, 4473 mCurrentFingerIdBits, positions); 4474 } 4475 4476 // Pick a new active touch id if needed. 4477 // Choose an arbitrary pointer that just went down, if there is one. 4478 // Otherwise choose an arbitrary remaining pointer. 4479 // This guarantees we always have an active touch id when there is at least one pointer. 4480 // We keep the same active touch id for as long as possible. 4481 bool activeTouchChanged = false; 4482 int32_t lastActiveTouchId = mPointerGesture.activeTouchId; 4483 int32_t activeTouchId = lastActiveTouchId; 4484 if (activeTouchId < 0) { 4485 if (!mCurrentFingerIdBits.isEmpty()) { 4486 activeTouchChanged = true; 4487 activeTouchId = mPointerGesture.activeTouchId = 4488 mCurrentFingerIdBits.firstMarkedBit(); 4489 mPointerGesture.firstTouchTime = when; 4490 } 4491 } else if (!mCurrentFingerIdBits.hasBit(activeTouchId)) { 4492 activeTouchChanged = true; 4493 if (!mCurrentFingerIdBits.isEmpty()) { 4494 activeTouchId = mPointerGesture.activeTouchId = 4495 mCurrentFingerIdBits.firstMarkedBit(); 4496 } else { 4497 activeTouchId = mPointerGesture.activeTouchId = -1; 4498 } 4499 } 4500 4501 // Determine whether we are in quiet time. 4502 bool isQuietTime = false; 4503 if (activeTouchId < 0) { 4504 mPointerGesture.resetQuietTime(); 4505 } else { 4506 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval; 4507 if (!isQuietTime) { 4508 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS 4509 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE 4510 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) 4511 && currentFingerCount < 2) { 4512 // Enter quiet time when exiting swipe or freeform state. 4513 // This is to prevent accidentally entering the hover state and flinging the 4514 // pointer when finishing a swipe and there is still one pointer left onscreen. 4515 isQuietTime = true; 4516 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG 4517 && currentFingerCount >= 2 4518 && !isPointerDown(mCurrentButtonState)) { 4519 // Enter quiet time when releasing the button and there are still two or more 4520 // fingers down. This may indicate that one finger was used to press the button 4521 // but it has not gone up yet. 4522 isQuietTime = true; 4523 } 4524 if (isQuietTime) { 4525 mPointerGesture.quietTime = when; 4526 } 4527 } 4528 } 4529 4530 // Switch states based on button and pointer state. 4531 if (isQuietTime) { 4532 // Case 1: Quiet time. (QUIET) 4533#if DEBUG_GESTURES 4534 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime 4535 + mConfig.pointerGestureQuietInterval - when) * 0.000001f); 4536#endif 4537 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) { 4538 *outFinishPreviousGesture = true; 4539 } 4540 4541 mPointerGesture.activeGestureId = -1; 4542 mPointerGesture.currentGestureMode = PointerGesture::QUIET; 4543 mPointerGesture.currentGestureIdBits.clear(); 4544 4545 mPointerVelocityControl.reset(); 4546 } else if (isPointerDown(mCurrentButtonState)) { 4547 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG) 4548 // The pointer follows the active touch point. 4549 // Emit DOWN, MOVE, UP events at the pointer location. 4550 // 4551 // Only the active touch matters; other fingers are ignored. This policy helps 4552 // to handle the case where the user places a second finger on the touch pad 4553 // to apply the necessary force to depress an integrated button below the surface. 4554 // We don't want the second finger to be delivered to applications. 4555 // 4556 // For this to work well, we need to make sure to track the pointer that is really 4557 // active. If the user first puts one finger down to click then adds another 4558 // finger to drag then the active pointer should switch to the finger that is 4559 // being dragged. 4560#if DEBUG_GESTURES 4561 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, " 4562 "currentFingerCount=%d", activeTouchId, currentFingerCount); 4563#endif 4564 // Reset state when just starting. 4565 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) { 4566 *outFinishPreviousGesture = true; 4567 mPointerGesture.activeGestureId = 0; 4568 } 4569 4570 // Switch pointers if needed. 4571 // Find the fastest pointer and follow it. 4572 if (activeTouchId >= 0 && currentFingerCount > 1) { 4573 int32_t bestId = -1; 4574 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed; 4575 for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); ) { 4576 uint32_t id = idBits.clearFirstMarkedBit(); 4577 float vx, vy; 4578 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) { 4579 float speed = hypotf(vx, vy); 4580 if (speed > bestSpeed) { 4581 bestId = id; 4582 bestSpeed = speed; 4583 } 4584 } 4585 } 4586 if (bestId >= 0 && bestId != activeTouchId) { 4587 mPointerGesture.activeTouchId = activeTouchId = bestId; 4588 activeTouchChanged = true; 4589#if DEBUG_GESTURES 4590 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, " 4591 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed); 4592#endif 4593 } 4594 } 4595 4596 if (activeTouchId >= 0 && mLastFingerIdBits.hasBit(activeTouchId)) { 4597 const RawPointerData::Pointer& currentPointer = 4598 mCurrentRawPointerData.pointerForId(activeTouchId); 4599 const RawPointerData::Pointer& lastPointer = 4600 mLastRawPointerData.pointerForId(activeTouchId); 4601 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale; 4602 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale; 4603 4604 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); 4605 mPointerVelocityControl.move(when, &deltaX, &deltaY); 4606 4607 // Move the pointer using a relative motion. 4608 // When using spots, the click will occur at the position of the anchor 4609 // spot and all other spots will move there. 4610 mPointerController->move(deltaX, deltaY); 4611 } else { 4612 mPointerVelocityControl.reset(); 4613 } 4614 4615 float x, y; 4616 mPointerController->getPosition(&x, &y); 4617 4618 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG; 4619 mPointerGesture.currentGestureIdBits.clear(); 4620 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); 4621 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; 4622 mPointerGesture.currentGestureProperties[0].clear(); 4623 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; 4624 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; 4625 mPointerGesture.currentGestureCoords[0].clear(); 4626 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); 4627 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); 4628 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 4629 } else if (currentFingerCount == 0) { 4630 // Case 3. No fingers down and button is not pressed. (NEUTRAL) 4631 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) { 4632 *outFinishPreviousGesture = true; 4633 } 4634 4635 // Watch for taps coming out of HOVER or TAP_DRAG mode. 4636 // Checking for taps after TAP_DRAG allows us to detect double-taps. 4637 bool tapped = false; 4638 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER 4639 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) 4640 && lastFingerCount == 1) { 4641 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) { 4642 float x, y; 4643 mPointerController->getPosition(&x, &y); 4644 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop 4645 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) { 4646#if DEBUG_GESTURES 4647 ALOGD("Gestures: TAP"); 4648#endif 4649 4650 mPointerGesture.tapUpTime = when; 4651 getContext()->requestTimeoutAtTime(when 4652 + mConfig.pointerGestureTapDragInterval); 4653 4654 mPointerGesture.activeGestureId = 0; 4655 mPointerGesture.currentGestureMode = PointerGesture::TAP; 4656 mPointerGesture.currentGestureIdBits.clear(); 4657 mPointerGesture.currentGestureIdBits.markBit( 4658 mPointerGesture.activeGestureId); 4659 mPointerGesture.currentGestureIdToIndex[ 4660 mPointerGesture.activeGestureId] = 0; 4661 mPointerGesture.currentGestureProperties[0].clear(); 4662 mPointerGesture.currentGestureProperties[0].id = 4663 mPointerGesture.activeGestureId; 4664 mPointerGesture.currentGestureProperties[0].toolType = 4665 AMOTION_EVENT_TOOL_TYPE_FINGER; 4666 mPointerGesture.currentGestureCoords[0].clear(); 4667 mPointerGesture.currentGestureCoords[0].setAxisValue( 4668 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX); 4669 mPointerGesture.currentGestureCoords[0].setAxisValue( 4670 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY); 4671 mPointerGesture.currentGestureCoords[0].setAxisValue( 4672 AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 4673 4674 tapped = true; 4675 } else { 4676#if DEBUG_GESTURES 4677 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", 4678 x - mPointerGesture.tapX, 4679 y - mPointerGesture.tapY); 4680#endif 4681 } 4682 } else { 4683#if DEBUG_GESTURES 4684 ALOGD("Gestures: Not a TAP, %0.3fms since down", 4685 (when - mPointerGesture.tapDownTime) * 0.000001f); 4686#endif 4687 } 4688 } 4689 4690 mPointerVelocityControl.reset(); 4691 4692 if (!tapped) { 4693#if DEBUG_GESTURES 4694 ALOGD("Gestures: NEUTRAL"); 4695#endif 4696 mPointerGesture.activeGestureId = -1; 4697 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL; 4698 mPointerGesture.currentGestureIdBits.clear(); 4699 } 4700 } else if (currentFingerCount == 1) { 4701 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG) 4702 // The pointer follows the active touch point. 4703 // When in HOVER, emit HOVER_MOVE events at the pointer location. 4704 // When in TAP_DRAG, emit MOVE events at the pointer location. 4705 ALOG_ASSERT(activeTouchId >= 0); 4706 4707 mPointerGesture.currentGestureMode = PointerGesture::HOVER; 4708 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) { 4709 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) { 4710 float x, y; 4711 mPointerController->getPosition(&x, &y); 4712 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop 4713 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) { 4714 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG; 4715 } else { 4716#if DEBUG_GESTURES 4717 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f", 4718 x - mPointerGesture.tapX, 4719 y - mPointerGesture.tapY); 4720#endif 4721 } 4722 } else { 4723#if DEBUG_GESTURES 4724 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up", 4725 (when - mPointerGesture.tapUpTime) * 0.000001f); 4726#endif 4727 } 4728 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) { 4729 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG; 4730 } 4731 4732 if (mLastFingerIdBits.hasBit(activeTouchId)) { 4733 const RawPointerData::Pointer& currentPointer = 4734 mCurrentRawPointerData.pointerForId(activeTouchId); 4735 const RawPointerData::Pointer& lastPointer = 4736 mLastRawPointerData.pointerForId(activeTouchId); 4737 float deltaX = (currentPointer.x - lastPointer.x) 4738 * mPointerXMovementScale; 4739 float deltaY = (currentPointer.y - lastPointer.y) 4740 * mPointerYMovementScale; 4741 4742 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); 4743 mPointerVelocityControl.move(when, &deltaX, &deltaY); 4744 4745 // Move the pointer using a relative motion. 4746 // When using spots, the hover or drag will occur at the position of the anchor spot. 4747 mPointerController->move(deltaX, deltaY); 4748 } else { 4749 mPointerVelocityControl.reset(); 4750 } 4751 4752 bool down; 4753 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) { 4754#if DEBUG_GESTURES 4755 ALOGD("Gestures: TAP_DRAG"); 4756#endif 4757 down = true; 4758 } else { 4759#if DEBUG_GESTURES 4760 ALOGD("Gestures: HOVER"); 4761#endif 4762 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) { 4763 *outFinishPreviousGesture = true; 4764 } 4765 mPointerGesture.activeGestureId = 0; 4766 down = false; 4767 } 4768 4769 float x, y; 4770 mPointerController->getPosition(&x, &y); 4771 4772 mPointerGesture.currentGestureIdBits.clear(); 4773 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); 4774 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; 4775 mPointerGesture.currentGestureProperties[0].clear(); 4776 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; 4777 mPointerGesture.currentGestureProperties[0].toolType = 4778 AMOTION_EVENT_TOOL_TYPE_FINGER; 4779 mPointerGesture.currentGestureCoords[0].clear(); 4780 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); 4781 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); 4782 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 4783 down ? 1.0f : 0.0f); 4784 4785 if (lastFingerCount == 0 && currentFingerCount != 0) { 4786 mPointerGesture.resetTap(); 4787 mPointerGesture.tapDownTime = when; 4788 mPointerGesture.tapX = x; 4789 mPointerGesture.tapY = y; 4790 } 4791 } else { 4792 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM) 4793 // We need to provide feedback for each finger that goes down so we cannot wait 4794 // for the fingers to move before deciding what to do. 4795 // 4796 // The ambiguous case is deciding what to do when there are two fingers down but they 4797 // have not moved enough to determine whether they are part of a drag or part of a 4798 // freeform gesture, or just a press or long-press at the pointer location. 4799 // 4800 // When there are two fingers we start with the PRESS hypothesis and we generate a 4801 // down at the pointer location. 4802 // 4803 // When the two fingers move enough or when additional fingers are added, we make 4804 // a decision to transition into SWIPE or FREEFORM mode accordingly. 4805 ALOG_ASSERT(activeTouchId >= 0); 4806 4807 bool settled = when >= mPointerGesture.firstTouchTime 4808 + mConfig.pointerGestureMultitouchSettleInterval; 4809 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS 4810 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE 4811 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { 4812 *outFinishPreviousGesture = true; 4813 } else if (!settled && currentFingerCount > lastFingerCount) { 4814 // Additional pointers have gone down but not yet settled. 4815 // Reset the gesture. 4816#if DEBUG_GESTURES 4817 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, " 4818 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime 4819 + mConfig.pointerGestureMultitouchSettleInterval - when) 4820 * 0.000001f); 4821#endif 4822 *outCancelPreviousGesture = true; 4823 } else { 4824 // Continue previous gesture. 4825 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode; 4826 } 4827 4828 if (*outFinishPreviousGesture || *outCancelPreviousGesture) { 4829 mPointerGesture.currentGestureMode = PointerGesture::PRESS; 4830 mPointerGesture.activeGestureId = 0; 4831 mPointerGesture.referenceIdBits.clear(); 4832 mPointerVelocityControl.reset(); 4833 4834 // Use the centroid and pointer location as the reference points for the gesture. 4835#if DEBUG_GESTURES 4836 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, " 4837 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime 4838 + mConfig.pointerGestureMultitouchSettleInterval - when) 4839 * 0.000001f); 4840#endif 4841 mCurrentRawPointerData.getCentroidOfTouchingPointers( 4842 &mPointerGesture.referenceTouchX, 4843 &mPointerGesture.referenceTouchY); 4844 mPointerController->getPosition(&mPointerGesture.referenceGestureX, 4845 &mPointerGesture.referenceGestureY); 4846 } 4847 4848 // Clear the reference deltas for fingers not yet included in the reference calculation. 4849 for (BitSet32 idBits(mCurrentFingerIdBits.value 4850 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) { 4851 uint32_t id = idBits.clearFirstMarkedBit(); 4852 mPointerGesture.referenceDeltas[id].dx = 0; 4853 mPointerGesture.referenceDeltas[id].dy = 0; 4854 } 4855 mPointerGesture.referenceIdBits = mCurrentFingerIdBits; 4856 4857 // Add delta for all fingers and calculate a common movement delta. 4858 float commonDeltaX = 0, commonDeltaY = 0; 4859 BitSet32 commonIdBits(mLastFingerIdBits.value 4860 & mCurrentFingerIdBits.value); 4861 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) { 4862 bool first = (idBits == commonIdBits); 4863 uint32_t id = idBits.clearFirstMarkedBit(); 4864 const RawPointerData::Pointer& cpd = mCurrentRawPointerData.pointerForId(id); 4865 const RawPointerData::Pointer& lpd = mLastRawPointerData.pointerForId(id); 4866 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; 4867 delta.dx += cpd.x - lpd.x; 4868 delta.dy += cpd.y - lpd.y; 4869 4870 if (first) { 4871 commonDeltaX = delta.dx; 4872 commonDeltaY = delta.dy; 4873 } else { 4874 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx); 4875 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy); 4876 } 4877 } 4878 4879 // Consider transitions from PRESS to SWIPE or MULTITOUCH. 4880 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) { 4881 float dist[MAX_POINTER_ID + 1]; 4882 int32_t distOverThreshold = 0; 4883 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) { 4884 uint32_t id = idBits.clearFirstMarkedBit(); 4885 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; 4886 dist[id] = hypotf(delta.dx * mPointerXZoomScale, 4887 delta.dy * mPointerYZoomScale); 4888 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) { 4889 distOverThreshold += 1; 4890 } 4891 } 4892 4893 // Only transition when at least two pointers have moved further than 4894 // the minimum distance threshold. 4895 if (distOverThreshold >= 2) { 4896 if (currentFingerCount > 2) { 4897 // There are more than two pointers, switch to FREEFORM. 4898#if DEBUG_GESTURES 4899 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2", 4900 currentFingerCount); 4901#endif 4902 *outCancelPreviousGesture = true; 4903 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; 4904 } else { 4905 // There are exactly two pointers. 4906 BitSet32 idBits(mCurrentFingerIdBits); 4907 uint32_t id1 = idBits.clearFirstMarkedBit(); 4908 uint32_t id2 = idBits.firstMarkedBit(); 4909 const RawPointerData::Pointer& p1 = mCurrentRawPointerData.pointerForId(id1); 4910 const RawPointerData::Pointer& p2 = mCurrentRawPointerData.pointerForId(id2); 4911 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y); 4912 if (mutualDistance > mPointerGestureMaxSwipeWidth) { 4913 // There are two pointers but they are too far apart for a SWIPE, 4914 // switch to FREEFORM. 4915#if DEBUG_GESTURES 4916 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f", 4917 mutualDistance, mPointerGestureMaxSwipeWidth); 4918#endif 4919 *outCancelPreviousGesture = true; 4920 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; 4921 } else { 4922 // There are two pointers. Wait for both pointers to start moving 4923 // before deciding whether this is a SWIPE or FREEFORM gesture. 4924 float dist1 = dist[id1]; 4925 float dist2 = dist[id2]; 4926 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance 4927 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) { 4928 // Calculate the dot product of the displacement vectors. 4929 // When the vectors are oriented in approximately the same direction, 4930 // the angle betweeen them is near zero and the cosine of the angle 4931 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2). 4932 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1]; 4933 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2]; 4934 float dx1 = delta1.dx * mPointerXZoomScale; 4935 float dy1 = delta1.dy * mPointerYZoomScale; 4936 float dx2 = delta2.dx * mPointerXZoomScale; 4937 float dy2 = delta2.dy * mPointerYZoomScale; 4938 float dot = dx1 * dx2 + dy1 * dy2; 4939 float cosine = dot / (dist1 * dist2); // denominator always > 0 4940 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) { 4941 // Pointers are moving in the same direction. Switch to SWIPE. 4942#if DEBUG_GESTURES 4943 ALOGD("Gestures: PRESS transitioned to SWIPE, " 4944 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, " 4945 "cosine %0.3f >= %0.3f", 4946 dist1, mConfig.pointerGestureMultitouchMinDistance, 4947 dist2, mConfig.pointerGestureMultitouchMinDistance, 4948 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine); 4949#endif 4950 mPointerGesture.currentGestureMode = PointerGesture::SWIPE; 4951 } else { 4952 // Pointers are moving in different directions. Switch to FREEFORM. 4953#if DEBUG_GESTURES 4954 ALOGD("Gestures: PRESS transitioned to FREEFORM, " 4955 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, " 4956 "cosine %0.3f < %0.3f", 4957 dist1, mConfig.pointerGestureMultitouchMinDistance, 4958 dist2, mConfig.pointerGestureMultitouchMinDistance, 4959 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine); 4960#endif 4961 *outCancelPreviousGesture = true; 4962 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; 4963 } 4964 } 4965 } 4966 } 4967 } 4968 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { 4969 // Switch from SWIPE to FREEFORM if additional pointers go down. 4970 // Cancel previous gesture. 4971 if (currentFingerCount > 2) { 4972#if DEBUG_GESTURES 4973 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2", 4974 currentFingerCount); 4975#endif 4976 *outCancelPreviousGesture = true; 4977 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; 4978 } 4979 } 4980 4981 // Move the reference points based on the overall group motion of the fingers 4982 // except in PRESS mode while waiting for a transition to occur. 4983 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS 4984 && (commonDeltaX || commonDeltaY)) { 4985 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) { 4986 uint32_t id = idBits.clearFirstMarkedBit(); 4987 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; 4988 delta.dx = 0; 4989 delta.dy = 0; 4990 } 4991 4992 mPointerGesture.referenceTouchX += commonDeltaX; 4993 mPointerGesture.referenceTouchY += commonDeltaY; 4994 4995 commonDeltaX *= mPointerXMovementScale; 4996 commonDeltaY *= mPointerYMovementScale; 4997 4998 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY); 4999 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY); 5000 5001 mPointerGesture.referenceGestureX += commonDeltaX; 5002 mPointerGesture.referenceGestureY += commonDeltaY; 5003 } 5004 5005 // Report gestures. 5006 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS 5007 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { 5008 // PRESS or SWIPE mode. 5009#if DEBUG_GESTURES 5010 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d," 5011 "activeGestureId=%d, currentTouchPointerCount=%d", 5012 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount); 5013#endif 5014 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0); 5015 5016 mPointerGesture.currentGestureIdBits.clear(); 5017 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); 5018 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; 5019 mPointerGesture.currentGestureProperties[0].clear(); 5020 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; 5021 mPointerGesture.currentGestureProperties[0].toolType = 5022 AMOTION_EVENT_TOOL_TYPE_FINGER; 5023 mPointerGesture.currentGestureCoords[0].clear(); 5024 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 5025 mPointerGesture.referenceGestureX); 5026 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 5027 mPointerGesture.referenceGestureY); 5028 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 5029 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) { 5030 // FREEFORM mode. 5031#if DEBUG_GESTURES 5032 ALOGD("Gestures: FREEFORM activeTouchId=%d," 5033 "activeGestureId=%d, currentTouchPointerCount=%d", 5034 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount); 5035#endif 5036 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0); 5037 5038 mPointerGesture.currentGestureIdBits.clear(); 5039 5040 BitSet32 mappedTouchIdBits; 5041 BitSet32 usedGestureIdBits; 5042 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { 5043 // Initially, assign the active gesture id to the active touch point 5044 // if there is one. No other touch id bits are mapped yet. 5045 if (!*outCancelPreviousGesture) { 5046 mappedTouchIdBits.markBit(activeTouchId); 5047 usedGestureIdBits.markBit(mPointerGesture.activeGestureId); 5048 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] = 5049 mPointerGesture.activeGestureId; 5050 } else { 5051 mPointerGesture.activeGestureId = -1; 5052 } 5053 } else { 5054 // Otherwise, assume we mapped all touches from the previous frame. 5055 // Reuse all mappings that are still applicable. 5056 mappedTouchIdBits.value = mLastFingerIdBits.value 5057 & mCurrentFingerIdBits.value; 5058 usedGestureIdBits = mPointerGesture.lastGestureIdBits; 5059 5060 // Check whether we need to choose a new active gesture id because the 5061 // current went went up. 5062 for (BitSet32 upTouchIdBits(mLastFingerIdBits.value 5063 & ~mCurrentFingerIdBits.value); 5064 !upTouchIdBits.isEmpty(); ) { 5065 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit(); 5066 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId]; 5067 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) { 5068 mPointerGesture.activeGestureId = -1; 5069 break; 5070 } 5071 } 5072 } 5073 5074#if DEBUG_GESTURES 5075 ALOGD("Gestures: FREEFORM follow up " 5076 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, " 5077 "activeGestureId=%d", 5078 mappedTouchIdBits.value, usedGestureIdBits.value, 5079 mPointerGesture.activeGestureId); 5080#endif 5081 5082 BitSet32 idBits(mCurrentFingerIdBits); 5083 for (uint32_t i = 0; i < currentFingerCount; i++) { 5084 uint32_t touchId = idBits.clearFirstMarkedBit(); 5085 uint32_t gestureId; 5086 if (!mappedTouchIdBits.hasBit(touchId)) { 5087 gestureId = usedGestureIdBits.markFirstUnmarkedBit(); 5088 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId; 5089#if DEBUG_GESTURES 5090 ALOGD("Gestures: FREEFORM " 5091 "new mapping for touch id %d -> gesture id %d", 5092 touchId, gestureId); 5093#endif 5094 } else { 5095 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId]; 5096#if DEBUG_GESTURES 5097 ALOGD("Gestures: FREEFORM " 5098 "existing mapping for touch id %d -> gesture id %d", 5099 touchId, gestureId); 5100#endif 5101 } 5102 mPointerGesture.currentGestureIdBits.markBit(gestureId); 5103 mPointerGesture.currentGestureIdToIndex[gestureId] = i; 5104 5105 const RawPointerData::Pointer& pointer = 5106 mCurrentRawPointerData.pointerForId(touchId); 5107 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) 5108 * mPointerXZoomScale; 5109 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) 5110 * mPointerYZoomScale; 5111 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); 5112 5113 mPointerGesture.currentGestureProperties[i].clear(); 5114 mPointerGesture.currentGestureProperties[i].id = gestureId; 5115 mPointerGesture.currentGestureProperties[i].toolType = 5116 AMOTION_EVENT_TOOL_TYPE_FINGER; 5117 mPointerGesture.currentGestureCoords[i].clear(); 5118 mPointerGesture.currentGestureCoords[i].setAxisValue( 5119 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX); 5120 mPointerGesture.currentGestureCoords[i].setAxisValue( 5121 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY); 5122 mPointerGesture.currentGestureCoords[i].setAxisValue( 5123 AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 5124 } 5125 5126 if (mPointerGesture.activeGestureId < 0) { 5127 mPointerGesture.activeGestureId = 5128 mPointerGesture.currentGestureIdBits.firstMarkedBit(); 5129#if DEBUG_GESTURES 5130 ALOGD("Gestures: FREEFORM new " 5131 "activeGestureId=%d", mPointerGesture.activeGestureId); 5132#endif 5133 } 5134 } 5135 } 5136 5137 mPointerController->setButtonState(mCurrentButtonState); 5138 5139#if DEBUG_GESTURES 5140 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, " 5141 "currentGestureMode=%d, currentGestureIdBits=0x%08x, " 5142 "lastGestureMode=%d, lastGestureIdBits=0x%08x", 5143 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture), 5144 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value, 5145 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value); 5146 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) { 5147 uint32_t id = idBits.clearFirstMarkedBit(); 5148 uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; 5149 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index]; 5150 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index]; 5151 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, " 5152 "x=%0.3f, y=%0.3f, pressure=%0.3f", 5153 id, index, properties.toolType, 5154 coords.getAxisValue(AMOTION_EVENT_AXIS_X), 5155 coords.getAxisValue(AMOTION_EVENT_AXIS_Y), 5156 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); 5157 } 5158 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) { 5159 uint32_t id = idBits.clearFirstMarkedBit(); 5160 uint32_t index = mPointerGesture.lastGestureIdToIndex[id]; 5161 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index]; 5162 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index]; 5163 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, " 5164 "x=%0.3f, y=%0.3f, pressure=%0.3f", 5165 id, index, properties.toolType, 5166 coords.getAxisValue(AMOTION_EVENT_AXIS_X), 5167 coords.getAxisValue(AMOTION_EVENT_AXIS_Y), 5168 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); 5169 } 5170#endif 5171 return true; 5172} 5173 5174void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) { 5175 mPointerSimple.currentCoords.clear(); 5176 mPointerSimple.currentProperties.clear(); 5177 5178 bool down, hovering; 5179 if (!mCurrentStylusIdBits.isEmpty()) { 5180 uint32_t id = mCurrentStylusIdBits.firstMarkedBit(); 5181 uint32_t index = mCurrentCookedPointerData.idToIndex[id]; 5182 float x = mCurrentCookedPointerData.pointerCoords[index].getX(); 5183 float y = mCurrentCookedPointerData.pointerCoords[index].getY(); 5184 mPointerController->setPosition(x, y); 5185 5186 hovering = mCurrentCookedPointerData.hoveringIdBits.hasBit(id); 5187 down = !hovering; 5188 5189 mPointerController->getPosition(&x, &y); 5190 mPointerSimple.currentCoords.copyFrom(mCurrentCookedPointerData.pointerCoords[index]); 5191 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); 5192 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 5193 mPointerSimple.currentProperties.id = 0; 5194 mPointerSimple.currentProperties.toolType = 5195 mCurrentCookedPointerData.pointerProperties[index].toolType; 5196 } else { 5197 down = false; 5198 hovering = false; 5199 } 5200 5201 dispatchPointerSimple(when, policyFlags, down, hovering); 5202} 5203 5204void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) { 5205 abortPointerSimple(when, policyFlags); 5206} 5207 5208void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) { 5209 mPointerSimple.currentCoords.clear(); 5210 mPointerSimple.currentProperties.clear(); 5211 5212 bool down, hovering; 5213 if (!mCurrentMouseIdBits.isEmpty()) { 5214 uint32_t id = mCurrentMouseIdBits.firstMarkedBit(); 5215 uint32_t currentIndex = mCurrentRawPointerData.idToIndex[id]; 5216 if (mLastMouseIdBits.hasBit(id)) { 5217 uint32_t lastIndex = mCurrentRawPointerData.idToIndex[id]; 5218 float deltaX = (mCurrentRawPointerData.pointers[currentIndex].x 5219 - mLastRawPointerData.pointers[lastIndex].x) 5220 * mPointerXMovementScale; 5221 float deltaY = (mCurrentRawPointerData.pointers[currentIndex].y 5222 - mLastRawPointerData.pointers[lastIndex].y) 5223 * mPointerYMovementScale; 5224 5225 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); 5226 mPointerVelocityControl.move(when, &deltaX, &deltaY); 5227 5228 mPointerController->move(deltaX, deltaY); 5229 } else { 5230 mPointerVelocityControl.reset(); 5231 } 5232 5233 down = isPointerDown(mCurrentButtonState); 5234 hovering = !down; 5235 5236 float x, y; 5237 mPointerController->getPosition(&x, &y); 5238 mPointerSimple.currentCoords.copyFrom( 5239 mCurrentCookedPointerData.pointerCoords[currentIndex]); 5240 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); 5241 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 5242 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 5243 hovering ? 0.0f : 1.0f); 5244 mPointerSimple.currentProperties.id = 0; 5245 mPointerSimple.currentProperties.toolType = 5246 mCurrentCookedPointerData.pointerProperties[currentIndex].toolType; 5247 } else { 5248 mPointerVelocityControl.reset(); 5249 5250 down = false; 5251 hovering = false; 5252 } 5253 5254 dispatchPointerSimple(when, policyFlags, down, hovering); 5255} 5256 5257void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) { 5258 abortPointerSimple(when, policyFlags); 5259 5260 mPointerVelocityControl.reset(); 5261} 5262 5263void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, 5264 bool down, bool hovering) { 5265 int32_t metaState = getContext()->getGlobalMetaState(); 5266 5267 if (mPointerController != NULL) { 5268 if (down || hovering) { 5269 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); 5270 mPointerController->clearSpots(); 5271 mPointerController->setButtonState(mCurrentButtonState); 5272 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); 5273 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) { 5274 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); 5275 } 5276 } 5277 5278 if (mPointerSimple.down && !down) { 5279 mPointerSimple.down = false; 5280 5281 // Send up. 5282 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 5283 AMOTION_EVENT_ACTION_UP, 0, metaState, mLastButtonState, 0, 5284 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, 5285 mOrientedXPrecision, mOrientedYPrecision, 5286 mPointerSimple.downTime); 5287 getListener()->notifyMotion(&args); 5288 } 5289 5290 if (mPointerSimple.hovering && !hovering) { 5291 mPointerSimple.hovering = false; 5292 5293 // Send hover exit. 5294 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 5295 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0, 5296 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, 5297 mOrientedXPrecision, mOrientedYPrecision, 5298 mPointerSimple.downTime); 5299 getListener()->notifyMotion(&args); 5300 } 5301 5302 if (down) { 5303 if (!mPointerSimple.down) { 5304 mPointerSimple.down = true; 5305 mPointerSimple.downTime = when; 5306 5307 // Send down. 5308 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 5309 AMOTION_EVENT_ACTION_DOWN, 0, metaState, mCurrentButtonState, 0, 5310 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, 5311 mOrientedXPrecision, mOrientedYPrecision, 5312 mPointerSimple.downTime); 5313 getListener()->notifyMotion(&args); 5314 } 5315 5316 // Send move. 5317 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 5318 AMOTION_EVENT_ACTION_MOVE, 0, metaState, mCurrentButtonState, 0, 5319 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, 5320 mOrientedXPrecision, mOrientedYPrecision, 5321 mPointerSimple.downTime); 5322 getListener()->notifyMotion(&args); 5323 } 5324 5325 if (hovering) { 5326 if (!mPointerSimple.hovering) { 5327 mPointerSimple.hovering = true; 5328 5329 // Send hover enter. 5330 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 5331 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0, 5332 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, 5333 mOrientedXPrecision, mOrientedYPrecision, 5334 mPointerSimple.downTime); 5335 getListener()->notifyMotion(&args); 5336 } 5337 5338 // Send hover move. 5339 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 5340 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0, 5341 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, 5342 mOrientedXPrecision, mOrientedYPrecision, 5343 mPointerSimple.downTime); 5344 getListener()->notifyMotion(&args); 5345 } 5346 5347 if (mCurrentRawVScroll || mCurrentRawHScroll) { 5348 float vscroll = mCurrentRawVScroll; 5349 float hscroll = mCurrentRawHScroll; 5350 mWheelYVelocityControl.move(when, NULL, &vscroll); 5351 mWheelXVelocityControl.move(when, &hscroll, NULL); 5352 5353 // Send scroll. 5354 PointerCoords pointerCoords; 5355 pointerCoords.copyFrom(mPointerSimple.currentCoords); 5356 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); 5357 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); 5358 5359 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, 5360 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, mCurrentButtonState, 0, 5361 1, &mPointerSimple.currentProperties, &pointerCoords, 5362 mOrientedXPrecision, mOrientedYPrecision, 5363 mPointerSimple.downTime); 5364 getListener()->notifyMotion(&args); 5365 } 5366 5367 // Save state. 5368 if (down || hovering) { 5369 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords); 5370 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties); 5371 } else { 5372 mPointerSimple.reset(); 5373 } 5374} 5375 5376void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) { 5377 mPointerSimple.currentCoords.clear(); 5378 mPointerSimple.currentProperties.clear(); 5379 5380 dispatchPointerSimple(when, policyFlags, false, false); 5381} 5382 5383void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source, 5384 int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags, 5385 const PointerProperties* properties, const PointerCoords* coords, 5386 const uint32_t* idToIndex, BitSet32 idBits, 5387 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) { 5388 PointerCoords pointerCoords[MAX_POINTERS]; 5389 PointerProperties pointerProperties[MAX_POINTERS]; 5390 uint32_t pointerCount = 0; 5391 while (!idBits.isEmpty()) { 5392 uint32_t id = idBits.clearFirstMarkedBit(); 5393 uint32_t index = idToIndex[id]; 5394 pointerProperties[pointerCount].copyFrom(properties[index]); 5395 pointerCoords[pointerCount].copyFrom(coords[index]); 5396 5397 if (changedId >= 0 && id == uint32_t(changedId)) { 5398 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; 5399 } 5400 5401 pointerCount += 1; 5402 } 5403 5404 ALOG_ASSERT(pointerCount != 0); 5405 5406 if (changedId >= 0 && pointerCount == 1) { 5407 // Replace initial down and final up action. 5408 // We can compare the action without masking off the changed pointer index 5409 // because we know the index is 0. 5410 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) { 5411 action = AMOTION_EVENT_ACTION_DOWN; 5412 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) { 5413 action = AMOTION_EVENT_ACTION_UP; 5414 } else { 5415 // Can't happen. 5416 ALOG_ASSERT(false); 5417 } 5418 } 5419 5420 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags, 5421 action, flags, metaState, buttonState, edgeFlags, 5422 pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime); 5423 getListener()->notifyMotion(&args); 5424} 5425 5426bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties, 5427 const PointerCoords* inCoords, const uint32_t* inIdToIndex, 5428 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex, 5429 BitSet32 idBits) const { 5430 bool changed = false; 5431 while (!idBits.isEmpty()) { 5432 uint32_t id = idBits.clearFirstMarkedBit(); 5433 uint32_t inIndex = inIdToIndex[id]; 5434 uint32_t outIndex = outIdToIndex[id]; 5435 5436 const PointerProperties& curInProperties = inProperties[inIndex]; 5437 const PointerCoords& curInCoords = inCoords[inIndex]; 5438 PointerProperties& curOutProperties = outProperties[outIndex]; 5439 PointerCoords& curOutCoords = outCoords[outIndex]; 5440 5441 if (curInProperties != curOutProperties) { 5442 curOutProperties.copyFrom(curInProperties); 5443 changed = true; 5444 } 5445 5446 if (curInCoords != curOutCoords) { 5447 curOutCoords.copyFrom(curInCoords); 5448 changed = true; 5449 } 5450 } 5451 return changed; 5452} 5453 5454void TouchInputMapper::fadePointer() { 5455 if (mPointerController != NULL) { 5456 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); 5457 } 5458} 5459 5460bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) { 5461 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue 5462 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue; 5463} 5464 5465const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit( 5466 int32_t x, int32_t y) { 5467 size_t numVirtualKeys = mVirtualKeys.size(); 5468 for (size_t i = 0; i < numVirtualKeys; i++) { 5469 const VirtualKey& virtualKey = mVirtualKeys[i]; 5470 5471#if DEBUG_VIRTUAL_KEYS 5472 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, " 5473 "left=%d, top=%d, right=%d, bottom=%d", 5474 x, y, 5475 virtualKey.keyCode, virtualKey.scanCode, 5476 virtualKey.hitLeft, virtualKey.hitTop, 5477 virtualKey.hitRight, virtualKey.hitBottom); 5478#endif 5479 5480 if (virtualKey.isHit(x, y)) { 5481 return & virtualKey; 5482 } 5483 } 5484 5485 return NULL; 5486} 5487 5488void TouchInputMapper::assignPointerIds() { 5489 uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount; 5490 uint32_t lastPointerCount = mLastRawPointerData.pointerCount; 5491 5492 mCurrentRawPointerData.clearIdBits(); 5493 5494 if (currentPointerCount == 0) { 5495 // No pointers to assign. 5496 return; 5497 } 5498 5499 if (lastPointerCount == 0) { 5500 // All pointers are new. 5501 for (uint32_t i = 0; i < currentPointerCount; i++) { 5502 uint32_t id = i; 5503 mCurrentRawPointerData.pointers[i].id = id; 5504 mCurrentRawPointerData.idToIndex[id] = i; 5505 mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(i)); 5506 } 5507 return; 5508 } 5509 5510 if (currentPointerCount == 1 && lastPointerCount == 1 5511 && mCurrentRawPointerData.pointers[0].toolType 5512 == mLastRawPointerData.pointers[0].toolType) { 5513 // Only one pointer and no change in count so it must have the same id as before. 5514 uint32_t id = mLastRawPointerData.pointers[0].id; 5515 mCurrentRawPointerData.pointers[0].id = id; 5516 mCurrentRawPointerData.idToIndex[id] = 0; 5517 mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(0)); 5518 return; 5519 } 5520 5521 // General case. 5522 // We build a heap of squared euclidean distances between current and last pointers 5523 // associated with the current and last pointer indices. Then, we find the best 5524 // match (by distance) for each current pointer. 5525 // The pointers must have the same tool type but it is possible for them to 5526 // transition from hovering to touching or vice-versa while retaining the same id. 5527 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS]; 5528 5529 uint32_t heapSize = 0; 5530 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount; 5531 currentPointerIndex++) { 5532 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount; 5533 lastPointerIndex++) { 5534 const RawPointerData::Pointer& currentPointer = 5535 mCurrentRawPointerData.pointers[currentPointerIndex]; 5536 const RawPointerData::Pointer& lastPointer = 5537 mLastRawPointerData.pointers[lastPointerIndex]; 5538 if (currentPointer.toolType == lastPointer.toolType) { 5539 int64_t deltaX = currentPointer.x - lastPointer.x; 5540 int64_t deltaY = currentPointer.y - lastPointer.y; 5541 5542 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY); 5543 5544 // Insert new element into the heap (sift up). 5545 heap[heapSize].currentPointerIndex = currentPointerIndex; 5546 heap[heapSize].lastPointerIndex = lastPointerIndex; 5547 heap[heapSize].distance = distance; 5548 heapSize += 1; 5549 } 5550 } 5551 } 5552 5553 // Heapify 5554 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) { 5555 startIndex -= 1; 5556 for (uint32_t parentIndex = startIndex; ;) { 5557 uint32_t childIndex = parentIndex * 2 + 1; 5558 if (childIndex >= heapSize) { 5559 break; 5560 } 5561 5562 if (childIndex + 1 < heapSize 5563 && heap[childIndex + 1].distance < heap[childIndex].distance) { 5564 childIndex += 1; 5565 } 5566 5567 if (heap[parentIndex].distance <= heap[childIndex].distance) { 5568 break; 5569 } 5570 5571 swap(heap[parentIndex], heap[childIndex]); 5572 parentIndex = childIndex; 5573 } 5574 } 5575 5576#if DEBUG_POINTER_ASSIGNMENT 5577 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize); 5578 for (size_t i = 0; i < heapSize; i++) { 5579 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", 5580 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, 5581 heap[i].distance); 5582 } 5583#endif 5584 5585 // Pull matches out by increasing order of distance. 5586 // To avoid reassigning pointers that have already been matched, the loop keeps track 5587 // of which last and current pointers have been matched using the matchedXXXBits variables. 5588 // It also tracks the used pointer id bits. 5589 BitSet32 matchedLastBits(0); 5590 BitSet32 matchedCurrentBits(0); 5591 BitSet32 usedIdBits(0); 5592 bool first = true; 5593 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) { 5594 while (heapSize > 0) { 5595 if (first) { 5596 // The first time through the loop, we just consume the root element of 5597 // the heap (the one with smallest distance). 5598 first = false; 5599 } else { 5600 // Previous iterations consumed the root element of the heap. 5601 // Pop root element off of the heap (sift down). 5602 heap[0] = heap[heapSize]; 5603 for (uint32_t parentIndex = 0; ;) { 5604 uint32_t childIndex = parentIndex * 2 + 1; 5605 if (childIndex >= heapSize) { 5606 break; 5607 } 5608 5609 if (childIndex + 1 < heapSize 5610 && heap[childIndex + 1].distance < heap[childIndex].distance) { 5611 childIndex += 1; 5612 } 5613 5614 if (heap[parentIndex].distance <= heap[childIndex].distance) { 5615 break; 5616 } 5617 5618 swap(heap[parentIndex], heap[childIndex]); 5619 parentIndex = childIndex; 5620 } 5621 5622#if DEBUG_POINTER_ASSIGNMENT 5623 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize); 5624 for (size_t i = 0; i < heapSize; i++) { 5625 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", 5626 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, 5627 heap[i].distance); 5628 } 5629#endif 5630 } 5631 5632 heapSize -= 1; 5633 5634 uint32_t currentPointerIndex = heap[0].currentPointerIndex; 5635 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched 5636 5637 uint32_t lastPointerIndex = heap[0].lastPointerIndex; 5638 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched 5639 5640 matchedCurrentBits.markBit(currentPointerIndex); 5641 matchedLastBits.markBit(lastPointerIndex); 5642 5643 uint32_t id = mLastRawPointerData.pointers[lastPointerIndex].id; 5644 mCurrentRawPointerData.pointers[currentPointerIndex].id = id; 5645 mCurrentRawPointerData.idToIndex[id] = currentPointerIndex; 5646 mCurrentRawPointerData.markIdBit(id, 5647 mCurrentRawPointerData.isHovering(currentPointerIndex)); 5648 usedIdBits.markBit(id); 5649 5650#if DEBUG_POINTER_ASSIGNMENT 5651 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld", 5652 lastPointerIndex, currentPointerIndex, id, heap[0].distance); 5653#endif 5654 break; 5655 } 5656 } 5657 5658 // Assign fresh ids to pointers that were not matched in the process. 5659 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) { 5660 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit(); 5661 uint32_t id = usedIdBits.markFirstUnmarkedBit(); 5662 5663 mCurrentRawPointerData.pointers[currentPointerIndex].id = id; 5664 mCurrentRawPointerData.idToIndex[id] = currentPointerIndex; 5665 mCurrentRawPointerData.markIdBit(id, 5666 mCurrentRawPointerData.isHovering(currentPointerIndex)); 5667 5668#if DEBUG_POINTER_ASSIGNMENT 5669 ALOGD("assignPointerIds - assigned: cur=%d, id=%d", 5670 currentPointerIndex, id); 5671#endif 5672 } 5673} 5674 5675int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 5676 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) { 5677 return AKEY_STATE_VIRTUAL; 5678 } 5679 5680 size_t numVirtualKeys = mVirtualKeys.size(); 5681 for (size_t i = 0; i < numVirtualKeys; i++) { 5682 const VirtualKey& virtualKey = mVirtualKeys[i]; 5683 if (virtualKey.keyCode == keyCode) { 5684 return AKEY_STATE_UP; 5685 } 5686 } 5687 5688 return AKEY_STATE_UNKNOWN; 5689} 5690 5691int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 5692 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) { 5693 return AKEY_STATE_VIRTUAL; 5694 } 5695 5696 size_t numVirtualKeys = mVirtualKeys.size(); 5697 for (size_t i = 0; i < numVirtualKeys; i++) { 5698 const VirtualKey& virtualKey = mVirtualKeys[i]; 5699 if (virtualKey.scanCode == scanCode) { 5700 return AKEY_STATE_UP; 5701 } 5702 } 5703 5704 return AKEY_STATE_UNKNOWN; 5705} 5706 5707bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 5708 const int32_t* keyCodes, uint8_t* outFlags) { 5709 size_t numVirtualKeys = mVirtualKeys.size(); 5710 for (size_t i = 0; i < numVirtualKeys; i++) { 5711 const VirtualKey& virtualKey = mVirtualKeys[i]; 5712 5713 for (size_t i = 0; i < numCodes; i++) { 5714 if (virtualKey.keyCode == keyCodes[i]) { 5715 outFlags[i] = 1; 5716 } 5717 } 5718 } 5719 5720 return true; 5721} 5722 5723 5724// --- SingleTouchInputMapper --- 5725 5726SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) : 5727 TouchInputMapper(device) { 5728} 5729 5730SingleTouchInputMapper::~SingleTouchInputMapper() { 5731} 5732 5733void SingleTouchInputMapper::reset(nsecs_t when) { 5734 mSingleTouchMotionAccumulator.reset(getDevice()); 5735 5736 TouchInputMapper::reset(when); 5737} 5738 5739void SingleTouchInputMapper::process(const RawEvent* rawEvent) { 5740 TouchInputMapper::process(rawEvent); 5741 5742 mSingleTouchMotionAccumulator.process(rawEvent); 5743} 5744 5745void SingleTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) { 5746 if (mTouchButtonAccumulator.isToolActive()) { 5747 mCurrentRawPointerData.pointerCount = 1; 5748 mCurrentRawPointerData.idToIndex[0] = 0; 5749 5750 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE 5751 && (mTouchButtonAccumulator.isHovering() 5752 || (mRawPointerAxes.pressure.valid 5753 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0)); 5754 mCurrentRawPointerData.markIdBit(0, isHovering); 5755 5756 RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[0]; 5757 outPointer.id = 0; 5758 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX(); 5759 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY(); 5760 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure(); 5761 outPointer.touchMajor = 0; 5762 outPointer.touchMinor = 0; 5763 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth(); 5764 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth(); 5765 outPointer.orientation = 0; 5766 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance(); 5767 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX(); 5768 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY(); 5769 outPointer.toolType = mTouchButtonAccumulator.getToolType(); 5770 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { 5771 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; 5772 } 5773 outPointer.isHovering = isHovering; 5774 } 5775} 5776 5777void SingleTouchInputMapper::configureRawPointerAxes() { 5778 TouchInputMapper::configureRawPointerAxes(); 5779 5780 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x); 5781 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y); 5782 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure); 5783 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor); 5784 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance); 5785 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX); 5786 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY); 5787} 5788 5789 5790// --- MultiTouchInputMapper --- 5791 5792MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) : 5793 TouchInputMapper(device) { 5794} 5795 5796MultiTouchInputMapper::~MultiTouchInputMapper() { 5797} 5798 5799void MultiTouchInputMapper::reset(nsecs_t when) { 5800 mMultiTouchMotionAccumulator.reset(getDevice()); 5801 5802 mPointerIdBits.clear(); 5803 5804 TouchInputMapper::reset(when); 5805} 5806 5807void MultiTouchInputMapper::process(const RawEvent* rawEvent) { 5808 TouchInputMapper::process(rawEvent); 5809 5810 mMultiTouchMotionAccumulator.process(rawEvent); 5811} 5812 5813void MultiTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) { 5814 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount(); 5815 size_t outCount = 0; 5816 BitSet32 newPointerIdBits; 5817 5818 for (size_t inIndex = 0; inIndex < inCount; inIndex++) { 5819 const MultiTouchMotionAccumulator::Slot* inSlot = 5820 mMultiTouchMotionAccumulator.getSlot(inIndex); 5821 if (!inSlot->isInUse()) { 5822 continue; 5823 } 5824 5825 if (outCount >= MAX_POINTERS) { 5826#if DEBUG_POINTERS 5827 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; " 5828 "ignoring the rest.", 5829 getDeviceName().string(), MAX_POINTERS); 5830#endif 5831 break; // too many fingers! 5832 } 5833 5834 RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[outCount]; 5835 outPointer.x = inSlot->getX(); 5836 outPointer.y = inSlot->getY(); 5837 outPointer.pressure = inSlot->getPressure(); 5838 outPointer.touchMajor = inSlot->getTouchMajor(); 5839 outPointer.touchMinor = inSlot->getTouchMinor(); 5840 outPointer.toolMajor = inSlot->getToolMajor(); 5841 outPointer.toolMinor = inSlot->getToolMinor(); 5842 outPointer.orientation = inSlot->getOrientation(); 5843 outPointer.distance = inSlot->getDistance(); 5844 outPointer.tiltX = 0; 5845 outPointer.tiltY = 0; 5846 5847 outPointer.toolType = inSlot->getToolType(); 5848 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { 5849 outPointer.toolType = mTouchButtonAccumulator.getToolType(); 5850 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { 5851 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; 5852 } 5853 } 5854 5855 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE 5856 && (mTouchButtonAccumulator.isHovering() 5857 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0)); 5858 outPointer.isHovering = isHovering; 5859 5860 // Assign pointer id using tracking id if available. 5861 if (*outHavePointerIds) { 5862 int32_t trackingId = inSlot->getTrackingId(); 5863 int32_t id = -1; 5864 if (trackingId >= 0) { 5865 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) { 5866 uint32_t n = idBits.clearFirstMarkedBit(); 5867 if (mPointerTrackingIdMap[n] == trackingId) { 5868 id = n; 5869 } 5870 } 5871 5872 if (id < 0 && !mPointerIdBits.isFull()) { 5873 id = mPointerIdBits.markFirstUnmarkedBit(); 5874 mPointerTrackingIdMap[id] = trackingId; 5875 } 5876 } 5877 if (id < 0) { 5878 *outHavePointerIds = false; 5879 mCurrentRawPointerData.clearIdBits(); 5880 newPointerIdBits.clear(); 5881 } else { 5882 outPointer.id = id; 5883 mCurrentRawPointerData.idToIndex[id] = outCount; 5884 mCurrentRawPointerData.markIdBit(id, isHovering); 5885 newPointerIdBits.markBit(id); 5886 } 5887 } 5888 5889 outCount += 1; 5890 } 5891 5892 mCurrentRawPointerData.pointerCount = outCount; 5893 mPointerIdBits = newPointerIdBits; 5894 5895 mMultiTouchMotionAccumulator.finishSync(); 5896} 5897 5898void MultiTouchInputMapper::configureRawPointerAxes() { 5899 TouchInputMapper::configureRawPointerAxes(); 5900 5901 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x); 5902 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y); 5903 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor); 5904 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor); 5905 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor); 5906 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor); 5907 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation); 5908 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure); 5909 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance); 5910 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId); 5911 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot); 5912 5913 if (mRawPointerAxes.trackingId.valid 5914 && mRawPointerAxes.slot.valid 5915 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) { 5916 size_t slotCount = mRawPointerAxes.slot.maxValue + 1; 5917 if (slotCount > MAX_SLOTS) { 5918 ALOGW("MultiTouch Device %s reported %d slots but the framework " 5919 "only supports a maximum of %d slots at this time.", 5920 getDeviceName().string(), slotCount, MAX_SLOTS); 5921 slotCount = MAX_SLOTS; 5922 } 5923 mMultiTouchMotionAccumulator.configure(slotCount, true /*usingSlotsProtocol*/); 5924 } else { 5925 mMultiTouchMotionAccumulator.configure(MAX_POINTERS, false /*usingSlotsProtocol*/); 5926 } 5927} 5928 5929 5930// --- JoystickInputMapper --- 5931 5932JoystickInputMapper::JoystickInputMapper(InputDevice* device) : 5933 InputMapper(device) { 5934} 5935 5936JoystickInputMapper::~JoystickInputMapper() { 5937} 5938 5939uint32_t JoystickInputMapper::getSources() { 5940 return AINPUT_SOURCE_JOYSTICK; 5941} 5942 5943void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 5944 InputMapper::populateDeviceInfo(info); 5945 5946 for (size_t i = 0; i < mAxes.size(); i++) { 5947 const Axis& axis = mAxes.valueAt(i); 5948 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK, 5949 axis.min, axis.max, axis.flat, axis.fuzz); 5950 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 5951 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK, 5952 axis.min, axis.max, axis.flat, axis.fuzz); 5953 } 5954 } 5955} 5956 5957void JoystickInputMapper::dump(String8& dump) { 5958 dump.append(INDENT2 "Joystick Input Mapper:\n"); 5959 5960 dump.append(INDENT3 "Axes:\n"); 5961 size_t numAxes = mAxes.size(); 5962 for (size_t i = 0; i < numAxes; i++) { 5963 const Axis& axis = mAxes.valueAt(i); 5964 const char* label = getAxisLabel(axis.axisInfo.axis); 5965 if (label) { 5966 dump.appendFormat(INDENT4 "%s", label); 5967 } else { 5968 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis); 5969 } 5970 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 5971 label = getAxisLabel(axis.axisInfo.highAxis); 5972 if (label) { 5973 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue); 5974 } else { 5975 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis, 5976 axis.axisInfo.splitValue); 5977 } 5978 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) { 5979 dump.append(" (invert)"); 5980 } 5981 5982 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n", 5983 axis.min, axis.max, axis.flat, axis.fuzz); 5984 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, " 5985 "highScale=%0.5f, highOffset=%0.5f\n", 5986 axis.scale, axis.offset, axis.highScale, axis.highOffset); 5987 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, " 5988 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n", 5989 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue, 5990 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution); 5991 } 5992} 5993 5994void JoystickInputMapper::configure(nsecs_t when, 5995 const InputReaderConfiguration* config, uint32_t changes) { 5996 InputMapper::configure(when, config, changes); 5997 5998 if (!changes) { // first time only 5999 // Collect all axes. 6000 for (int32_t abs = 0; abs <= ABS_MAX; abs++) { 6001 if (!(getAbsAxisUsage(abs, getDevice()->getClasses()) 6002 & INPUT_DEVICE_CLASS_JOYSTICK)) { 6003 continue; // axis must be claimed by a different device 6004 } 6005 6006 RawAbsoluteAxisInfo rawAxisInfo; 6007 getAbsoluteAxisInfo(abs, &rawAxisInfo); 6008 if (rawAxisInfo.valid) { 6009 // Map axis. 6010 AxisInfo axisInfo; 6011 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo); 6012 if (!explicitlyMapped) { 6013 // Axis is not explicitly mapped, will choose a generic axis later. 6014 axisInfo.mode = AxisInfo::MODE_NORMAL; 6015 axisInfo.axis = -1; 6016 } 6017 6018 // Apply flat override. 6019 int32_t rawFlat = axisInfo.flatOverride < 0 6020 ? rawAxisInfo.flat : axisInfo.flatOverride; 6021 6022 // Calculate scaling factors and limits. 6023 Axis axis; 6024 if (axisInfo.mode == AxisInfo::MODE_SPLIT) { 6025 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue); 6026 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue); 6027 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 6028 scale, 0.0f, highScale, 0.0f, 6029 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 6030 } else if (isCenteredAxis(axisInfo.axis)) { 6031 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); 6032 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale; 6033 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 6034 scale, offset, scale, offset, 6035 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 6036 } else { 6037 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); 6038 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 6039 scale, 0.0f, scale, 0.0f, 6040 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 6041 } 6042 6043 // To eliminate noise while the joystick is at rest, filter out small variations 6044 // in axis values up front. 6045 axis.filter = axis.flat * 0.25f; 6046 6047 mAxes.add(abs, axis); 6048 } 6049 } 6050 6051 // If there are too many axes, start dropping them. 6052 // Prefer to keep explicitly mapped axes. 6053 if (mAxes.size() > PointerCoords::MAX_AXES) { 6054 ALOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.", 6055 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES); 6056 pruneAxes(true); 6057 pruneAxes(false); 6058 } 6059 6060 // Assign generic axis ids to remaining axes. 6061 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1; 6062 size_t numAxes = mAxes.size(); 6063 for (size_t i = 0; i < numAxes; i++) { 6064 Axis& axis = mAxes.editValueAt(i); 6065 if (axis.axisInfo.axis < 0) { 6066 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 6067 && haveAxis(nextGenericAxisId)) { 6068 nextGenericAxisId += 1; 6069 } 6070 6071 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) { 6072 axis.axisInfo.axis = nextGenericAxisId; 6073 nextGenericAxisId += 1; 6074 } else { 6075 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids " 6076 "have already been assigned to other axes.", 6077 getDeviceName().string(), mAxes.keyAt(i)); 6078 mAxes.removeItemsAt(i--); 6079 numAxes -= 1; 6080 } 6081 } 6082 } 6083 } 6084} 6085 6086bool JoystickInputMapper::haveAxis(int32_t axisId) { 6087 size_t numAxes = mAxes.size(); 6088 for (size_t i = 0; i < numAxes; i++) { 6089 const Axis& axis = mAxes.valueAt(i); 6090 if (axis.axisInfo.axis == axisId 6091 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT 6092 && axis.axisInfo.highAxis == axisId)) { 6093 return true; 6094 } 6095 } 6096 return false; 6097} 6098 6099void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) { 6100 size_t i = mAxes.size(); 6101 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) { 6102 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) { 6103 continue; 6104 } 6105 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.", 6106 getDeviceName().string(), mAxes.keyAt(i)); 6107 mAxes.removeItemsAt(i); 6108 } 6109} 6110 6111bool JoystickInputMapper::isCenteredAxis(int32_t axis) { 6112 switch (axis) { 6113 case AMOTION_EVENT_AXIS_X: 6114 case AMOTION_EVENT_AXIS_Y: 6115 case AMOTION_EVENT_AXIS_Z: 6116 case AMOTION_EVENT_AXIS_RX: 6117 case AMOTION_EVENT_AXIS_RY: 6118 case AMOTION_EVENT_AXIS_RZ: 6119 case AMOTION_EVENT_AXIS_HAT_X: 6120 case AMOTION_EVENT_AXIS_HAT_Y: 6121 case AMOTION_EVENT_AXIS_ORIENTATION: 6122 case AMOTION_EVENT_AXIS_RUDDER: 6123 case AMOTION_EVENT_AXIS_WHEEL: 6124 return true; 6125 default: 6126 return false; 6127 } 6128} 6129 6130void JoystickInputMapper::reset(nsecs_t when) { 6131 // Recenter all axes. 6132 size_t numAxes = mAxes.size(); 6133 for (size_t i = 0; i < numAxes; i++) { 6134 Axis& axis = mAxes.editValueAt(i); 6135 axis.resetValue(); 6136 } 6137 6138 InputMapper::reset(when); 6139} 6140 6141void JoystickInputMapper::process(const RawEvent* rawEvent) { 6142 switch (rawEvent->type) { 6143 case EV_ABS: { 6144 ssize_t index = mAxes.indexOfKey(rawEvent->code); 6145 if (index >= 0) { 6146 Axis& axis = mAxes.editValueAt(index); 6147 float newValue, highNewValue; 6148 switch (axis.axisInfo.mode) { 6149 case AxisInfo::MODE_INVERT: 6150 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) 6151 * axis.scale + axis.offset; 6152 highNewValue = 0.0f; 6153 break; 6154 case AxisInfo::MODE_SPLIT: 6155 if (rawEvent->value < axis.axisInfo.splitValue) { 6156 newValue = (axis.axisInfo.splitValue - rawEvent->value) 6157 * axis.scale + axis.offset; 6158 highNewValue = 0.0f; 6159 } else if (rawEvent->value > axis.axisInfo.splitValue) { 6160 newValue = 0.0f; 6161 highNewValue = (rawEvent->value - axis.axisInfo.splitValue) 6162 * axis.highScale + axis.highOffset; 6163 } else { 6164 newValue = 0.0f; 6165 highNewValue = 0.0f; 6166 } 6167 break; 6168 default: 6169 newValue = rawEvent->value * axis.scale + axis.offset; 6170 highNewValue = 0.0f; 6171 break; 6172 } 6173 axis.newValue = newValue; 6174 axis.highNewValue = highNewValue; 6175 } 6176 break; 6177 } 6178 6179 case EV_SYN: 6180 switch (rawEvent->code) { 6181 case SYN_REPORT: 6182 sync(rawEvent->when, false /*force*/); 6183 break; 6184 } 6185 break; 6186 } 6187} 6188 6189void JoystickInputMapper::sync(nsecs_t when, bool force) { 6190 if (!filterAxes(force)) { 6191 return; 6192 } 6193 6194 int32_t metaState = mContext->getGlobalMetaState(); 6195 int32_t buttonState = 0; 6196 6197 PointerProperties pointerProperties; 6198 pointerProperties.clear(); 6199 pointerProperties.id = 0; 6200 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN; 6201 6202 PointerCoords pointerCoords; 6203 pointerCoords.clear(); 6204 6205 size_t numAxes = mAxes.size(); 6206 for (size_t i = 0; i < numAxes; i++) { 6207 const Axis& axis = mAxes.valueAt(i); 6208 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue); 6209 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 6210 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue); 6211 } 6212 } 6213 6214 // Moving a joystick axis should not wake the devide because joysticks can 6215 // be fairly noisy even when not in use. On the other hand, pushing a gamepad 6216 // button will likely wake the device. 6217 // TODO: Use the input device configuration to control this behavior more finely. 6218 uint32_t policyFlags = 0; 6219 6220 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags, 6221 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, 6222 1, &pointerProperties, &pointerCoords, 0, 0, 0); 6223 getListener()->notifyMotion(&args); 6224} 6225 6226bool JoystickInputMapper::filterAxes(bool force) { 6227 bool atLeastOneSignificantChange = force; 6228 size_t numAxes = mAxes.size(); 6229 for (size_t i = 0; i < numAxes; i++) { 6230 Axis& axis = mAxes.editValueAt(i); 6231 if (force || hasValueChangedSignificantly(axis.filter, 6232 axis.newValue, axis.currentValue, axis.min, axis.max)) { 6233 axis.currentValue = axis.newValue; 6234 atLeastOneSignificantChange = true; 6235 } 6236 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 6237 if (force || hasValueChangedSignificantly(axis.filter, 6238 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) { 6239 axis.highCurrentValue = axis.highNewValue; 6240 atLeastOneSignificantChange = true; 6241 } 6242 } 6243 } 6244 return atLeastOneSignificantChange; 6245} 6246 6247bool JoystickInputMapper::hasValueChangedSignificantly( 6248 float filter, float newValue, float currentValue, float min, float max) { 6249 if (newValue != currentValue) { 6250 // Filter out small changes in value unless the value is converging on the axis 6251 // bounds or center point. This is intended to reduce the amount of information 6252 // sent to applications by particularly noisy joysticks (such as PS3). 6253 if (fabs(newValue - currentValue) > filter 6254 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) 6255 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) 6256 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) { 6257 return true; 6258 } 6259 } 6260 return false; 6261} 6262 6263bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange( 6264 float filter, float newValue, float currentValue, float thresholdValue) { 6265 float newDistance = fabs(newValue - thresholdValue); 6266 if (newDistance < filter) { 6267 float oldDistance = fabs(currentValue - thresholdValue); 6268 if (newDistance < oldDistance) { 6269 return true; 6270 } 6271 } 6272 return false; 6273} 6274 6275} // namespace android 6276