InputReader.cpp revision 8529745b27877d98a0c76692295a3fcac238b1e6
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#include "InputReader.h" 37 38#include <cutils/log.h> 39#include <ui/Keyboard.h> 40#include <ui/VirtualKeyMap.h> 41 42#include <stddef.h> 43#include <stdlib.h> 44#include <unistd.h> 45#include <errno.h> 46#include <limits.h> 47#include <math.h> 48 49#define INDENT " " 50#define INDENT2 " " 51#define INDENT3 " " 52#define INDENT4 " " 53 54namespace android { 55 56// --- Static Functions --- 57 58template<typename T> 59inline static T abs(const T& value) { 60 return value < 0 ? - value : value; 61} 62 63template<typename T> 64inline static T min(const T& a, const T& b) { 65 return a < b ? a : b; 66} 67 68template<typename T> 69inline static void swap(T& a, T& b) { 70 T temp = a; 71 a = b; 72 b = temp; 73} 74 75inline static float avg(float x, float y) { 76 return (x + y) / 2; 77} 78 79inline static float pythag(float x, float y) { 80 return sqrtf(x * x + y * y); 81} 82 83inline static int32_t signExtendNybble(int32_t value) { 84 return value >= 8 ? value - 16 : value; 85} 86 87static inline const char* toString(bool value) { 88 return value ? "true" : "false"; 89} 90 91static const int32_t keyCodeRotationMap[][4] = { 92 // key codes enumerated counter-clockwise with the original (unrotated) key first 93 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation 94 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT }, 95 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN }, 96 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT }, 97 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP }, 98}; 99static const int keyCodeRotationMapSize = 100 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]); 101 102int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) { 103 if (orientation != DISPLAY_ORIENTATION_0) { 104 for (int i = 0; i < keyCodeRotationMapSize; i++) { 105 if (keyCode == keyCodeRotationMap[i][0]) { 106 return keyCodeRotationMap[i][orientation]; 107 } 108 } 109 } 110 return keyCode; 111} 112 113static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) { 114 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0; 115} 116 117 118// --- InputReader --- 119 120InputReader::InputReader(const sp<EventHubInterface>& eventHub, 121 const sp<InputReaderPolicyInterface>& policy, 122 const sp<InputDispatcherInterface>& dispatcher) : 123 mEventHub(eventHub), mPolicy(policy), mDispatcher(dispatcher), 124 mGlobalMetaState(0), mDisableVirtualKeysTimeout(-1) { 125 configureExcludedDevices(); 126 updateGlobalMetaState(); 127 updateInputConfiguration(); 128} 129 130InputReader::~InputReader() { 131 for (size_t i = 0; i < mDevices.size(); i++) { 132 delete mDevices.valueAt(i); 133 } 134} 135 136void InputReader::loopOnce() { 137 RawEvent rawEvent; 138 mEventHub->getEvent(& rawEvent); 139 140#if DEBUG_RAW_EVENTS 141 LOGD("Input event: device=%d type=0x%x scancode=%d keycode=%d value=%d", 142 rawEvent.deviceId, rawEvent.type, rawEvent.scanCode, rawEvent.keyCode, 143 rawEvent.value); 144#endif 145 146 process(& rawEvent); 147} 148 149void InputReader::process(const RawEvent* rawEvent) { 150 switch (rawEvent->type) { 151 case EventHubInterface::DEVICE_ADDED: 152 addDevice(rawEvent->deviceId); 153 break; 154 155 case EventHubInterface::DEVICE_REMOVED: 156 removeDevice(rawEvent->deviceId); 157 break; 158 159 case EventHubInterface::FINISHED_DEVICE_SCAN: 160 handleConfigurationChanged(rawEvent->when); 161 break; 162 163 default: 164 consumeEvent(rawEvent); 165 break; 166 } 167} 168 169void InputReader::addDevice(int32_t deviceId) { 170 String8 name = mEventHub->getDeviceName(deviceId); 171 uint32_t classes = mEventHub->getDeviceClasses(deviceId); 172 173 InputDevice* device = createDevice(deviceId, name, classes); 174 device->configure(); 175 176 if (device->isIgnored()) { 177 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string()); 178 } else { 179 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(), 180 device->getSources()); 181 } 182 183 bool added = false; 184 { // acquire device registry writer lock 185 RWLock::AutoWLock _wl(mDeviceRegistryLock); 186 187 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 188 if (deviceIndex < 0) { 189 mDevices.add(deviceId, device); 190 added = true; 191 } 192 } // release device registry writer lock 193 194 if (! added) { 195 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId); 196 delete device; 197 return; 198 } 199} 200 201void InputReader::removeDevice(int32_t deviceId) { 202 bool removed = false; 203 InputDevice* device = NULL; 204 { // acquire device registry writer lock 205 RWLock::AutoWLock _wl(mDeviceRegistryLock); 206 207 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 208 if (deviceIndex >= 0) { 209 device = mDevices.valueAt(deviceIndex); 210 mDevices.removeItemsAt(deviceIndex, 1); 211 removed = true; 212 } 213 } // release device registry writer lock 214 215 if (! removed) { 216 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId); 217 return; 218 } 219 220 if (device->isIgnored()) { 221 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)", 222 device->getId(), device->getName().string()); 223 } else { 224 LOGI("Device removed: id=%d, name='%s', sources=0x%08x", 225 device->getId(), device->getName().string(), device->getSources()); 226 } 227 228 device->reset(); 229 230 delete device; 231} 232 233InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) { 234 InputDevice* device = new InputDevice(this, deviceId, name); 235 236 // External devices. 237 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) { 238 device->setExternal(true); 239 } 240 241 // Switch-like devices. 242 if (classes & INPUT_DEVICE_CLASS_SWITCH) { 243 device->addMapper(new SwitchInputMapper(device)); 244 } 245 246 // Keyboard-like devices. 247 uint32_t keyboardSources = 0; 248 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC; 249 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) { 250 keyboardSources |= AINPUT_SOURCE_KEYBOARD; 251 } 252 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) { 253 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC; 254 } 255 if (classes & INPUT_DEVICE_CLASS_DPAD) { 256 keyboardSources |= AINPUT_SOURCE_DPAD; 257 } 258 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) { 259 keyboardSources |= AINPUT_SOURCE_GAMEPAD; 260 } 261 262 if (keyboardSources != 0) { 263 device->addMapper(new KeyboardInputMapper(device, keyboardSources, keyboardType)); 264 } 265 266 // Cursor-like devices. 267 if (classes & INPUT_DEVICE_CLASS_CURSOR) { 268 device->addMapper(new CursorInputMapper(device)); 269 } 270 271 // Touchscreens and touchpad devices. 272 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) { 273 device->addMapper(new MultiTouchInputMapper(device)); 274 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) { 275 device->addMapper(new SingleTouchInputMapper(device)); 276 } 277 278 // Joystick-like devices. 279 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) { 280 device->addMapper(new JoystickInputMapper(device)); 281 } 282 283 return device; 284} 285 286void InputReader::consumeEvent(const RawEvent* rawEvent) { 287 int32_t deviceId = rawEvent->deviceId; 288 289 { // acquire device registry reader lock 290 RWLock::AutoRLock _rl(mDeviceRegistryLock); 291 292 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 293 if (deviceIndex < 0) { 294 LOGW("Discarding event for unknown deviceId %d.", deviceId); 295 return; 296 } 297 298 InputDevice* device = mDevices.valueAt(deviceIndex); 299 if (device->isIgnored()) { 300 //LOGD("Discarding event for ignored deviceId %d.", deviceId); 301 return; 302 } 303 304 device->process(rawEvent); 305 } // release device registry reader lock 306} 307 308void InputReader::handleConfigurationChanged(nsecs_t when) { 309 // Reset global meta state because it depends on the list of all configured devices. 310 updateGlobalMetaState(); 311 312 // Update input configuration. 313 updateInputConfiguration(); 314 315 // Enqueue configuration changed. 316 mDispatcher->notifyConfigurationChanged(when); 317} 318 319void InputReader::configureExcludedDevices() { 320 Vector<String8> excludedDeviceNames; 321 mPolicy->getExcludedDeviceNames(excludedDeviceNames); 322 323 for (size_t i = 0; i < excludedDeviceNames.size(); i++) { 324 mEventHub->addExcludedDevice(excludedDeviceNames[i]); 325 } 326} 327 328void InputReader::updateGlobalMetaState() { 329 { // acquire state lock 330 AutoMutex _l(mStateLock); 331 332 mGlobalMetaState = 0; 333 334 { // acquire device registry reader lock 335 RWLock::AutoRLock _rl(mDeviceRegistryLock); 336 337 for (size_t i = 0; i < mDevices.size(); i++) { 338 InputDevice* device = mDevices.valueAt(i); 339 mGlobalMetaState |= device->getMetaState(); 340 } 341 } // release device registry reader lock 342 } // release state lock 343} 344 345int32_t InputReader::getGlobalMetaState() { 346 { // acquire state lock 347 AutoMutex _l(mStateLock); 348 349 return mGlobalMetaState; 350 } // release state lock 351} 352 353void InputReader::updateInputConfiguration() { 354 { // acquire state lock 355 AutoMutex _l(mStateLock); 356 357 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH; 358 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS; 359 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV; 360 { // acquire device registry reader lock 361 RWLock::AutoRLock _rl(mDeviceRegistryLock); 362 363 InputDeviceInfo deviceInfo; 364 for (size_t i = 0; i < mDevices.size(); i++) { 365 InputDevice* device = mDevices.valueAt(i); 366 device->getDeviceInfo(& deviceInfo); 367 uint32_t sources = deviceInfo.getSources(); 368 369 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) { 370 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER; 371 } 372 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) { 373 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL; 374 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) { 375 navigationConfig = InputConfiguration::NAVIGATION_DPAD; 376 } 377 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) { 378 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY; 379 } 380 } 381 } // release device registry reader lock 382 383 mInputConfiguration.touchScreen = touchScreenConfig; 384 mInputConfiguration.keyboard = keyboardConfig; 385 mInputConfiguration.navigation = navigationConfig; 386 } // release state lock 387} 388 389void InputReader::disableVirtualKeysUntil(nsecs_t time) { 390 mDisableVirtualKeysTimeout = time; 391} 392 393bool InputReader::shouldDropVirtualKey(nsecs_t now, 394 InputDevice* device, int32_t keyCode, int32_t scanCode) { 395 if (now < mDisableVirtualKeysTimeout) { 396 LOGI("Dropping virtual key from device %s because virtual keys are " 397 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d", 398 device->getName().string(), 399 (mDisableVirtualKeysTimeout - now) * 0.000001, 400 keyCode, scanCode); 401 return true; 402 } else { 403 return false; 404 } 405} 406 407void InputReader::fadePointer() { 408 { // acquire device registry reader lock 409 RWLock::AutoRLock _rl(mDeviceRegistryLock); 410 411 for (size_t i = 0; i < mDevices.size(); i++) { 412 InputDevice* device = mDevices.valueAt(i); 413 device->fadePointer(); 414 } 415 } // release device registry reader lock 416} 417 418void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) { 419 { // acquire state lock 420 AutoMutex _l(mStateLock); 421 422 *outConfiguration = mInputConfiguration; 423 } // release state lock 424} 425 426status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) { 427 { // acquire device registry reader lock 428 RWLock::AutoRLock _rl(mDeviceRegistryLock); 429 430 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 431 if (deviceIndex < 0) { 432 return NAME_NOT_FOUND; 433 } 434 435 InputDevice* device = mDevices.valueAt(deviceIndex); 436 if (device->isIgnored()) { 437 return NAME_NOT_FOUND; 438 } 439 440 device->getDeviceInfo(outDeviceInfo); 441 return OK; 442 } // release device registy reader lock 443} 444 445void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) { 446 outDeviceIds.clear(); 447 448 { // acquire device registry reader lock 449 RWLock::AutoRLock _rl(mDeviceRegistryLock); 450 451 size_t numDevices = mDevices.size(); 452 for (size_t i = 0; i < numDevices; i++) { 453 InputDevice* device = mDevices.valueAt(i); 454 if (! device->isIgnored()) { 455 outDeviceIds.add(device->getId()); 456 } 457 } 458 } // release device registy reader lock 459} 460 461int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, 462 int32_t keyCode) { 463 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState); 464} 465 466int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, 467 int32_t scanCode) { 468 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState); 469} 470 471int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) { 472 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState); 473} 474 475int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code, 476 GetStateFunc getStateFunc) { 477 { // acquire device registry reader lock 478 RWLock::AutoRLock _rl(mDeviceRegistryLock); 479 480 int32_t result = AKEY_STATE_UNKNOWN; 481 if (deviceId >= 0) { 482 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 483 if (deviceIndex >= 0) { 484 InputDevice* device = mDevices.valueAt(deviceIndex); 485 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 486 result = (device->*getStateFunc)(sourceMask, code); 487 } 488 } 489 } else { 490 size_t numDevices = mDevices.size(); 491 for (size_t i = 0; i < numDevices; i++) { 492 InputDevice* device = mDevices.valueAt(i); 493 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 494 result = (device->*getStateFunc)(sourceMask, code); 495 if (result >= AKEY_STATE_DOWN) { 496 return result; 497 } 498 } 499 } 500 } 501 return result; 502 } // release device registy reader lock 503} 504 505bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, 506 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { 507 memset(outFlags, 0, numCodes); 508 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags); 509} 510 511bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes, 512 const int32_t* keyCodes, uint8_t* outFlags) { 513 { // acquire device registry reader lock 514 RWLock::AutoRLock _rl(mDeviceRegistryLock); 515 bool result = false; 516 if (deviceId >= 0) { 517 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 518 if (deviceIndex >= 0) { 519 InputDevice* device = mDevices.valueAt(deviceIndex); 520 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 521 result = device->markSupportedKeyCodes(sourceMask, 522 numCodes, keyCodes, outFlags); 523 } 524 } 525 } else { 526 size_t numDevices = mDevices.size(); 527 for (size_t i = 0; i < numDevices; i++) { 528 InputDevice* device = mDevices.valueAt(i); 529 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 530 result |= device->markSupportedKeyCodes(sourceMask, 531 numCodes, keyCodes, outFlags); 532 } 533 } 534 } 535 return result; 536 } // release device registy reader lock 537} 538 539void InputReader::dump(String8& dump) { 540 mEventHub->dump(dump); 541 dump.append("\n"); 542 543 dump.append("Input Reader State:\n"); 544 545 { // acquire device registry reader lock 546 RWLock::AutoRLock _rl(mDeviceRegistryLock); 547 548 for (size_t i = 0; i < mDevices.size(); i++) { 549 mDevices.valueAt(i)->dump(dump); 550 } 551 } // release device registy reader lock 552} 553 554 555// --- InputReaderThread --- 556 557InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) : 558 Thread(/*canCallJava*/ true), mReader(reader) { 559} 560 561InputReaderThread::~InputReaderThread() { 562} 563 564bool InputReaderThread::threadLoop() { 565 mReader->loopOnce(); 566 return true; 567} 568 569 570// --- InputDevice --- 571 572InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) : 573 mContext(context), mId(id), mName(name), mSources(0), mIsExternal(false) { 574} 575 576InputDevice::~InputDevice() { 577 size_t numMappers = mMappers.size(); 578 for (size_t i = 0; i < numMappers; i++) { 579 delete mMappers[i]; 580 } 581 mMappers.clear(); 582} 583 584void InputDevice::dump(String8& dump) { 585 InputDeviceInfo deviceInfo; 586 getDeviceInfo(& deviceInfo); 587 588 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(), 589 deviceInfo.getName().string()); 590 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal)); 591 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources()); 592 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType()); 593 594 const KeyedVector<int32_t, InputDeviceInfo::MotionRange> ranges = deviceInfo.getMotionRanges(); 595 if (!ranges.isEmpty()) { 596 dump.append(INDENT2 "Motion Ranges:\n"); 597 for (size_t i = 0; i < ranges.size(); i++) { 598 int32_t axis = ranges.keyAt(i); 599 const char* label = getAxisLabel(axis); 600 char name[32]; 601 if (label) { 602 strncpy(name, label, sizeof(name)); 603 name[sizeof(name) - 1] = '\0'; 604 } else { 605 snprintf(name, sizeof(name), "%d", axis); 606 } 607 const InputDeviceInfo::MotionRange& range = ranges.valueAt(i); 608 dump.appendFormat(INDENT3 "%s: min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n", 609 name, range.min, range.max, range.flat, range.fuzz); 610 } 611 } 612 613 size_t numMappers = mMappers.size(); 614 for (size_t i = 0; i < numMappers; i++) { 615 InputMapper* mapper = mMappers[i]; 616 mapper->dump(dump); 617 } 618} 619 620void InputDevice::addMapper(InputMapper* mapper) { 621 mMappers.add(mapper); 622} 623 624void InputDevice::configure() { 625 if (! isIgnored()) { 626 mContext->getEventHub()->getConfiguration(mId, &mConfiguration); 627 } 628 629 mSources = 0; 630 631 size_t numMappers = mMappers.size(); 632 for (size_t i = 0; i < numMappers; i++) { 633 InputMapper* mapper = mMappers[i]; 634 mapper->configure(); 635 mSources |= mapper->getSources(); 636 } 637} 638 639void InputDevice::reset() { 640 size_t numMappers = mMappers.size(); 641 for (size_t i = 0; i < numMappers; i++) { 642 InputMapper* mapper = mMappers[i]; 643 mapper->reset(); 644 } 645} 646 647void InputDevice::process(const RawEvent* rawEvent) { 648 size_t numMappers = mMappers.size(); 649 for (size_t i = 0; i < numMappers; i++) { 650 InputMapper* mapper = mMappers[i]; 651 mapper->process(rawEvent); 652 } 653} 654 655void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) { 656 outDeviceInfo->initialize(mId, mName); 657 658 size_t numMappers = mMappers.size(); 659 for (size_t i = 0; i < numMappers; i++) { 660 InputMapper* mapper = mMappers[i]; 661 mapper->populateDeviceInfo(outDeviceInfo); 662 } 663} 664 665int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 666 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState); 667} 668 669int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 670 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState); 671} 672 673int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 674 return getState(sourceMask, switchCode, & InputMapper::getSwitchState); 675} 676 677int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { 678 int32_t result = AKEY_STATE_UNKNOWN; 679 size_t numMappers = mMappers.size(); 680 for (size_t i = 0; i < numMappers; i++) { 681 InputMapper* mapper = mMappers[i]; 682 if (sourcesMatchMask(mapper->getSources(), sourceMask)) { 683 result = (mapper->*getStateFunc)(sourceMask, code); 684 if (result >= AKEY_STATE_DOWN) { 685 return result; 686 } 687 } 688 } 689 return result; 690} 691 692bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 693 const int32_t* keyCodes, uint8_t* outFlags) { 694 bool result = false; 695 size_t numMappers = mMappers.size(); 696 for (size_t i = 0; i < numMappers; i++) { 697 InputMapper* mapper = mMappers[i]; 698 if (sourcesMatchMask(mapper->getSources(), sourceMask)) { 699 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); 700 } 701 } 702 return result; 703} 704 705int32_t InputDevice::getMetaState() { 706 int32_t result = 0; 707 size_t numMappers = mMappers.size(); 708 for (size_t i = 0; i < numMappers; i++) { 709 InputMapper* mapper = mMappers[i]; 710 result |= mapper->getMetaState(); 711 } 712 return result; 713} 714 715void InputDevice::fadePointer() { 716 size_t numMappers = mMappers.size(); 717 for (size_t i = 0; i < numMappers; i++) { 718 InputMapper* mapper = mMappers[i]; 719 mapper->fadePointer(); 720 } 721} 722 723 724// --- InputMapper --- 725 726InputMapper::InputMapper(InputDevice* device) : 727 mDevice(device), mContext(device->getContext()) { 728} 729 730InputMapper::~InputMapper() { 731} 732 733void InputMapper::populateDeviceInfo(InputDeviceInfo* info) { 734 info->addSource(getSources()); 735} 736 737void InputMapper::dump(String8& dump) { 738} 739 740void InputMapper::configure() { 741} 742 743void InputMapper::reset() { 744} 745 746int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 747 return AKEY_STATE_UNKNOWN; 748} 749 750int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 751 return AKEY_STATE_UNKNOWN; 752} 753 754int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 755 return AKEY_STATE_UNKNOWN; 756} 757 758bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 759 const int32_t* keyCodes, uint8_t* outFlags) { 760 return false; 761} 762 763int32_t InputMapper::getMetaState() { 764 return 0; 765} 766 767void InputMapper::fadePointer() { 768} 769 770void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump, 771 const RawAbsoluteAxisInfo& axis, const char* name) { 772 if (axis.valid) { 773 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d\n", 774 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz); 775 } else { 776 dump.appendFormat(INDENT4 "%s: unknown range\n", name); 777 } 778} 779 780 781// --- SwitchInputMapper --- 782 783SwitchInputMapper::SwitchInputMapper(InputDevice* device) : 784 InputMapper(device) { 785} 786 787SwitchInputMapper::~SwitchInputMapper() { 788} 789 790uint32_t SwitchInputMapper::getSources() { 791 return AINPUT_SOURCE_SWITCH; 792} 793 794void SwitchInputMapper::process(const RawEvent* rawEvent) { 795 switch (rawEvent->type) { 796 case EV_SW: 797 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value); 798 break; 799 } 800} 801 802void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) { 803 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0); 804} 805 806int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 807 return getEventHub()->getSwitchState(getDeviceId(), switchCode); 808} 809 810 811// --- KeyboardInputMapper --- 812 813KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, 814 uint32_t sources, int32_t keyboardType) : 815 InputMapper(device), mSources(sources), 816 mKeyboardType(keyboardType) { 817 initializeLocked(); 818} 819 820KeyboardInputMapper::~KeyboardInputMapper() { 821} 822 823void KeyboardInputMapper::initializeLocked() { 824 mLocked.metaState = AMETA_NONE; 825 mLocked.downTime = 0; 826} 827 828uint32_t KeyboardInputMapper::getSources() { 829 return mSources; 830} 831 832void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 833 InputMapper::populateDeviceInfo(info); 834 835 info->setKeyboardType(mKeyboardType); 836} 837 838void KeyboardInputMapper::dump(String8& dump) { 839 { // acquire lock 840 AutoMutex _l(mLock); 841 dump.append(INDENT2 "Keyboard Input Mapper:\n"); 842 dumpParameters(dump); 843 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType); 844 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size()); 845 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState); 846 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime); 847 } // release lock 848} 849 850 851void KeyboardInputMapper::configure() { 852 InputMapper::configure(); 853 854 // Configure basic parameters. 855 configureParameters(); 856 857 // Reset LEDs. 858 { 859 AutoMutex _l(mLock); 860 resetLedStateLocked(); 861 } 862} 863 864void KeyboardInputMapper::configureParameters() { 865 mParameters.orientationAware = false; 866 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"), 867 mParameters.orientationAware); 868 869 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1; 870} 871 872void KeyboardInputMapper::dumpParameters(String8& dump) { 873 dump.append(INDENT3 "Parameters:\n"); 874 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 875 mParameters.associatedDisplayId); 876 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 877 toString(mParameters.orientationAware)); 878} 879 880void KeyboardInputMapper::reset() { 881 for (;;) { 882 int32_t keyCode, scanCode; 883 { // acquire lock 884 AutoMutex _l(mLock); 885 886 // Synthesize key up event on reset if keys are currently down. 887 if (mLocked.keyDowns.isEmpty()) { 888 initializeLocked(); 889 resetLedStateLocked(); 890 break; // done 891 } 892 893 const KeyDown& keyDown = mLocked.keyDowns.top(); 894 keyCode = keyDown.keyCode; 895 scanCode = keyDown.scanCode; 896 } // release lock 897 898 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 899 processKey(when, false, keyCode, scanCode, 0); 900 } 901 902 InputMapper::reset(); 903 getContext()->updateGlobalMetaState(); 904} 905 906void KeyboardInputMapper::process(const RawEvent* rawEvent) { 907 switch (rawEvent->type) { 908 case EV_KEY: { 909 int32_t scanCode = rawEvent->scanCode; 910 if (isKeyboardOrGamepadKey(scanCode)) { 911 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode, 912 rawEvent->flags); 913 } 914 break; 915 } 916 } 917} 918 919bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) { 920 return scanCode < BTN_MOUSE 921 || scanCode >= KEY_OK 922 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI); 923} 924 925void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode, 926 int32_t scanCode, uint32_t policyFlags) { 927 int32_t newMetaState; 928 nsecs_t downTime; 929 bool metaStateChanged = false; 930 931 { // acquire lock 932 AutoMutex _l(mLock); 933 934 if (down) { 935 // Rotate key codes according to orientation if needed. 936 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock. 937 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) { 938 int32_t orientation; 939 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId, 940 NULL, NULL, & orientation)) { 941 orientation = DISPLAY_ORIENTATION_0; 942 } 943 944 keyCode = rotateKeyCode(keyCode, orientation); 945 } 946 947 // Add key down. 948 ssize_t keyDownIndex = findKeyDownLocked(scanCode); 949 if (keyDownIndex >= 0) { 950 // key repeat, be sure to use same keycode as before in case of rotation 951 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode; 952 } else { 953 // key down 954 if ((policyFlags & POLICY_FLAG_VIRTUAL) 955 && mContext->shouldDropVirtualKey(when, 956 getDevice(), keyCode, scanCode)) { 957 return; 958 } 959 960 mLocked.keyDowns.push(); 961 KeyDown& keyDown = mLocked.keyDowns.editTop(); 962 keyDown.keyCode = keyCode; 963 keyDown.scanCode = scanCode; 964 } 965 966 mLocked.downTime = when; 967 } else { 968 // Remove key down. 969 ssize_t keyDownIndex = findKeyDownLocked(scanCode); 970 if (keyDownIndex >= 0) { 971 // key up, be sure to use same keycode as before in case of rotation 972 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode; 973 mLocked.keyDowns.removeAt(size_t(keyDownIndex)); 974 } else { 975 // key was not actually down 976 LOGI("Dropping key up from device %s because the key was not down. " 977 "keyCode=%d, scanCode=%d", 978 getDeviceName().string(), keyCode, scanCode); 979 return; 980 } 981 } 982 983 int32_t oldMetaState = mLocked.metaState; 984 newMetaState = updateMetaState(keyCode, down, oldMetaState); 985 if (oldMetaState != newMetaState) { 986 mLocked.metaState = newMetaState; 987 metaStateChanged = true; 988 updateLedStateLocked(false); 989 } 990 991 downTime = mLocked.downTime; 992 } // release lock 993 994 // Key down on external an keyboard should wake the device. 995 // We don't do this for internal keyboards to prevent them from waking up in your pocket. 996 // For internal keyboards, the key layout file should specify the policy flags for 997 // each wake key individually. 998 // TODO: Use the input device configuration to control this behavior more finely. 999 if (down && getDevice()->isExternal() 1000 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) { 1001 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 1002 } 1003 1004 if (metaStateChanged) { 1005 getContext()->updateGlobalMetaState(); 1006 } 1007 1008 if (down && !isMetaKey(keyCode)) { 1009 getContext()->fadePointer(); 1010 } 1011 1012 if (policyFlags & POLICY_FLAG_FUNCTION) { 1013 newMetaState |= AMETA_FUNCTION_ON; 1014 } 1015 getDispatcher()->notifyKey(when, getDeviceId(), mSources, policyFlags, 1016 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, 1017 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime); 1018} 1019 1020ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) { 1021 size_t n = mLocked.keyDowns.size(); 1022 for (size_t i = 0; i < n; i++) { 1023 if (mLocked.keyDowns[i].scanCode == scanCode) { 1024 return i; 1025 } 1026 } 1027 return -1; 1028} 1029 1030int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 1031 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode); 1032} 1033 1034int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 1035 return getEventHub()->getScanCodeState(getDeviceId(), scanCode); 1036} 1037 1038bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 1039 const int32_t* keyCodes, uint8_t* outFlags) { 1040 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags); 1041} 1042 1043int32_t KeyboardInputMapper::getMetaState() { 1044 { // acquire lock 1045 AutoMutex _l(mLock); 1046 return mLocked.metaState; 1047 } // release lock 1048} 1049 1050void KeyboardInputMapper::resetLedStateLocked() { 1051 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL); 1052 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML); 1053 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL); 1054 1055 updateLedStateLocked(true); 1056} 1057 1058void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) { 1059 ledState.avail = getEventHub()->hasLed(getDeviceId(), led); 1060 ledState.on = false; 1061} 1062 1063void KeyboardInputMapper::updateLedStateLocked(bool reset) { 1064 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL, 1065 AMETA_CAPS_LOCK_ON, reset); 1066 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML, 1067 AMETA_NUM_LOCK_ON, reset); 1068 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL, 1069 AMETA_SCROLL_LOCK_ON, reset); 1070} 1071 1072void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState, 1073 int32_t led, int32_t modifier, bool reset) { 1074 if (ledState.avail) { 1075 bool desiredState = (mLocked.metaState & modifier) != 0; 1076 if (reset || ledState.on != desiredState) { 1077 getEventHub()->setLedState(getDeviceId(), led, desiredState); 1078 ledState.on = desiredState; 1079 } 1080 } 1081} 1082 1083 1084// --- CursorInputMapper --- 1085 1086CursorInputMapper::CursorInputMapper(InputDevice* device) : 1087 InputMapper(device) { 1088 initializeLocked(); 1089} 1090 1091CursorInputMapper::~CursorInputMapper() { 1092} 1093 1094uint32_t CursorInputMapper::getSources() { 1095 return mSources; 1096} 1097 1098void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 1099 InputMapper::populateDeviceInfo(info); 1100 1101 if (mParameters.mode == Parameters::MODE_POINTER) { 1102 float minX, minY, maxX, maxY; 1103 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) { 1104 info->addMotionRange(AMOTION_EVENT_AXIS_X, minX, maxX, 0.0f, 0.0f); 1105 info->addMotionRange(AMOTION_EVENT_AXIS_Y, minY, maxY, 0.0f, 0.0f); 1106 } 1107 } else { 1108 info->addMotionRange(AMOTION_EVENT_AXIS_X, -1.0f, 1.0f, 0.0f, mXScale); 1109 info->addMotionRange(AMOTION_EVENT_AXIS_Y, -1.0f, 1.0f, 0.0f, mYScale); 1110 } 1111 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, 0.0f, 1.0f, 0.0f, 0.0f); 1112 1113 if (mHaveVWheel) { 1114 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, -1.0f, 1.0f, 0.0f, 0.0f); 1115 } 1116 if (mHaveHWheel) { 1117 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, -1.0f, 1.0f, 0.0f, 0.0f); 1118 } 1119} 1120 1121void CursorInputMapper::dump(String8& dump) { 1122 { // acquire lock 1123 AutoMutex _l(mLock); 1124 dump.append(INDENT2 "Cursor Input Mapper:\n"); 1125 dumpParameters(dump); 1126 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale); 1127 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale); 1128 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision); 1129 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision); 1130 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel)); 1131 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel)); 1132 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale); 1133 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale); 1134 dump.appendFormat(INDENT3 "Down: %s\n", toString(mLocked.down)); 1135 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime); 1136 } // release lock 1137} 1138 1139void CursorInputMapper::configure() { 1140 InputMapper::configure(); 1141 1142 // Configure basic parameters. 1143 configureParameters(); 1144 1145 // Configure device mode. 1146 switch (mParameters.mode) { 1147 case Parameters::MODE_POINTER: 1148 mSources = AINPUT_SOURCE_MOUSE; 1149 mXPrecision = 1.0f; 1150 mYPrecision = 1.0f; 1151 mXScale = 1.0f; 1152 mYScale = 1.0f; 1153 mPointerController = getPolicy()->obtainPointerController(getDeviceId()); 1154 break; 1155 case Parameters::MODE_NAVIGATION: 1156 mSources = AINPUT_SOURCE_TRACKBALL; 1157 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD; 1158 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD; 1159 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; 1160 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; 1161 break; 1162 } 1163 1164 mVWheelScale = 1.0f; 1165 mHWheelScale = 1.0f; 1166 1167 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL); 1168 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL); 1169} 1170 1171void CursorInputMapper::configureParameters() { 1172 mParameters.mode = Parameters::MODE_POINTER; 1173 String8 cursorModeString; 1174 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) { 1175 if (cursorModeString == "navigation") { 1176 mParameters.mode = Parameters::MODE_NAVIGATION; 1177 } else if (cursorModeString != "pointer" && cursorModeString != "default") { 1178 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string()); 1179 } 1180 } 1181 1182 mParameters.orientationAware = false; 1183 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"), 1184 mParameters.orientationAware); 1185 1186 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER 1187 || mParameters.orientationAware ? 0 : -1; 1188} 1189 1190void CursorInputMapper::dumpParameters(String8& dump) { 1191 dump.append(INDENT3 "Parameters:\n"); 1192 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 1193 mParameters.associatedDisplayId); 1194 1195 switch (mParameters.mode) { 1196 case Parameters::MODE_POINTER: 1197 dump.append(INDENT4 "Mode: pointer\n"); 1198 break; 1199 case Parameters::MODE_NAVIGATION: 1200 dump.append(INDENT4 "Mode: navigation\n"); 1201 break; 1202 default: 1203 assert(false); 1204 } 1205 1206 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 1207 toString(mParameters.orientationAware)); 1208} 1209 1210void CursorInputMapper::initializeLocked() { 1211 mAccumulator.clear(); 1212 1213 mLocked.down = false; 1214 mLocked.downTime = 0; 1215} 1216 1217void CursorInputMapper::reset() { 1218 for (;;) { 1219 { // acquire lock 1220 AutoMutex _l(mLock); 1221 1222 if (! mLocked.down) { 1223 initializeLocked(); 1224 break; // done 1225 } 1226 } // release lock 1227 1228 // Synthesize button up event on reset. 1229 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 1230 mAccumulator.fields = Accumulator::FIELD_BTN_MOUSE; 1231 mAccumulator.btnMouse = false; 1232 sync(when); 1233 } 1234 1235 InputMapper::reset(); 1236} 1237 1238void CursorInputMapper::process(const RawEvent* rawEvent) { 1239 switch (rawEvent->type) { 1240 case EV_KEY: 1241 switch (rawEvent->scanCode) { 1242 case BTN_LEFT: 1243 case BTN_RIGHT: 1244 case BTN_MIDDLE: 1245 case BTN_SIDE: 1246 case BTN_EXTRA: 1247 case BTN_FORWARD: 1248 case BTN_BACK: 1249 case BTN_TASK: 1250 mAccumulator.fields |= Accumulator::FIELD_BTN_MOUSE; 1251 mAccumulator.btnMouse = rawEvent->value != 0; 1252 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and 1253 // we need to ensure that we report the up/down promptly. 1254 sync(rawEvent->when); 1255 break; 1256 } 1257 break; 1258 1259 case EV_REL: 1260 switch (rawEvent->scanCode) { 1261 case REL_X: 1262 mAccumulator.fields |= Accumulator::FIELD_REL_X; 1263 mAccumulator.relX = rawEvent->value; 1264 break; 1265 case REL_Y: 1266 mAccumulator.fields |= Accumulator::FIELD_REL_Y; 1267 mAccumulator.relY = rawEvent->value; 1268 break; 1269 case REL_WHEEL: 1270 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL; 1271 mAccumulator.relWheel = rawEvent->value; 1272 break; 1273 case REL_HWHEEL: 1274 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL; 1275 mAccumulator.relHWheel = rawEvent->value; 1276 break; 1277 } 1278 break; 1279 1280 case EV_SYN: 1281 switch (rawEvent->scanCode) { 1282 case SYN_REPORT: 1283 sync(rawEvent->when); 1284 break; 1285 } 1286 break; 1287 } 1288} 1289 1290void CursorInputMapper::sync(nsecs_t when) { 1291 uint32_t fields = mAccumulator.fields; 1292 if (fields == 0) { 1293 return; // no new state changes, so nothing to do 1294 } 1295 1296 int motionEventAction; 1297 PointerCoords pointerCoords; 1298 nsecs_t downTime; 1299 float vscroll, hscroll; 1300 { // acquire lock 1301 AutoMutex _l(mLock); 1302 1303 bool downChanged = fields & Accumulator::FIELD_BTN_MOUSE; 1304 1305 if (downChanged) { 1306 if (mAccumulator.btnMouse) { 1307 if (!mLocked.down) { 1308 mLocked.down = true; 1309 mLocked.downTime = when; 1310 } else { 1311 downChanged = false; 1312 } 1313 } else { 1314 if (mLocked.down) { 1315 mLocked.down = false; 1316 } else { 1317 downChanged = false; 1318 } 1319 } 1320 } 1321 1322 downTime = mLocked.downTime; 1323 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f; 1324 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f; 1325 1326 if (downChanged) { 1327 motionEventAction = mLocked.down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP; 1328 } else if (mLocked.down || mPointerController == NULL) { 1329 motionEventAction = AMOTION_EVENT_ACTION_MOVE; 1330 } else { 1331 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE; 1332 } 1333 1334 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0 1335 && (deltaX != 0.0f || deltaY != 0.0f)) { 1336 // Rotate motion based on display orientation if needed. 1337 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock. 1338 int32_t orientation; 1339 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId, 1340 NULL, NULL, & orientation)) { 1341 orientation = DISPLAY_ORIENTATION_0; 1342 } 1343 1344 float temp; 1345 switch (orientation) { 1346 case DISPLAY_ORIENTATION_90: 1347 temp = deltaX; 1348 deltaX = deltaY; 1349 deltaY = -temp; 1350 break; 1351 1352 case DISPLAY_ORIENTATION_180: 1353 deltaX = -deltaX; 1354 deltaY = -deltaY; 1355 break; 1356 1357 case DISPLAY_ORIENTATION_270: 1358 temp = deltaX; 1359 deltaX = -deltaY; 1360 deltaY = temp; 1361 break; 1362 } 1363 } 1364 1365 pointerCoords.clear(); 1366 1367 if (mPointerController != NULL) { 1368 mPointerController->move(deltaX, deltaY); 1369 if (downChanged) { 1370 mPointerController->setButtonState(mLocked.down ? POINTER_BUTTON_1 : 0); 1371 } 1372 float x, y; 1373 mPointerController->getPosition(&x, &y); 1374 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); 1375 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 1376 } else { 1377 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); 1378 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); 1379 } 1380 1381 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, mLocked.down ? 1.0f : 0.0f); 1382 1383 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) { 1384 vscroll = mAccumulator.relWheel; 1385 } else { 1386 vscroll = 0; 1387 } 1388 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) { 1389 hscroll = mAccumulator.relHWheel; 1390 } else { 1391 hscroll = 0; 1392 } 1393 if (hscroll != 0 || vscroll != 0) { 1394 mPointerController->unfade(); 1395 } 1396 } // release lock 1397 1398 // Moving an external trackball or mouse should wake the device. 1399 // We don't do this for internal cursor devices to prevent them from waking up 1400 // the device in your pocket. 1401 // TODO: Use the input device configuration to control this behavior more finely. 1402 uint32_t policyFlags = 0; 1403 if (getDevice()->isExternal()) { 1404 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 1405 } 1406 1407 int32_t metaState = mContext->getGlobalMetaState(); 1408 int32_t pointerId = 0; 1409 getDispatcher()->notifyMotion(when, getDeviceId(), mSources, policyFlags, 1410 motionEventAction, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 1411 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime); 1412 1413 mAccumulator.clear(); 1414 1415 if (vscroll != 0 || hscroll != 0) { 1416 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); 1417 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); 1418 1419 getDispatcher()->notifyMotion(when, getDeviceId(), mSources, policyFlags, 1420 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 1421 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime); 1422 } 1423} 1424 1425int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 1426 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) { 1427 return getEventHub()->getScanCodeState(getDeviceId(), scanCode); 1428 } else { 1429 return AKEY_STATE_UNKNOWN; 1430 } 1431} 1432 1433void CursorInputMapper::fadePointer() { 1434 { // acquire lock 1435 AutoMutex _l(mLock); 1436 mPointerController->fade(); 1437 } // release lock 1438} 1439 1440 1441// --- TouchInputMapper --- 1442 1443TouchInputMapper::TouchInputMapper(InputDevice* device) : 1444 InputMapper(device) { 1445 mLocked.surfaceOrientation = -1; 1446 mLocked.surfaceWidth = -1; 1447 mLocked.surfaceHeight = -1; 1448 1449 initializeLocked(); 1450} 1451 1452TouchInputMapper::~TouchInputMapper() { 1453} 1454 1455uint32_t TouchInputMapper::getSources() { 1456 return mSources; 1457} 1458 1459void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 1460 InputMapper::populateDeviceInfo(info); 1461 1462 { // acquire lock 1463 AutoMutex _l(mLock); 1464 1465 // Ensure surface information is up to date so that orientation changes are 1466 // noticed immediately. 1467 configureSurfaceLocked(); 1468 1469 info->addMotionRange(AMOTION_EVENT_AXIS_X, mLocked.orientedRanges.x); 1470 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mLocked.orientedRanges.y); 1471 1472 if (mLocked.orientedRanges.havePressure) { 1473 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, 1474 mLocked.orientedRanges.pressure); 1475 } 1476 1477 if (mLocked.orientedRanges.haveSize) { 1478 info->addMotionRange(AMOTION_EVENT_AXIS_SIZE, 1479 mLocked.orientedRanges.size); 1480 } 1481 1482 if (mLocked.orientedRanges.haveTouchSize) { 1483 info->addMotionRange(AMOTION_EVENT_AXIS_TOUCH_MAJOR, 1484 mLocked.orientedRanges.touchMajor); 1485 info->addMotionRange(AMOTION_EVENT_AXIS_TOUCH_MINOR, 1486 mLocked.orientedRanges.touchMinor); 1487 } 1488 1489 if (mLocked.orientedRanges.haveToolSize) { 1490 info->addMotionRange(AMOTION_EVENT_AXIS_TOOL_MAJOR, 1491 mLocked.orientedRanges.toolMajor); 1492 info->addMotionRange(AMOTION_EVENT_AXIS_TOOL_MINOR, 1493 mLocked.orientedRanges.toolMinor); 1494 } 1495 1496 if (mLocked.orientedRanges.haveOrientation) { 1497 info->addMotionRange(AMOTION_EVENT_AXIS_ORIENTATION, 1498 mLocked.orientedRanges.orientation); 1499 } 1500 } // release lock 1501} 1502 1503void TouchInputMapper::dump(String8& dump) { 1504 { // acquire lock 1505 AutoMutex _l(mLock); 1506 dump.append(INDENT2 "Touch Input Mapper:\n"); 1507 dumpParameters(dump); 1508 dumpVirtualKeysLocked(dump); 1509 dumpRawAxes(dump); 1510 dumpCalibration(dump); 1511 dumpSurfaceLocked(dump); 1512 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n"); 1513 dump.appendFormat(INDENT4 "XOrigin: %d\n", mLocked.xOrigin); 1514 dump.appendFormat(INDENT4 "YOrigin: %d\n", mLocked.yOrigin); 1515 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale); 1516 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale); 1517 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision); 1518 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision); 1519 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale); 1520 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale); 1521 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias); 1522 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale); 1523 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias); 1524 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale); 1525 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale); 1526 dump.appendFormat(INDENT4 "OrientationSCale: %0.3f\n", mLocked.orientationScale); 1527 } // release lock 1528} 1529 1530void TouchInputMapper::initializeLocked() { 1531 mCurrentTouch.clear(); 1532 mLastTouch.clear(); 1533 mDownTime = 0; 1534 1535 for (uint32_t i = 0; i < MAX_POINTERS; i++) { 1536 mAveragingTouchFilter.historyStart[i] = 0; 1537 mAveragingTouchFilter.historyEnd[i] = 0; 1538 } 1539 1540 mJumpyTouchFilter.jumpyPointsDropped = 0; 1541 1542 mLocked.currentVirtualKey.down = false; 1543 1544 mLocked.orientedRanges.havePressure = false; 1545 mLocked.orientedRanges.haveSize = false; 1546 mLocked.orientedRanges.haveTouchSize = false; 1547 mLocked.orientedRanges.haveToolSize = false; 1548 mLocked.orientedRanges.haveOrientation = false; 1549} 1550 1551void TouchInputMapper::configure() { 1552 InputMapper::configure(); 1553 1554 // Configure basic parameters. 1555 configureParameters(); 1556 1557 // Configure sources. 1558 switch (mParameters.deviceType) { 1559 case Parameters::DEVICE_TYPE_TOUCH_SCREEN: 1560 mSources = AINPUT_SOURCE_TOUCHSCREEN; 1561 break; 1562 case Parameters::DEVICE_TYPE_TOUCH_PAD: 1563 mSources = AINPUT_SOURCE_TOUCHPAD; 1564 break; 1565 default: 1566 assert(false); 1567 } 1568 1569 // Configure absolute axis information. 1570 configureRawAxes(); 1571 1572 // Prepare input device calibration. 1573 parseCalibration(); 1574 resolveCalibration(); 1575 1576 { // acquire lock 1577 AutoMutex _l(mLock); 1578 1579 // Configure surface dimensions and orientation. 1580 configureSurfaceLocked(); 1581 } // release lock 1582} 1583 1584void TouchInputMapper::configureParameters() { 1585 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents(); 1586 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents(); 1587 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents(); 1588 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime(); 1589 1590 String8 deviceTypeString; 1591 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; 1592 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"), 1593 deviceTypeString)) { 1594 if (deviceTypeString == "touchScreen") { 1595 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; 1596 } else if (deviceTypeString != "touchPad") { 1597 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string()); 1598 } 1599 } 1600 bool isTouchScreen = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN; 1601 1602 mParameters.orientationAware = isTouchScreen; 1603 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"), 1604 mParameters.orientationAware); 1605 1606 mParameters.associatedDisplayId = mParameters.orientationAware || isTouchScreen ? 0 : -1; 1607} 1608 1609void TouchInputMapper::dumpParameters(String8& dump) { 1610 dump.append(INDENT3 "Parameters:\n"); 1611 1612 switch (mParameters.deviceType) { 1613 case Parameters::DEVICE_TYPE_TOUCH_SCREEN: 1614 dump.append(INDENT4 "DeviceType: touchScreen\n"); 1615 break; 1616 case Parameters::DEVICE_TYPE_TOUCH_PAD: 1617 dump.append(INDENT4 "DeviceType: touchPad\n"); 1618 break; 1619 default: 1620 assert(false); 1621 } 1622 1623 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 1624 mParameters.associatedDisplayId); 1625 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 1626 toString(mParameters.orientationAware)); 1627 1628 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n", 1629 toString(mParameters.useBadTouchFilter)); 1630 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n", 1631 toString(mParameters.useAveragingTouchFilter)); 1632 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n", 1633 toString(mParameters.useJumpyTouchFilter)); 1634} 1635 1636void TouchInputMapper::configureRawAxes() { 1637 mRawAxes.x.clear(); 1638 mRawAxes.y.clear(); 1639 mRawAxes.pressure.clear(); 1640 mRawAxes.touchMajor.clear(); 1641 mRawAxes.touchMinor.clear(); 1642 mRawAxes.toolMajor.clear(); 1643 mRawAxes.toolMinor.clear(); 1644 mRawAxes.orientation.clear(); 1645} 1646 1647void TouchInputMapper::dumpRawAxes(String8& dump) { 1648 dump.append(INDENT3 "Raw Axes:\n"); 1649 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X"); 1650 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y"); 1651 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure"); 1652 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor"); 1653 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor"); 1654 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor"); 1655 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor"); 1656 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation"); 1657} 1658 1659bool TouchInputMapper::configureSurfaceLocked() { 1660 // Update orientation and dimensions if needed. 1661 int32_t orientation = DISPLAY_ORIENTATION_0; 1662 int32_t width = mRawAxes.x.getRange(); 1663 int32_t height = mRawAxes.y.getRange(); 1664 1665 if (mParameters.associatedDisplayId >= 0) { 1666 bool wantSize = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN; 1667 bool wantOrientation = mParameters.orientationAware; 1668 1669 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock. 1670 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId, 1671 wantSize ? &width : NULL, wantSize ? &height : NULL, 1672 wantOrientation ? &orientation : NULL)) { 1673 return false; 1674 } 1675 } 1676 1677 bool orientationChanged = mLocked.surfaceOrientation != orientation; 1678 if (orientationChanged) { 1679 mLocked.surfaceOrientation = orientation; 1680 } 1681 1682 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height; 1683 if (sizeChanged) { 1684 LOGI("Device reconfigured: id=%d, name='%s', display size is now %dx%d", 1685 getDeviceId(), getDeviceName().string(), width, height); 1686 1687 mLocked.surfaceWidth = width; 1688 mLocked.surfaceHeight = height; 1689 1690 // Configure X and Y factors. 1691 if (mRawAxes.x.valid && mRawAxes.y.valid) { 1692 mLocked.xOrigin = mCalibration.haveXOrigin 1693 ? mCalibration.xOrigin 1694 : mRawAxes.x.minValue; 1695 mLocked.yOrigin = mCalibration.haveYOrigin 1696 ? mCalibration.yOrigin 1697 : mRawAxes.y.minValue; 1698 mLocked.xScale = mCalibration.haveXScale 1699 ? mCalibration.xScale 1700 : float(width) / mRawAxes.x.getRange(); 1701 mLocked.yScale = mCalibration.haveYScale 1702 ? mCalibration.yScale 1703 : float(height) / mRawAxes.y.getRange(); 1704 mLocked.xPrecision = 1.0f / mLocked.xScale; 1705 mLocked.yPrecision = 1.0f / mLocked.yScale; 1706 1707 configureVirtualKeysLocked(); 1708 } else { 1709 LOGW(INDENT "Touch device did not report support for X or Y axis!"); 1710 mLocked.xOrigin = 0; 1711 mLocked.yOrigin = 0; 1712 mLocked.xScale = 1.0f; 1713 mLocked.yScale = 1.0f; 1714 mLocked.xPrecision = 1.0f; 1715 mLocked.yPrecision = 1.0f; 1716 } 1717 1718 // Scale factor for terms that are not oriented in a particular axis. 1719 // If the pixels are square then xScale == yScale otherwise we fake it 1720 // by choosing an average. 1721 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale); 1722 1723 // Size of diagonal axis. 1724 float diagonalSize = pythag(width, height); 1725 1726 // TouchMajor and TouchMinor factors. 1727 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) { 1728 mLocked.orientedRanges.haveTouchSize = true; 1729 mLocked.orientedRanges.touchMajor.min = 0; 1730 mLocked.orientedRanges.touchMajor.max = diagonalSize; 1731 mLocked.orientedRanges.touchMajor.flat = 0; 1732 mLocked.orientedRanges.touchMajor.fuzz = 0; 1733 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor; 1734 } 1735 1736 // ToolMajor and ToolMinor factors. 1737 mLocked.toolSizeLinearScale = 0; 1738 mLocked.toolSizeLinearBias = 0; 1739 mLocked.toolSizeAreaScale = 0; 1740 mLocked.toolSizeAreaBias = 0; 1741 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) { 1742 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) { 1743 if (mCalibration.haveToolSizeLinearScale) { 1744 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale; 1745 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) { 1746 mLocked.toolSizeLinearScale = float(min(width, height)) 1747 / mRawAxes.toolMajor.maxValue; 1748 } 1749 1750 if (mCalibration.haveToolSizeLinearBias) { 1751 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias; 1752 } 1753 } else if (mCalibration.toolSizeCalibration == 1754 Calibration::TOOL_SIZE_CALIBRATION_AREA) { 1755 if (mCalibration.haveToolSizeLinearScale) { 1756 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale; 1757 } else { 1758 mLocked.toolSizeLinearScale = min(width, height); 1759 } 1760 1761 if (mCalibration.haveToolSizeLinearBias) { 1762 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias; 1763 } 1764 1765 if (mCalibration.haveToolSizeAreaScale) { 1766 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale; 1767 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) { 1768 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue; 1769 } 1770 1771 if (mCalibration.haveToolSizeAreaBias) { 1772 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias; 1773 } 1774 } 1775 1776 mLocked.orientedRanges.haveToolSize = true; 1777 mLocked.orientedRanges.toolMajor.min = 0; 1778 mLocked.orientedRanges.toolMajor.max = diagonalSize; 1779 mLocked.orientedRanges.toolMajor.flat = 0; 1780 mLocked.orientedRanges.toolMajor.fuzz = 0; 1781 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor; 1782 } 1783 1784 // Pressure factors. 1785 mLocked.pressureScale = 0; 1786 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) { 1787 RawAbsoluteAxisInfo rawPressureAxis; 1788 switch (mCalibration.pressureSource) { 1789 case Calibration::PRESSURE_SOURCE_PRESSURE: 1790 rawPressureAxis = mRawAxes.pressure; 1791 break; 1792 case Calibration::PRESSURE_SOURCE_TOUCH: 1793 rawPressureAxis = mRawAxes.touchMajor; 1794 break; 1795 default: 1796 rawPressureAxis.clear(); 1797 } 1798 1799 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL 1800 || mCalibration.pressureCalibration 1801 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) { 1802 if (mCalibration.havePressureScale) { 1803 mLocked.pressureScale = mCalibration.pressureScale; 1804 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) { 1805 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue; 1806 } 1807 } 1808 1809 mLocked.orientedRanges.havePressure = true; 1810 mLocked.orientedRanges.pressure.min = 0; 1811 mLocked.orientedRanges.pressure.max = 1.0; 1812 mLocked.orientedRanges.pressure.flat = 0; 1813 mLocked.orientedRanges.pressure.fuzz = 0; 1814 } 1815 1816 // Size factors. 1817 mLocked.sizeScale = 0; 1818 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) { 1819 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) { 1820 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) { 1821 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue; 1822 } 1823 } 1824 1825 mLocked.orientedRanges.haveSize = true; 1826 mLocked.orientedRanges.size.min = 0; 1827 mLocked.orientedRanges.size.max = 1.0; 1828 mLocked.orientedRanges.size.flat = 0; 1829 mLocked.orientedRanges.size.fuzz = 0; 1830 } 1831 1832 // Orientation 1833 mLocked.orientationScale = 0; 1834 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) { 1835 if (mCalibration.orientationCalibration 1836 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) { 1837 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) { 1838 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue; 1839 } 1840 } 1841 1842 mLocked.orientedRanges.orientation.min = - M_PI_2; 1843 mLocked.orientedRanges.orientation.max = M_PI_2; 1844 mLocked.orientedRanges.orientation.flat = 0; 1845 mLocked.orientedRanges.orientation.fuzz = 0; 1846 } 1847 } 1848 1849 if (orientationChanged || sizeChanged) { 1850 // Compute oriented surface dimensions, precision, and scales. 1851 float orientedXScale, orientedYScale; 1852 switch (mLocked.surfaceOrientation) { 1853 case DISPLAY_ORIENTATION_90: 1854 case DISPLAY_ORIENTATION_270: 1855 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight; 1856 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth; 1857 mLocked.orientedXPrecision = mLocked.yPrecision; 1858 mLocked.orientedYPrecision = mLocked.xPrecision; 1859 orientedXScale = mLocked.yScale; 1860 orientedYScale = mLocked.xScale; 1861 break; 1862 default: 1863 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth; 1864 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight; 1865 mLocked.orientedXPrecision = mLocked.xPrecision; 1866 mLocked.orientedYPrecision = mLocked.yPrecision; 1867 orientedXScale = mLocked.xScale; 1868 orientedYScale = mLocked.yScale; 1869 break; 1870 } 1871 1872 // Configure position ranges. 1873 mLocked.orientedRanges.x.min = 0; 1874 mLocked.orientedRanges.x.max = mLocked.orientedSurfaceWidth; 1875 mLocked.orientedRanges.x.flat = 0; 1876 mLocked.orientedRanges.x.fuzz = orientedXScale; 1877 1878 mLocked.orientedRanges.y.min = 0; 1879 mLocked.orientedRanges.y.max = mLocked.orientedSurfaceHeight; 1880 mLocked.orientedRanges.y.flat = 0; 1881 mLocked.orientedRanges.y.fuzz = orientedYScale; 1882 } 1883 1884 return true; 1885} 1886 1887void TouchInputMapper::dumpSurfaceLocked(String8& dump) { 1888 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth); 1889 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight); 1890 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation); 1891} 1892 1893void TouchInputMapper::configureVirtualKeysLocked() { 1894 assert(mRawAxes.x.valid && mRawAxes.y.valid); 1895 1896 Vector<VirtualKeyDefinition> virtualKeyDefinitions; 1897 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions); 1898 1899 mLocked.virtualKeys.clear(); 1900 1901 if (virtualKeyDefinitions.size() == 0) { 1902 return; 1903 } 1904 1905 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size()); 1906 1907 int32_t touchScreenLeft = mRawAxes.x.minValue; 1908 int32_t touchScreenTop = mRawAxes.y.minValue; 1909 int32_t touchScreenWidth = mRawAxes.x.getRange(); 1910 int32_t touchScreenHeight = mRawAxes.y.getRange(); 1911 1912 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) { 1913 const VirtualKeyDefinition& virtualKeyDefinition = 1914 virtualKeyDefinitions[i]; 1915 1916 mLocked.virtualKeys.add(); 1917 VirtualKey& virtualKey = mLocked.virtualKeys.editTop(); 1918 1919 virtualKey.scanCode = virtualKeyDefinition.scanCode; 1920 int32_t keyCode; 1921 uint32_t flags; 1922 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 1923 & keyCode, & flags)) { 1924 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", 1925 virtualKey.scanCode); 1926 mLocked.virtualKeys.pop(); // drop the key 1927 continue; 1928 } 1929 1930 virtualKey.keyCode = keyCode; 1931 virtualKey.flags = flags; 1932 1933 // convert the key definition's display coordinates into touch coordinates for a hit box 1934 int32_t halfWidth = virtualKeyDefinition.width / 2; 1935 int32_t halfHeight = virtualKeyDefinition.height / 2; 1936 1937 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) 1938 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft; 1939 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth) 1940 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft; 1941 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) 1942 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop; 1943 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) 1944 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop; 1945 1946 } 1947} 1948 1949void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) { 1950 if (!mLocked.virtualKeys.isEmpty()) { 1951 dump.append(INDENT3 "Virtual Keys:\n"); 1952 1953 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) { 1954 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i); 1955 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, " 1956 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n", 1957 i, virtualKey.scanCode, virtualKey.keyCode, 1958 virtualKey.hitLeft, virtualKey.hitRight, 1959 virtualKey.hitTop, virtualKey.hitBottom); 1960 } 1961 } 1962} 1963 1964void TouchInputMapper::parseCalibration() { 1965 const PropertyMap& in = getDevice()->getConfiguration(); 1966 Calibration& out = mCalibration; 1967 1968 // Position 1969 out.haveXOrigin = in.tryGetProperty(String8("touch.position.xOrigin"), out.xOrigin); 1970 out.haveYOrigin = in.tryGetProperty(String8("touch.position.yOrigin"), out.yOrigin); 1971 out.haveXScale = in.tryGetProperty(String8("touch.position.xScale"), out.xScale); 1972 out.haveYScale = in.tryGetProperty(String8("touch.position.yScale"), out.yScale); 1973 1974 // Touch Size 1975 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT; 1976 String8 touchSizeCalibrationString; 1977 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) { 1978 if (touchSizeCalibrationString == "none") { 1979 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE; 1980 } else if (touchSizeCalibrationString == "geometric") { 1981 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC; 1982 } else if (touchSizeCalibrationString == "pressure") { 1983 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE; 1984 } else if (touchSizeCalibrationString != "default") { 1985 LOGW("Invalid value for touch.touchSize.calibration: '%s'", 1986 touchSizeCalibrationString.string()); 1987 } 1988 } 1989 1990 // Tool Size 1991 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT; 1992 String8 toolSizeCalibrationString; 1993 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) { 1994 if (toolSizeCalibrationString == "none") { 1995 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE; 1996 } else if (toolSizeCalibrationString == "geometric") { 1997 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC; 1998 } else if (toolSizeCalibrationString == "linear") { 1999 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR; 2000 } else if (toolSizeCalibrationString == "area") { 2001 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA; 2002 } else if (toolSizeCalibrationString != "default") { 2003 LOGW("Invalid value for touch.toolSize.calibration: '%s'", 2004 toolSizeCalibrationString.string()); 2005 } 2006 } 2007 2008 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"), 2009 out.toolSizeLinearScale); 2010 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"), 2011 out.toolSizeLinearBias); 2012 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"), 2013 out.toolSizeAreaScale); 2014 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"), 2015 out.toolSizeAreaBias); 2016 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"), 2017 out.toolSizeIsSummed); 2018 2019 // Pressure 2020 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT; 2021 String8 pressureCalibrationString; 2022 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) { 2023 if (pressureCalibrationString == "none") { 2024 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; 2025 } else if (pressureCalibrationString == "physical") { 2026 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; 2027 } else if (pressureCalibrationString == "amplitude") { 2028 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE; 2029 } else if (pressureCalibrationString != "default") { 2030 LOGW("Invalid value for touch.pressure.calibration: '%s'", 2031 pressureCalibrationString.string()); 2032 } 2033 } 2034 2035 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT; 2036 String8 pressureSourceString; 2037 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) { 2038 if (pressureSourceString == "pressure") { 2039 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE; 2040 } else if (pressureSourceString == "touch") { 2041 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH; 2042 } else if (pressureSourceString != "default") { 2043 LOGW("Invalid value for touch.pressure.source: '%s'", 2044 pressureSourceString.string()); 2045 } 2046 } 2047 2048 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), 2049 out.pressureScale); 2050 2051 // Size 2052 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT; 2053 String8 sizeCalibrationString; 2054 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) { 2055 if (sizeCalibrationString == "none") { 2056 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; 2057 } else if (sizeCalibrationString == "normalized") { 2058 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED; 2059 } else if (sizeCalibrationString != "default") { 2060 LOGW("Invalid value for touch.size.calibration: '%s'", 2061 sizeCalibrationString.string()); 2062 } 2063 } 2064 2065 // Orientation 2066 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT; 2067 String8 orientationCalibrationString; 2068 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) { 2069 if (orientationCalibrationString == "none") { 2070 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; 2071 } else if (orientationCalibrationString == "interpolated") { 2072 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; 2073 } else if (orientationCalibrationString == "vector") { 2074 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR; 2075 } else if (orientationCalibrationString != "default") { 2076 LOGW("Invalid value for touch.orientation.calibration: '%s'", 2077 orientationCalibrationString.string()); 2078 } 2079 } 2080} 2081 2082void TouchInputMapper::resolveCalibration() { 2083 // Pressure 2084 switch (mCalibration.pressureSource) { 2085 case Calibration::PRESSURE_SOURCE_DEFAULT: 2086 if (mRawAxes.pressure.valid) { 2087 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE; 2088 } else if (mRawAxes.touchMajor.valid) { 2089 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH; 2090 } 2091 break; 2092 2093 case Calibration::PRESSURE_SOURCE_PRESSURE: 2094 if (! mRawAxes.pressure.valid) { 2095 LOGW("Calibration property touch.pressure.source is 'pressure' but " 2096 "the pressure axis is not available."); 2097 } 2098 break; 2099 2100 case Calibration::PRESSURE_SOURCE_TOUCH: 2101 if (! mRawAxes.touchMajor.valid) { 2102 LOGW("Calibration property touch.pressure.source is 'touch' but " 2103 "the touchMajor axis is not available."); 2104 } 2105 break; 2106 2107 default: 2108 break; 2109 } 2110 2111 switch (mCalibration.pressureCalibration) { 2112 case Calibration::PRESSURE_CALIBRATION_DEFAULT: 2113 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) { 2114 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE; 2115 } else { 2116 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; 2117 } 2118 break; 2119 2120 default: 2121 break; 2122 } 2123 2124 // Tool Size 2125 switch (mCalibration.toolSizeCalibration) { 2126 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT: 2127 if (mRawAxes.toolMajor.valid) { 2128 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR; 2129 } else { 2130 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE; 2131 } 2132 break; 2133 2134 default: 2135 break; 2136 } 2137 2138 // Touch Size 2139 switch (mCalibration.touchSizeCalibration) { 2140 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT: 2141 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE 2142 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) { 2143 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE; 2144 } else { 2145 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE; 2146 } 2147 break; 2148 2149 default: 2150 break; 2151 } 2152 2153 // Size 2154 switch (mCalibration.sizeCalibration) { 2155 case Calibration::SIZE_CALIBRATION_DEFAULT: 2156 if (mRawAxes.toolMajor.valid) { 2157 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED; 2158 } else { 2159 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; 2160 } 2161 break; 2162 2163 default: 2164 break; 2165 } 2166 2167 // Orientation 2168 switch (mCalibration.orientationCalibration) { 2169 case Calibration::ORIENTATION_CALIBRATION_DEFAULT: 2170 if (mRawAxes.orientation.valid) { 2171 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; 2172 } else { 2173 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; 2174 } 2175 break; 2176 2177 default: 2178 break; 2179 } 2180} 2181 2182void TouchInputMapper::dumpCalibration(String8& dump) { 2183 dump.append(INDENT3 "Calibration:\n"); 2184 2185 // Position 2186 if (mCalibration.haveXOrigin) { 2187 dump.appendFormat(INDENT4 "touch.position.xOrigin: %d\n", mCalibration.xOrigin); 2188 } 2189 if (mCalibration.haveYOrigin) { 2190 dump.appendFormat(INDENT4 "touch.position.yOrigin: %d\n", mCalibration.yOrigin); 2191 } 2192 if (mCalibration.haveXScale) { 2193 dump.appendFormat(INDENT4 "touch.position.xScale: %0.3f\n", mCalibration.xScale); 2194 } 2195 if (mCalibration.haveYScale) { 2196 dump.appendFormat(INDENT4 "touch.position.yScale: %0.3f\n", mCalibration.yScale); 2197 } 2198 2199 // Touch Size 2200 switch (mCalibration.touchSizeCalibration) { 2201 case Calibration::TOUCH_SIZE_CALIBRATION_NONE: 2202 dump.append(INDENT4 "touch.touchSize.calibration: none\n"); 2203 break; 2204 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC: 2205 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n"); 2206 break; 2207 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE: 2208 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n"); 2209 break; 2210 default: 2211 assert(false); 2212 } 2213 2214 // Tool Size 2215 switch (mCalibration.toolSizeCalibration) { 2216 case Calibration::TOOL_SIZE_CALIBRATION_NONE: 2217 dump.append(INDENT4 "touch.toolSize.calibration: none\n"); 2218 break; 2219 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC: 2220 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n"); 2221 break; 2222 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR: 2223 dump.append(INDENT4 "touch.toolSize.calibration: linear\n"); 2224 break; 2225 case Calibration::TOOL_SIZE_CALIBRATION_AREA: 2226 dump.append(INDENT4 "touch.toolSize.calibration: area\n"); 2227 break; 2228 default: 2229 assert(false); 2230 } 2231 2232 if (mCalibration.haveToolSizeLinearScale) { 2233 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n", 2234 mCalibration.toolSizeLinearScale); 2235 } 2236 2237 if (mCalibration.haveToolSizeLinearBias) { 2238 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n", 2239 mCalibration.toolSizeLinearBias); 2240 } 2241 2242 if (mCalibration.haveToolSizeAreaScale) { 2243 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n", 2244 mCalibration.toolSizeAreaScale); 2245 } 2246 2247 if (mCalibration.haveToolSizeAreaBias) { 2248 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n", 2249 mCalibration.toolSizeAreaBias); 2250 } 2251 2252 if (mCalibration.haveToolSizeIsSummed) { 2253 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n", 2254 toString(mCalibration.toolSizeIsSummed)); 2255 } 2256 2257 // Pressure 2258 switch (mCalibration.pressureCalibration) { 2259 case Calibration::PRESSURE_CALIBRATION_NONE: 2260 dump.append(INDENT4 "touch.pressure.calibration: none\n"); 2261 break; 2262 case Calibration::PRESSURE_CALIBRATION_PHYSICAL: 2263 dump.append(INDENT4 "touch.pressure.calibration: physical\n"); 2264 break; 2265 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: 2266 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n"); 2267 break; 2268 default: 2269 assert(false); 2270 } 2271 2272 switch (mCalibration.pressureSource) { 2273 case Calibration::PRESSURE_SOURCE_PRESSURE: 2274 dump.append(INDENT4 "touch.pressure.source: pressure\n"); 2275 break; 2276 case Calibration::PRESSURE_SOURCE_TOUCH: 2277 dump.append(INDENT4 "touch.pressure.source: touch\n"); 2278 break; 2279 case Calibration::PRESSURE_SOURCE_DEFAULT: 2280 break; 2281 default: 2282 assert(false); 2283 } 2284 2285 if (mCalibration.havePressureScale) { 2286 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n", 2287 mCalibration.pressureScale); 2288 } 2289 2290 // Size 2291 switch (mCalibration.sizeCalibration) { 2292 case Calibration::SIZE_CALIBRATION_NONE: 2293 dump.append(INDENT4 "touch.size.calibration: none\n"); 2294 break; 2295 case Calibration::SIZE_CALIBRATION_NORMALIZED: 2296 dump.append(INDENT4 "touch.size.calibration: normalized\n"); 2297 break; 2298 default: 2299 assert(false); 2300 } 2301 2302 // Orientation 2303 switch (mCalibration.orientationCalibration) { 2304 case Calibration::ORIENTATION_CALIBRATION_NONE: 2305 dump.append(INDENT4 "touch.orientation.calibration: none\n"); 2306 break; 2307 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: 2308 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n"); 2309 break; 2310 case Calibration::ORIENTATION_CALIBRATION_VECTOR: 2311 dump.append(INDENT4 "touch.orientation.calibration: vector\n"); 2312 break; 2313 default: 2314 assert(false); 2315 } 2316} 2317 2318void TouchInputMapper::reset() { 2319 // Synthesize touch up event if touch is currently down. 2320 // This will also take care of finishing virtual key processing if needed. 2321 if (mLastTouch.pointerCount != 0) { 2322 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 2323 mCurrentTouch.clear(); 2324 syncTouch(when, true); 2325 } 2326 2327 { // acquire lock 2328 AutoMutex _l(mLock); 2329 initializeLocked(); 2330 } // release lock 2331 2332 InputMapper::reset(); 2333} 2334 2335void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) { 2336 // Preprocess pointer data. 2337 if (mParameters.useBadTouchFilter) { 2338 if (applyBadTouchFilter()) { 2339 havePointerIds = false; 2340 } 2341 } 2342 2343 if (mParameters.useJumpyTouchFilter) { 2344 if (applyJumpyTouchFilter()) { 2345 havePointerIds = false; 2346 } 2347 } 2348 2349 if (! havePointerIds) { 2350 calculatePointerIds(); 2351 } 2352 2353 TouchData temp; 2354 TouchData* savedTouch; 2355 if (mParameters.useAveragingTouchFilter) { 2356 temp.copyFrom(mCurrentTouch); 2357 savedTouch = & temp; 2358 2359 applyAveragingTouchFilter(); 2360 } else { 2361 savedTouch = & mCurrentTouch; 2362 } 2363 2364 uint32_t policyFlags = 0; 2365 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) { 2366 // Hide the pointer on an initial down. 2367 getContext()->fadePointer(); 2368 2369 // Initial downs on external touch devices should wake the device. 2370 // We don't do this for internal touch screens to prevent them from waking 2371 // up in your pocket. 2372 // TODO: Use the input device configuration to control this behavior more finely. 2373 if (getDevice()->isExternal()) { 2374 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 2375 } 2376 } 2377 2378 // Process touches and virtual keys. 2379 TouchResult touchResult = consumeOffScreenTouches(when, policyFlags); 2380 if (touchResult == DISPATCH_TOUCH) { 2381 detectGestures(when); 2382 dispatchTouches(when, policyFlags); 2383 } 2384 2385 // Copy current touch to last touch in preparation for the next cycle. 2386 if (touchResult == DROP_STROKE) { 2387 mLastTouch.clear(); 2388 } else { 2389 mLastTouch.copyFrom(*savedTouch); 2390 } 2391} 2392 2393TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches( 2394 nsecs_t when, uint32_t policyFlags) { 2395 int32_t keyEventAction, keyEventFlags; 2396 int32_t keyCode, scanCode, downTime; 2397 TouchResult touchResult; 2398 2399 { // acquire lock 2400 AutoMutex _l(mLock); 2401 2402 // Update surface size and orientation, including virtual key positions. 2403 if (! configureSurfaceLocked()) { 2404 return DROP_STROKE; 2405 } 2406 2407 // Check for virtual key press. 2408 if (mLocked.currentVirtualKey.down) { 2409 if (mCurrentTouch.pointerCount == 0) { 2410 // Pointer went up while virtual key was down. 2411 mLocked.currentVirtualKey.down = false; 2412#if DEBUG_VIRTUAL_KEYS 2413 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d", 2414 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode); 2415#endif 2416 keyEventAction = AKEY_EVENT_ACTION_UP; 2417 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY; 2418 touchResult = SKIP_TOUCH; 2419 goto DispatchVirtualKey; 2420 } 2421 2422 if (mCurrentTouch.pointerCount == 1) { 2423 int32_t x = mCurrentTouch.pointers[0].x; 2424 int32_t y = mCurrentTouch.pointers[0].y; 2425 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y); 2426 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) { 2427 // Pointer is still within the space of the virtual key. 2428 return SKIP_TOUCH; 2429 } 2430 } 2431 2432 // Pointer left virtual key area or another pointer also went down. 2433 // Send key cancellation and drop the stroke so subsequent motions will be 2434 // considered fresh downs. This is useful when the user swipes away from the 2435 // virtual key area into the main display surface. 2436 mLocked.currentVirtualKey.down = false; 2437#if DEBUG_VIRTUAL_KEYS 2438 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", 2439 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode); 2440#endif 2441 keyEventAction = AKEY_EVENT_ACTION_UP; 2442 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY 2443 | AKEY_EVENT_FLAG_CANCELED; 2444 2445 // Check whether the pointer moved inside the display area where we should 2446 // start a new stroke. 2447 int32_t x = mCurrentTouch.pointers[0].x; 2448 int32_t y = mCurrentTouch.pointers[0].y; 2449 if (isPointInsideSurfaceLocked(x, y)) { 2450 mLastTouch.clear(); 2451 touchResult = DISPATCH_TOUCH; 2452 } else { 2453 touchResult = DROP_STROKE; 2454 } 2455 } else { 2456 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) { 2457 // Pointer just went down. Handle off-screen touches, if needed. 2458 int32_t x = mCurrentTouch.pointers[0].x; 2459 int32_t y = mCurrentTouch.pointers[0].y; 2460 if (! isPointInsideSurfaceLocked(x, y)) { 2461 // If exactly one pointer went down, check for virtual key hit. 2462 // Otherwise we will drop the entire stroke. 2463 if (mCurrentTouch.pointerCount == 1) { 2464 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y); 2465 if (virtualKey) { 2466 if (mContext->shouldDropVirtualKey(when, getDevice(), 2467 virtualKey->keyCode, virtualKey->scanCode)) { 2468 return DROP_STROKE; 2469 } 2470 2471 mLocked.currentVirtualKey.down = true; 2472 mLocked.currentVirtualKey.downTime = when; 2473 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode; 2474 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode; 2475#if DEBUG_VIRTUAL_KEYS 2476 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d", 2477 mLocked.currentVirtualKey.keyCode, 2478 mLocked.currentVirtualKey.scanCode); 2479#endif 2480 keyEventAction = AKEY_EVENT_ACTION_DOWN; 2481 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM 2482 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY; 2483 touchResult = SKIP_TOUCH; 2484 goto DispatchVirtualKey; 2485 } 2486 } 2487 return DROP_STROKE; 2488 } 2489 } 2490 return DISPATCH_TOUCH; 2491 } 2492 2493 DispatchVirtualKey: 2494 // Collect remaining state needed to dispatch virtual key. 2495 keyCode = mLocked.currentVirtualKey.keyCode; 2496 scanCode = mLocked.currentVirtualKey.scanCode; 2497 downTime = mLocked.currentVirtualKey.downTime; 2498 } // release lock 2499 2500 // Dispatch virtual key. 2501 int32_t metaState = mContext->getGlobalMetaState(); 2502 policyFlags |= POLICY_FLAG_VIRTUAL; 2503 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags, 2504 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); 2505 return touchResult; 2506} 2507 2508void TouchInputMapper::detectGestures(nsecs_t when) { 2509 // Disable all virtual key touches that happen within a short time interval of the 2510 // most recent touch. The idea is to filter out stray virtual key presses when 2511 // interacting with the touch screen. 2512 // 2513 // Problems we're trying to solve: 2514 // 2515 // 1. While scrolling a list or dragging the window shade, the user swipes down into a 2516 // virtual key area that is implemented by a separate touch panel and accidentally 2517 // triggers a virtual key. 2518 // 2519 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen 2520 // area and accidentally triggers a virtual key. This often happens when virtual keys 2521 // are layed out below the screen near to where the on screen keyboard's space bar 2522 // is displayed. 2523 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) { 2524 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime); 2525 } 2526} 2527 2528void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) { 2529 uint32_t currentPointerCount = mCurrentTouch.pointerCount; 2530 uint32_t lastPointerCount = mLastTouch.pointerCount; 2531 if (currentPointerCount == 0 && lastPointerCount == 0) { 2532 return; // nothing to do! 2533 } 2534 2535 BitSet32 currentIdBits = mCurrentTouch.idBits; 2536 BitSet32 lastIdBits = mLastTouch.idBits; 2537 2538 if (currentIdBits == lastIdBits) { 2539 // No pointer id changes so this is a move event. 2540 // The dispatcher takes care of batching moves so we don't have to deal with that here. 2541 int32_t motionEventAction = AMOTION_EVENT_ACTION_MOVE; 2542 dispatchTouch(when, policyFlags, & mCurrentTouch, 2543 currentIdBits, -1, currentPointerCount, motionEventAction); 2544 } else { 2545 // There may be pointers going up and pointers going down and pointers moving 2546 // all at the same time. 2547 BitSet32 upIdBits(lastIdBits.value & ~ currentIdBits.value); 2548 BitSet32 downIdBits(currentIdBits.value & ~ lastIdBits.value); 2549 BitSet32 activeIdBits(lastIdBits.value); 2550 uint32_t pointerCount = lastPointerCount; 2551 2552 // Produce an intermediate representation of the touch data that consists of the 2553 // old location of pointers that have just gone up and the new location of pointers that 2554 // have just moved but omits the location of pointers that have just gone down. 2555 TouchData interimTouch; 2556 interimTouch.copyFrom(mLastTouch); 2557 2558 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value); 2559 bool moveNeeded = false; 2560 while (!moveIdBits.isEmpty()) { 2561 uint32_t moveId = moveIdBits.firstMarkedBit(); 2562 moveIdBits.clearBit(moveId); 2563 2564 int32_t oldIndex = mLastTouch.idToIndex[moveId]; 2565 int32_t newIndex = mCurrentTouch.idToIndex[moveId]; 2566 if (mLastTouch.pointers[oldIndex] != mCurrentTouch.pointers[newIndex]) { 2567 interimTouch.pointers[oldIndex] = mCurrentTouch.pointers[newIndex]; 2568 moveNeeded = true; 2569 } 2570 } 2571 2572 // Dispatch pointer up events using the interim pointer locations. 2573 while (!upIdBits.isEmpty()) { 2574 uint32_t upId = upIdBits.firstMarkedBit(); 2575 upIdBits.clearBit(upId); 2576 BitSet32 oldActiveIdBits = activeIdBits; 2577 activeIdBits.clearBit(upId); 2578 2579 int32_t motionEventAction; 2580 if (activeIdBits.isEmpty()) { 2581 motionEventAction = AMOTION_EVENT_ACTION_UP; 2582 } else { 2583 motionEventAction = AMOTION_EVENT_ACTION_POINTER_UP; 2584 } 2585 2586 dispatchTouch(when, policyFlags, &interimTouch, 2587 oldActiveIdBits, upId, pointerCount, motionEventAction); 2588 pointerCount -= 1; 2589 } 2590 2591 // Dispatch move events if any of the remaining pointers moved from their old locations. 2592 // Although applications receive new locations as part of individual pointer up 2593 // events, they do not generally handle them except when presented in a move event. 2594 if (moveNeeded) { 2595 dispatchTouch(when, policyFlags, &mCurrentTouch, 2596 activeIdBits, -1, pointerCount, AMOTION_EVENT_ACTION_MOVE); 2597 } 2598 2599 // Dispatch pointer down events using the new pointer locations. 2600 while (!downIdBits.isEmpty()) { 2601 uint32_t downId = downIdBits.firstMarkedBit(); 2602 downIdBits.clearBit(downId); 2603 BitSet32 oldActiveIdBits = activeIdBits; 2604 activeIdBits.markBit(downId); 2605 2606 int32_t motionEventAction; 2607 if (oldActiveIdBits.isEmpty()) { 2608 motionEventAction = AMOTION_EVENT_ACTION_DOWN; 2609 mDownTime = when; 2610 } else { 2611 motionEventAction = AMOTION_EVENT_ACTION_POINTER_DOWN; 2612 } 2613 2614 pointerCount += 1; 2615 dispatchTouch(when, policyFlags, &mCurrentTouch, 2616 activeIdBits, downId, pointerCount, motionEventAction); 2617 } 2618 } 2619} 2620 2621void TouchInputMapper::dispatchTouch(nsecs_t when, uint32_t policyFlags, 2622 TouchData* touch, BitSet32 idBits, uint32_t changedId, uint32_t pointerCount, 2623 int32_t motionEventAction) { 2624 int32_t pointerIds[MAX_POINTERS]; 2625 PointerCoords pointerCoords[MAX_POINTERS]; 2626 int32_t motionEventEdgeFlags = 0; 2627 float xPrecision, yPrecision; 2628 2629 { // acquire lock 2630 AutoMutex _l(mLock); 2631 2632 // Walk through the the active pointers and map touch screen coordinates (TouchData) into 2633 // display coordinates (PointerCoords) and adjust for display orientation. 2634 for (uint32_t outIndex = 0; ! idBits.isEmpty(); outIndex++) { 2635 uint32_t id = idBits.firstMarkedBit(); 2636 idBits.clearBit(id); 2637 uint32_t inIndex = touch->idToIndex[id]; 2638 2639 const PointerData& in = touch->pointers[inIndex]; 2640 2641 // X and Y 2642 float x = float(in.x - mLocked.xOrigin) * mLocked.xScale; 2643 float y = float(in.y - mLocked.yOrigin) * mLocked.yScale; 2644 2645 // ToolMajor and ToolMinor 2646 float toolMajor, toolMinor; 2647 switch (mCalibration.toolSizeCalibration) { 2648 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC: 2649 toolMajor = in.toolMajor * mLocked.geometricScale; 2650 if (mRawAxes.toolMinor.valid) { 2651 toolMinor = in.toolMinor * mLocked.geometricScale; 2652 } else { 2653 toolMinor = toolMajor; 2654 } 2655 break; 2656 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR: 2657 toolMajor = in.toolMajor != 0 2658 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias 2659 : 0; 2660 if (mRawAxes.toolMinor.valid) { 2661 toolMinor = in.toolMinor != 0 2662 ? in.toolMinor * mLocked.toolSizeLinearScale 2663 + mLocked.toolSizeLinearBias 2664 : 0; 2665 } else { 2666 toolMinor = toolMajor; 2667 } 2668 break; 2669 case Calibration::TOOL_SIZE_CALIBRATION_AREA: 2670 if (in.toolMajor != 0) { 2671 float diameter = sqrtf(in.toolMajor 2672 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias); 2673 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias; 2674 } else { 2675 toolMajor = 0; 2676 } 2677 toolMinor = toolMajor; 2678 break; 2679 default: 2680 toolMajor = 0; 2681 toolMinor = 0; 2682 break; 2683 } 2684 2685 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) { 2686 toolMajor /= pointerCount; 2687 toolMinor /= pointerCount; 2688 } 2689 2690 // Pressure 2691 float rawPressure; 2692 switch (mCalibration.pressureSource) { 2693 case Calibration::PRESSURE_SOURCE_PRESSURE: 2694 rawPressure = in.pressure; 2695 break; 2696 case Calibration::PRESSURE_SOURCE_TOUCH: 2697 rawPressure = in.touchMajor; 2698 break; 2699 default: 2700 rawPressure = 0; 2701 } 2702 2703 float pressure; 2704 switch (mCalibration.pressureCalibration) { 2705 case Calibration::PRESSURE_CALIBRATION_PHYSICAL: 2706 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: 2707 pressure = rawPressure * mLocked.pressureScale; 2708 break; 2709 default: 2710 pressure = 1; 2711 break; 2712 } 2713 2714 // TouchMajor and TouchMinor 2715 float touchMajor, touchMinor; 2716 switch (mCalibration.touchSizeCalibration) { 2717 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC: 2718 touchMajor = in.touchMajor * mLocked.geometricScale; 2719 if (mRawAxes.touchMinor.valid) { 2720 touchMinor = in.touchMinor * mLocked.geometricScale; 2721 } else { 2722 touchMinor = touchMajor; 2723 } 2724 break; 2725 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE: 2726 touchMajor = toolMajor * pressure; 2727 touchMinor = toolMinor * pressure; 2728 break; 2729 default: 2730 touchMajor = 0; 2731 touchMinor = 0; 2732 break; 2733 } 2734 2735 if (touchMajor > toolMajor) { 2736 touchMajor = toolMajor; 2737 } 2738 if (touchMinor > toolMinor) { 2739 touchMinor = toolMinor; 2740 } 2741 2742 // Size 2743 float size; 2744 switch (mCalibration.sizeCalibration) { 2745 case Calibration::SIZE_CALIBRATION_NORMALIZED: { 2746 float rawSize = mRawAxes.toolMinor.valid 2747 ? avg(in.toolMajor, in.toolMinor) 2748 : in.toolMajor; 2749 size = rawSize * mLocked.sizeScale; 2750 break; 2751 } 2752 default: 2753 size = 0; 2754 break; 2755 } 2756 2757 // Orientation 2758 float orientation; 2759 switch (mCalibration.orientationCalibration) { 2760 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: 2761 orientation = in.orientation * mLocked.orientationScale; 2762 break; 2763 case Calibration::ORIENTATION_CALIBRATION_VECTOR: { 2764 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4); 2765 int32_t c2 = signExtendNybble(in.orientation & 0x0f); 2766 if (c1 != 0 || c2 != 0) { 2767 orientation = atan2f(c1, c2) * 0.5f; 2768 float scale = 1.0f + pythag(c1, c2) / 16.0f; 2769 touchMajor *= scale; 2770 touchMinor /= scale; 2771 toolMajor *= scale; 2772 toolMinor /= scale; 2773 } else { 2774 orientation = 0; 2775 } 2776 break; 2777 } 2778 default: 2779 orientation = 0; 2780 } 2781 2782 // Adjust coords for orientation. 2783 switch (mLocked.surfaceOrientation) { 2784 case DISPLAY_ORIENTATION_90: { 2785 float xTemp = x; 2786 x = y; 2787 y = mLocked.surfaceWidth - xTemp; 2788 orientation -= M_PI_2; 2789 if (orientation < - M_PI_2) { 2790 orientation += M_PI; 2791 } 2792 break; 2793 } 2794 case DISPLAY_ORIENTATION_180: { 2795 x = mLocked.surfaceWidth - x; 2796 y = mLocked.surfaceHeight - y; 2797 break; 2798 } 2799 case DISPLAY_ORIENTATION_270: { 2800 float xTemp = x; 2801 x = mLocked.surfaceHeight - y; 2802 y = xTemp; 2803 orientation += M_PI_2; 2804 if (orientation > M_PI_2) { 2805 orientation -= M_PI; 2806 } 2807 break; 2808 } 2809 } 2810 2811 // Write output coords. 2812 PointerCoords& out = pointerCoords[outIndex]; 2813 out.clear(); 2814 out.setAxisValue(AMOTION_EVENT_AXIS_X, x); 2815 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 2816 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure); 2817 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size); 2818 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor); 2819 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor); 2820 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor); 2821 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor); 2822 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation); 2823 2824 pointerIds[outIndex] = int32_t(id); 2825 2826 if (id == changedId) { 2827 motionEventAction |= outIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; 2828 } 2829 } 2830 2831 // Check edge flags by looking only at the first pointer since the flags are 2832 // global to the event. 2833 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) { 2834 float x = pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X); 2835 float y = pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y); 2836 2837 if (x <= 0) { 2838 motionEventEdgeFlags |= AMOTION_EVENT_EDGE_FLAG_LEFT; 2839 } else if (x >= mLocked.orientedSurfaceWidth) { 2840 motionEventEdgeFlags |= AMOTION_EVENT_EDGE_FLAG_RIGHT; 2841 } 2842 if (y <= 0) { 2843 motionEventEdgeFlags |= AMOTION_EVENT_EDGE_FLAG_TOP; 2844 } else if (y >= mLocked.orientedSurfaceHeight) { 2845 motionEventEdgeFlags |= AMOTION_EVENT_EDGE_FLAG_BOTTOM; 2846 } 2847 } 2848 2849 xPrecision = mLocked.orientedXPrecision; 2850 yPrecision = mLocked.orientedYPrecision; 2851 } // release lock 2852 2853 getDispatcher()->notifyMotion(when, getDeviceId(), mSources, policyFlags, 2854 motionEventAction, 0, getContext()->getGlobalMetaState(), motionEventEdgeFlags, 2855 pointerCount, pointerIds, pointerCoords, 2856 xPrecision, yPrecision, mDownTime); 2857} 2858 2859bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) { 2860 if (mRawAxes.x.valid && mRawAxes.y.valid) { 2861 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue 2862 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue; 2863 } 2864 return true; 2865} 2866 2867const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked( 2868 int32_t x, int32_t y) { 2869 size_t numVirtualKeys = mLocked.virtualKeys.size(); 2870 for (size_t i = 0; i < numVirtualKeys; i++) { 2871 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 2872 2873#if DEBUG_VIRTUAL_KEYS 2874 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, " 2875 "left=%d, top=%d, right=%d, bottom=%d", 2876 x, y, 2877 virtualKey.keyCode, virtualKey.scanCode, 2878 virtualKey.hitLeft, virtualKey.hitTop, 2879 virtualKey.hitRight, virtualKey.hitBottom); 2880#endif 2881 2882 if (virtualKey.isHit(x, y)) { 2883 return & virtualKey; 2884 } 2885 } 2886 2887 return NULL; 2888} 2889 2890void TouchInputMapper::calculatePointerIds() { 2891 uint32_t currentPointerCount = mCurrentTouch.pointerCount; 2892 uint32_t lastPointerCount = mLastTouch.pointerCount; 2893 2894 if (currentPointerCount == 0) { 2895 // No pointers to assign. 2896 mCurrentTouch.idBits.clear(); 2897 } else if (lastPointerCount == 0) { 2898 // All pointers are new. 2899 mCurrentTouch.idBits.clear(); 2900 for (uint32_t i = 0; i < currentPointerCount; i++) { 2901 mCurrentTouch.pointers[i].id = i; 2902 mCurrentTouch.idToIndex[i] = i; 2903 mCurrentTouch.idBits.markBit(i); 2904 } 2905 } else if (currentPointerCount == 1 && lastPointerCount == 1) { 2906 // Only one pointer and no change in count so it must have the same id as before. 2907 uint32_t id = mLastTouch.pointers[0].id; 2908 mCurrentTouch.pointers[0].id = id; 2909 mCurrentTouch.idToIndex[id] = 0; 2910 mCurrentTouch.idBits.value = BitSet32::valueForBit(id); 2911 } else { 2912 // General case. 2913 // We build a heap of squared euclidean distances between current and last pointers 2914 // associated with the current and last pointer indices. Then, we find the best 2915 // match (by distance) for each current pointer. 2916 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS]; 2917 2918 uint32_t heapSize = 0; 2919 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount; 2920 currentPointerIndex++) { 2921 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount; 2922 lastPointerIndex++) { 2923 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x 2924 - mLastTouch.pointers[lastPointerIndex].x; 2925 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y 2926 - mLastTouch.pointers[lastPointerIndex].y; 2927 2928 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY); 2929 2930 // Insert new element into the heap (sift up). 2931 heap[heapSize].currentPointerIndex = currentPointerIndex; 2932 heap[heapSize].lastPointerIndex = lastPointerIndex; 2933 heap[heapSize].distance = distance; 2934 heapSize += 1; 2935 } 2936 } 2937 2938 // Heapify 2939 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) { 2940 startIndex -= 1; 2941 for (uint32_t parentIndex = startIndex; ;) { 2942 uint32_t childIndex = parentIndex * 2 + 1; 2943 if (childIndex >= heapSize) { 2944 break; 2945 } 2946 2947 if (childIndex + 1 < heapSize 2948 && heap[childIndex + 1].distance < heap[childIndex].distance) { 2949 childIndex += 1; 2950 } 2951 2952 if (heap[parentIndex].distance <= heap[childIndex].distance) { 2953 break; 2954 } 2955 2956 swap(heap[parentIndex], heap[childIndex]); 2957 parentIndex = childIndex; 2958 } 2959 } 2960 2961#if DEBUG_POINTER_ASSIGNMENT 2962 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize); 2963 for (size_t i = 0; i < heapSize; i++) { 2964 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", 2965 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, 2966 heap[i].distance); 2967 } 2968#endif 2969 2970 // Pull matches out by increasing order of distance. 2971 // To avoid reassigning pointers that have already been matched, the loop keeps track 2972 // of which last and current pointers have been matched using the matchedXXXBits variables. 2973 // It also tracks the used pointer id bits. 2974 BitSet32 matchedLastBits(0); 2975 BitSet32 matchedCurrentBits(0); 2976 BitSet32 usedIdBits(0); 2977 bool first = true; 2978 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) { 2979 for (;;) { 2980 if (first) { 2981 // The first time through the loop, we just consume the root element of 2982 // the heap (the one with smallest distance). 2983 first = false; 2984 } else { 2985 // Previous iterations consumed the root element of the heap. 2986 // Pop root element off of the heap (sift down). 2987 heapSize -= 1; 2988 assert(heapSize > 0); 2989 2990 // Sift down. 2991 heap[0] = heap[heapSize]; 2992 for (uint32_t parentIndex = 0; ;) { 2993 uint32_t childIndex = parentIndex * 2 + 1; 2994 if (childIndex >= heapSize) { 2995 break; 2996 } 2997 2998 if (childIndex + 1 < heapSize 2999 && heap[childIndex + 1].distance < heap[childIndex].distance) { 3000 childIndex += 1; 3001 } 3002 3003 if (heap[parentIndex].distance <= heap[childIndex].distance) { 3004 break; 3005 } 3006 3007 swap(heap[parentIndex], heap[childIndex]); 3008 parentIndex = childIndex; 3009 } 3010 3011#if DEBUG_POINTER_ASSIGNMENT 3012 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize); 3013 for (size_t i = 0; i < heapSize; i++) { 3014 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", 3015 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, 3016 heap[i].distance); 3017 } 3018#endif 3019 } 3020 3021 uint32_t currentPointerIndex = heap[0].currentPointerIndex; 3022 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched 3023 3024 uint32_t lastPointerIndex = heap[0].lastPointerIndex; 3025 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched 3026 3027 matchedCurrentBits.markBit(currentPointerIndex); 3028 matchedLastBits.markBit(lastPointerIndex); 3029 3030 uint32_t id = mLastTouch.pointers[lastPointerIndex].id; 3031 mCurrentTouch.pointers[currentPointerIndex].id = id; 3032 mCurrentTouch.idToIndex[id] = currentPointerIndex; 3033 usedIdBits.markBit(id); 3034 3035#if DEBUG_POINTER_ASSIGNMENT 3036 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld", 3037 lastPointerIndex, currentPointerIndex, id, heap[0].distance); 3038#endif 3039 break; 3040 } 3041 } 3042 3043 // Assign fresh ids to new pointers. 3044 if (currentPointerCount > lastPointerCount) { 3045 for (uint32_t i = currentPointerCount - lastPointerCount; ;) { 3046 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit(); 3047 uint32_t id = usedIdBits.firstUnmarkedBit(); 3048 3049 mCurrentTouch.pointers[currentPointerIndex].id = id; 3050 mCurrentTouch.idToIndex[id] = currentPointerIndex; 3051 usedIdBits.markBit(id); 3052 3053#if DEBUG_POINTER_ASSIGNMENT 3054 LOGD("calculatePointerIds - assigned: cur=%d, id=%d", 3055 currentPointerIndex, id); 3056#endif 3057 3058 if (--i == 0) break; // done 3059 matchedCurrentBits.markBit(currentPointerIndex); 3060 } 3061 } 3062 3063 // Fix id bits. 3064 mCurrentTouch.idBits = usedIdBits; 3065 } 3066} 3067 3068/* Special hack for devices that have bad screen data: if one of the 3069 * points has moved more than a screen height from the last position, 3070 * then drop it. */ 3071bool TouchInputMapper::applyBadTouchFilter() { 3072 // This hack requires valid axis parameters. 3073 if (! mRawAxes.y.valid) { 3074 return false; 3075 } 3076 3077 uint32_t pointerCount = mCurrentTouch.pointerCount; 3078 3079 // Nothing to do if there are no points. 3080 if (pointerCount == 0) { 3081 return false; 3082 } 3083 3084 // Don't do anything if a finger is going down or up. We run 3085 // here before assigning pointer IDs, so there isn't a good 3086 // way to do per-finger matching. 3087 if (pointerCount != mLastTouch.pointerCount) { 3088 return false; 3089 } 3090 3091 // We consider a single movement across more than a 7/16 of 3092 // the long size of the screen to be bad. This was a magic value 3093 // determined by looking at the maximum distance it is feasible 3094 // to actually move in one sample. 3095 int32_t maxDeltaY = mRawAxes.y.getRange() * 7 / 16; 3096 3097 // XXX The original code in InputDevice.java included commented out 3098 // code for testing the X axis. Note that when we drop a point 3099 // we don't actually restore the old X either. Strange. 3100 // The old code also tries to track when bad points were previously 3101 // detected but it turns out that due to the placement of a "break" 3102 // at the end of the loop, we never set mDroppedBadPoint to true 3103 // so it is effectively dead code. 3104 // Need to figure out if the old code is busted or just overcomplicated 3105 // but working as intended. 3106 3107 // Look through all new points and see if any are farther than 3108 // acceptable from all previous points. 3109 for (uint32_t i = pointerCount; i-- > 0; ) { 3110 int32_t y = mCurrentTouch.pointers[i].y; 3111 int32_t closestY = INT_MAX; 3112 int32_t closestDeltaY = 0; 3113 3114#if DEBUG_HACKS 3115 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y); 3116#endif 3117 3118 for (uint32_t j = pointerCount; j-- > 0; ) { 3119 int32_t lastY = mLastTouch.pointers[j].y; 3120 int32_t deltaY = abs(y - lastY); 3121 3122#if DEBUG_HACKS 3123 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d", 3124 j, lastY, deltaY); 3125#endif 3126 3127 if (deltaY < maxDeltaY) { 3128 goto SkipSufficientlyClosePoint; 3129 } 3130 if (deltaY < closestDeltaY) { 3131 closestDeltaY = deltaY; 3132 closestY = lastY; 3133 } 3134 } 3135 3136 // Must not have found a close enough match. 3137#if DEBUG_HACKS 3138 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d", 3139 i, y, closestY, closestDeltaY, maxDeltaY); 3140#endif 3141 3142 mCurrentTouch.pointers[i].y = closestY; 3143 return true; // XXX original code only corrects one point 3144 3145 SkipSufficientlyClosePoint: ; 3146 } 3147 3148 // No change. 3149 return false; 3150} 3151 3152/* Special hack for devices that have bad screen data: drop points where 3153 * the coordinate value for one axis has jumped to the other pointer's location. 3154 */ 3155bool TouchInputMapper::applyJumpyTouchFilter() { 3156 // This hack requires valid axis parameters. 3157 if (! mRawAxes.y.valid) { 3158 return false; 3159 } 3160 3161 uint32_t pointerCount = mCurrentTouch.pointerCount; 3162 if (mLastTouch.pointerCount != pointerCount) { 3163#if DEBUG_HACKS 3164 LOGD("JumpyTouchFilter: Different pointer count %d -> %d", 3165 mLastTouch.pointerCount, pointerCount); 3166 for (uint32_t i = 0; i < pointerCount; i++) { 3167 LOGD(" Pointer %d (%d, %d)", i, 3168 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y); 3169 } 3170#endif 3171 3172 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) { 3173 if (mLastTouch.pointerCount == 1 && pointerCount == 2) { 3174 // Just drop the first few events going from 1 to 2 pointers. 3175 // They're bad often enough that they're not worth considering. 3176 mCurrentTouch.pointerCount = 1; 3177 mJumpyTouchFilter.jumpyPointsDropped += 1; 3178 3179#if DEBUG_HACKS 3180 LOGD("JumpyTouchFilter: Pointer 2 dropped"); 3181#endif 3182 return true; 3183 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) { 3184 // The event when we go from 2 -> 1 tends to be messed up too 3185 mCurrentTouch.pointerCount = 2; 3186 mCurrentTouch.pointers[0] = mLastTouch.pointers[0]; 3187 mCurrentTouch.pointers[1] = mLastTouch.pointers[1]; 3188 mJumpyTouchFilter.jumpyPointsDropped += 1; 3189 3190#if DEBUG_HACKS 3191 for (int32_t i = 0; i < 2; i++) { 3192 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i, 3193 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y); 3194 } 3195#endif 3196 return true; 3197 } 3198 } 3199 // Reset jumpy points dropped on other transitions or if limit exceeded. 3200 mJumpyTouchFilter.jumpyPointsDropped = 0; 3201 3202#if DEBUG_HACKS 3203 LOGD("JumpyTouchFilter: Transition - drop limit reset"); 3204#endif 3205 return false; 3206 } 3207 3208 // We have the same number of pointers as last time. 3209 // A 'jumpy' point is one where the coordinate value for one axis 3210 // has jumped to the other pointer's location. No need to do anything 3211 // else if we only have one pointer. 3212 if (pointerCount < 2) { 3213 return false; 3214 } 3215 3216 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) { 3217 int jumpyEpsilon = mRawAxes.y.getRange() / JUMPY_EPSILON_DIVISOR; 3218 3219 // We only replace the single worst jumpy point as characterized by pointer distance 3220 // in a single axis. 3221 int32_t badPointerIndex = -1; 3222 int32_t badPointerReplacementIndex = -1; 3223 int32_t badPointerDistance = INT_MIN; // distance to be corrected 3224 3225 for (uint32_t i = pointerCount; i-- > 0; ) { 3226 int32_t x = mCurrentTouch.pointers[i].x; 3227 int32_t y = mCurrentTouch.pointers[i].y; 3228 3229#if DEBUG_HACKS 3230 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y); 3231#endif 3232 3233 // Check if a touch point is too close to another's coordinates 3234 bool dropX = false, dropY = false; 3235 for (uint32_t j = 0; j < pointerCount; j++) { 3236 if (i == j) { 3237 continue; 3238 } 3239 3240 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) { 3241 dropX = true; 3242 break; 3243 } 3244 3245 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) { 3246 dropY = true; 3247 break; 3248 } 3249 } 3250 if (! dropX && ! dropY) { 3251 continue; // not jumpy 3252 } 3253 3254 // Find a replacement candidate by comparing with older points on the 3255 // complementary (non-jumpy) axis. 3256 int32_t distance = INT_MIN; // distance to be corrected 3257 int32_t replacementIndex = -1; 3258 3259 if (dropX) { 3260 // X looks too close. Find an older replacement point with a close Y. 3261 int32_t smallestDeltaY = INT_MAX; 3262 for (uint32_t j = 0; j < pointerCount; j++) { 3263 int32_t deltaY = abs(y - mLastTouch.pointers[j].y); 3264 if (deltaY < smallestDeltaY) { 3265 smallestDeltaY = deltaY; 3266 replacementIndex = j; 3267 } 3268 } 3269 distance = abs(x - mLastTouch.pointers[replacementIndex].x); 3270 } else { 3271 // Y looks too close. Find an older replacement point with a close X. 3272 int32_t smallestDeltaX = INT_MAX; 3273 for (uint32_t j = 0; j < pointerCount; j++) { 3274 int32_t deltaX = abs(x - mLastTouch.pointers[j].x); 3275 if (deltaX < smallestDeltaX) { 3276 smallestDeltaX = deltaX; 3277 replacementIndex = j; 3278 } 3279 } 3280 distance = abs(y - mLastTouch.pointers[replacementIndex].y); 3281 } 3282 3283 // If replacing this pointer would correct a worse error than the previous ones 3284 // considered, then use this replacement instead. 3285 if (distance > badPointerDistance) { 3286 badPointerIndex = i; 3287 badPointerReplacementIndex = replacementIndex; 3288 badPointerDistance = distance; 3289 } 3290 } 3291 3292 // Correct the jumpy pointer if one was found. 3293 if (badPointerIndex >= 0) { 3294#if DEBUG_HACKS 3295 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)", 3296 badPointerIndex, 3297 mLastTouch.pointers[badPointerReplacementIndex].x, 3298 mLastTouch.pointers[badPointerReplacementIndex].y); 3299#endif 3300 3301 mCurrentTouch.pointers[badPointerIndex].x = 3302 mLastTouch.pointers[badPointerReplacementIndex].x; 3303 mCurrentTouch.pointers[badPointerIndex].y = 3304 mLastTouch.pointers[badPointerReplacementIndex].y; 3305 mJumpyTouchFilter.jumpyPointsDropped += 1; 3306 return true; 3307 } 3308 } 3309 3310 mJumpyTouchFilter.jumpyPointsDropped = 0; 3311 return false; 3312} 3313 3314/* Special hack for devices that have bad screen data: aggregate and 3315 * compute averages of the coordinate data, to reduce the amount of 3316 * jitter seen by applications. */ 3317void TouchInputMapper::applyAveragingTouchFilter() { 3318 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) { 3319 uint32_t id = mCurrentTouch.pointers[currentIndex].id; 3320 int32_t x = mCurrentTouch.pointers[currentIndex].x; 3321 int32_t y = mCurrentTouch.pointers[currentIndex].y; 3322 int32_t pressure; 3323 switch (mCalibration.pressureSource) { 3324 case Calibration::PRESSURE_SOURCE_PRESSURE: 3325 pressure = mCurrentTouch.pointers[currentIndex].pressure; 3326 break; 3327 case Calibration::PRESSURE_SOURCE_TOUCH: 3328 pressure = mCurrentTouch.pointers[currentIndex].touchMajor; 3329 break; 3330 default: 3331 pressure = 1; 3332 break; 3333 } 3334 3335 if (mLastTouch.idBits.hasBit(id)) { 3336 // Pointer was down before and is still down now. 3337 // Compute average over history trace. 3338 uint32_t start = mAveragingTouchFilter.historyStart[id]; 3339 uint32_t end = mAveragingTouchFilter.historyEnd[id]; 3340 3341 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x; 3342 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y; 3343 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY); 3344 3345#if DEBUG_HACKS 3346 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld", 3347 id, distance); 3348#endif 3349 3350 if (distance < AVERAGING_DISTANCE_LIMIT) { 3351 // Increment end index in preparation for recording new historical data. 3352 end += 1; 3353 if (end > AVERAGING_HISTORY_SIZE) { 3354 end = 0; 3355 } 3356 3357 // If the end index has looped back to the start index then we have filled 3358 // the historical trace up to the desired size so we drop the historical 3359 // data at the start of the trace. 3360 if (end == start) { 3361 start += 1; 3362 if (start > AVERAGING_HISTORY_SIZE) { 3363 start = 0; 3364 } 3365 } 3366 3367 // Add the raw data to the historical trace. 3368 mAveragingTouchFilter.historyStart[id] = start; 3369 mAveragingTouchFilter.historyEnd[id] = end; 3370 mAveragingTouchFilter.historyData[end].pointers[id].x = x; 3371 mAveragingTouchFilter.historyData[end].pointers[id].y = y; 3372 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure; 3373 3374 // Average over all historical positions in the trace by total pressure. 3375 int32_t averagedX = 0; 3376 int32_t averagedY = 0; 3377 int32_t totalPressure = 0; 3378 for (;;) { 3379 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x; 3380 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y; 3381 int32_t historicalPressure = mAveragingTouchFilter.historyData[start] 3382 .pointers[id].pressure; 3383 3384 averagedX += historicalX * historicalPressure; 3385 averagedY += historicalY * historicalPressure; 3386 totalPressure += historicalPressure; 3387 3388 if (start == end) { 3389 break; 3390 } 3391 3392 start += 1; 3393 if (start > AVERAGING_HISTORY_SIZE) { 3394 start = 0; 3395 } 3396 } 3397 3398 if (totalPressure != 0) { 3399 averagedX /= totalPressure; 3400 averagedY /= totalPressure; 3401 3402#if DEBUG_HACKS 3403 LOGD("AveragingTouchFilter: Pointer id %d - " 3404 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure, 3405 averagedX, averagedY); 3406#endif 3407 3408 mCurrentTouch.pointers[currentIndex].x = averagedX; 3409 mCurrentTouch.pointers[currentIndex].y = averagedY; 3410 } 3411 } else { 3412#if DEBUG_HACKS 3413 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id); 3414#endif 3415 } 3416 } else { 3417#if DEBUG_HACKS 3418 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id); 3419#endif 3420 } 3421 3422 // Reset pointer history. 3423 mAveragingTouchFilter.historyStart[id] = 0; 3424 mAveragingTouchFilter.historyEnd[id] = 0; 3425 mAveragingTouchFilter.historyData[0].pointers[id].x = x; 3426 mAveragingTouchFilter.historyData[0].pointers[id].y = y; 3427 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure; 3428 } 3429} 3430 3431int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 3432 { // acquire lock 3433 AutoMutex _l(mLock); 3434 3435 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) { 3436 return AKEY_STATE_VIRTUAL; 3437 } 3438 3439 size_t numVirtualKeys = mLocked.virtualKeys.size(); 3440 for (size_t i = 0; i < numVirtualKeys; i++) { 3441 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 3442 if (virtualKey.keyCode == keyCode) { 3443 return AKEY_STATE_UP; 3444 } 3445 } 3446 } // release lock 3447 3448 return AKEY_STATE_UNKNOWN; 3449} 3450 3451int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 3452 { // acquire lock 3453 AutoMutex _l(mLock); 3454 3455 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) { 3456 return AKEY_STATE_VIRTUAL; 3457 } 3458 3459 size_t numVirtualKeys = mLocked.virtualKeys.size(); 3460 for (size_t i = 0; i < numVirtualKeys; i++) { 3461 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 3462 if (virtualKey.scanCode == scanCode) { 3463 return AKEY_STATE_UP; 3464 } 3465 } 3466 } // release lock 3467 3468 return AKEY_STATE_UNKNOWN; 3469} 3470 3471bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 3472 const int32_t* keyCodes, uint8_t* outFlags) { 3473 { // acquire lock 3474 AutoMutex _l(mLock); 3475 3476 size_t numVirtualKeys = mLocked.virtualKeys.size(); 3477 for (size_t i = 0; i < numVirtualKeys; i++) { 3478 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 3479 3480 for (size_t i = 0; i < numCodes; i++) { 3481 if (virtualKey.keyCode == keyCodes[i]) { 3482 outFlags[i] = 1; 3483 } 3484 } 3485 } 3486 } // release lock 3487 3488 return true; 3489} 3490 3491 3492// --- SingleTouchInputMapper --- 3493 3494SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) : 3495 TouchInputMapper(device) { 3496 initialize(); 3497} 3498 3499SingleTouchInputMapper::~SingleTouchInputMapper() { 3500} 3501 3502void SingleTouchInputMapper::initialize() { 3503 mAccumulator.clear(); 3504 3505 mDown = false; 3506 mX = 0; 3507 mY = 0; 3508 mPressure = 0; // default to 0 for devices that don't report pressure 3509 mToolWidth = 0; // default to 0 for devices that don't report tool width 3510} 3511 3512void SingleTouchInputMapper::reset() { 3513 TouchInputMapper::reset(); 3514 3515 initialize(); 3516 } 3517 3518void SingleTouchInputMapper::process(const RawEvent* rawEvent) { 3519 switch (rawEvent->type) { 3520 case EV_KEY: 3521 switch (rawEvent->scanCode) { 3522 case BTN_TOUCH: 3523 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH; 3524 mAccumulator.btnTouch = rawEvent->value != 0; 3525 // Don't sync immediately. Wait until the next SYN_REPORT since we might 3526 // not have received valid position information yet. This logic assumes that 3527 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet. 3528 break; 3529 } 3530 break; 3531 3532 case EV_ABS: 3533 switch (rawEvent->scanCode) { 3534 case ABS_X: 3535 mAccumulator.fields |= Accumulator::FIELD_ABS_X; 3536 mAccumulator.absX = rawEvent->value; 3537 break; 3538 case ABS_Y: 3539 mAccumulator.fields |= Accumulator::FIELD_ABS_Y; 3540 mAccumulator.absY = rawEvent->value; 3541 break; 3542 case ABS_PRESSURE: 3543 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE; 3544 mAccumulator.absPressure = rawEvent->value; 3545 break; 3546 case ABS_TOOL_WIDTH: 3547 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH; 3548 mAccumulator.absToolWidth = rawEvent->value; 3549 break; 3550 } 3551 break; 3552 3553 case EV_SYN: 3554 switch (rawEvent->scanCode) { 3555 case SYN_REPORT: 3556 sync(rawEvent->when); 3557 break; 3558 } 3559 break; 3560 } 3561} 3562 3563void SingleTouchInputMapper::sync(nsecs_t when) { 3564 uint32_t fields = mAccumulator.fields; 3565 if (fields == 0) { 3566 return; // no new state changes, so nothing to do 3567 } 3568 3569 if (fields & Accumulator::FIELD_BTN_TOUCH) { 3570 mDown = mAccumulator.btnTouch; 3571 } 3572 3573 if (fields & Accumulator::FIELD_ABS_X) { 3574 mX = mAccumulator.absX; 3575 } 3576 3577 if (fields & Accumulator::FIELD_ABS_Y) { 3578 mY = mAccumulator.absY; 3579 } 3580 3581 if (fields & Accumulator::FIELD_ABS_PRESSURE) { 3582 mPressure = mAccumulator.absPressure; 3583 } 3584 3585 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) { 3586 mToolWidth = mAccumulator.absToolWidth; 3587 } 3588 3589 mCurrentTouch.clear(); 3590 3591 if (mDown) { 3592 mCurrentTouch.pointerCount = 1; 3593 mCurrentTouch.pointers[0].id = 0; 3594 mCurrentTouch.pointers[0].x = mX; 3595 mCurrentTouch.pointers[0].y = mY; 3596 mCurrentTouch.pointers[0].pressure = mPressure; 3597 mCurrentTouch.pointers[0].touchMajor = 0; 3598 mCurrentTouch.pointers[0].touchMinor = 0; 3599 mCurrentTouch.pointers[0].toolMajor = mToolWidth; 3600 mCurrentTouch.pointers[0].toolMinor = mToolWidth; 3601 mCurrentTouch.pointers[0].orientation = 0; 3602 mCurrentTouch.idToIndex[0] = 0; 3603 mCurrentTouch.idBits.markBit(0); 3604 } 3605 3606 syncTouch(when, true); 3607 3608 mAccumulator.clear(); 3609} 3610 3611void SingleTouchInputMapper::configureRawAxes() { 3612 TouchInputMapper::configureRawAxes(); 3613 3614 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x); 3615 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y); 3616 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure); 3617 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor); 3618} 3619 3620 3621// --- MultiTouchInputMapper --- 3622 3623MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) : 3624 TouchInputMapper(device) { 3625 initialize(); 3626} 3627 3628MultiTouchInputMapper::~MultiTouchInputMapper() { 3629} 3630 3631void MultiTouchInputMapper::initialize() { 3632 mAccumulator.clear(); 3633} 3634 3635void MultiTouchInputMapper::reset() { 3636 TouchInputMapper::reset(); 3637 3638 initialize(); 3639} 3640 3641void MultiTouchInputMapper::process(const RawEvent* rawEvent) { 3642 switch (rawEvent->type) { 3643 case EV_ABS: { 3644 uint32_t pointerIndex = mAccumulator.pointerCount; 3645 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex]; 3646 3647 switch (rawEvent->scanCode) { 3648 case ABS_MT_POSITION_X: 3649 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X; 3650 pointer->absMTPositionX = rawEvent->value; 3651 break; 3652 case ABS_MT_POSITION_Y: 3653 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y; 3654 pointer->absMTPositionY = rawEvent->value; 3655 break; 3656 case ABS_MT_TOUCH_MAJOR: 3657 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR; 3658 pointer->absMTTouchMajor = rawEvent->value; 3659 break; 3660 case ABS_MT_TOUCH_MINOR: 3661 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR; 3662 pointer->absMTTouchMinor = rawEvent->value; 3663 break; 3664 case ABS_MT_WIDTH_MAJOR: 3665 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR; 3666 pointer->absMTWidthMajor = rawEvent->value; 3667 break; 3668 case ABS_MT_WIDTH_MINOR: 3669 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR; 3670 pointer->absMTWidthMinor = rawEvent->value; 3671 break; 3672 case ABS_MT_ORIENTATION: 3673 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION; 3674 pointer->absMTOrientation = rawEvent->value; 3675 break; 3676 case ABS_MT_TRACKING_ID: 3677 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID; 3678 pointer->absMTTrackingId = rawEvent->value; 3679 break; 3680 case ABS_MT_PRESSURE: 3681 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE; 3682 pointer->absMTPressure = rawEvent->value; 3683 break; 3684 } 3685 break; 3686 } 3687 3688 case EV_SYN: 3689 switch (rawEvent->scanCode) { 3690 case SYN_MT_REPORT: { 3691 // MultiTouch Sync: The driver has returned all data for *one* of the pointers. 3692 uint32_t pointerIndex = mAccumulator.pointerCount; 3693 3694 if (mAccumulator.pointers[pointerIndex].fields) { 3695 if (pointerIndex == MAX_POINTERS) { 3696 LOGW("MultiTouch device driver returned more than maximum of %d pointers.", 3697 MAX_POINTERS); 3698 } else { 3699 pointerIndex += 1; 3700 mAccumulator.pointerCount = pointerIndex; 3701 } 3702 } 3703 3704 mAccumulator.pointers[pointerIndex].clear(); 3705 break; 3706 } 3707 3708 case SYN_REPORT: 3709 sync(rawEvent->when); 3710 break; 3711 } 3712 break; 3713 } 3714} 3715 3716void MultiTouchInputMapper::sync(nsecs_t when) { 3717 static const uint32_t REQUIRED_FIELDS = 3718 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y; 3719 3720 uint32_t inCount = mAccumulator.pointerCount; 3721 uint32_t outCount = 0; 3722 bool havePointerIds = true; 3723 3724 mCurrentTouch.clear(); 3725 3726 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) { 3727 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex]; 3728 uint32_t fields = inPointer.fields; 3729 3730 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) { 3731 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up. 3732 // Drop this finger. 3733 continue; 3734 } 3735 3736 PointerData& outPointer = mCurrentTouch.pointers[outCount]; 3737 outPointer.x = inPointer.absMTPositionX; 3738 outPointer.y = inPointer.absMTPositionY; 3739 3740 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) { 3741 if (inPointer.absMTPressure <= 0) { 3742 // Some devices send sync packets with X / Y but with a 0 pressure to indicate 3743 // a pointer going up. Drop this finger. 3744 continue; 3745 } 3746 outPointer.pressure = inPointer.absMTPressure; 3747 } else { 3748 // Default pressure to 0 if absent. 3749 outPointer.pressure = 0; 3750 } 3751 3752 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) { 3753 if (inPointer.absMTTouchMajor <= 0) { 3754 // Some devices send sync packets with X / Y but with a 0 touch major to indicate 3755 // a pointer going up. Drop this finger. 3756 continue; 3757 } 3758 outPointer.touchMajor = inPointer.absMTTouchMajor; 3759 } else { 3760 // Default touch area to 0 if absent. 3761 outPointer.touchMajor = 0; 3762 } 3763 3764 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) { 3765 outPointer.touchMinor = inPointer.absMTTouchMinor; 3766 } else { 3767 // Assume touch area is circular. 3768 outPointer.touchMinor = outPointer.touchMajor; 3769 } 3770 3771 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) { 3772 outPointer.toolMajor = inPointer.absMTWidthMajor; 3773 } else { 3774 // Default tool area to 0 if absent. 3775 outPointer.toolMajor = 0; 3776 } 3777 3778 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) { 3779 outPointer.toolMinor = inPointer.absMTWidthMinor; 3780 } else { 3781 // Assume tool area is circular. 3782 outPointer.toolMinor = outPointer.toolMajor; 3783 } 3784 3785 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) { 3786 outPointer.orientation = inPointer.absMTOrientation; 3787 } else { 3788 // Default orientation to vertical if absent. 3789 outPointer.orientation = 0; 3790 } 3791 3792 // Assign pointer id using tracking id if available. 3793 if (havePointerIds) { 3794 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) { 3795 uint32_t id = uint32_t(inPointer.absMTTrackingId); 3796 3797 if (id > MAX_POINTER_ID) { 3798#if DEBUG_POINTERS 3799 LOGD("Pointers: Ignoring driver provided pointer id %d because " 3800 "it is larger than max supported id %d", 3801 id, MAX_POINTER_ID); 3802#endif 3803 havePointerIds = false; 3804 } 3805 else { 3806 outPointer.id = id; 3807 mCurrentTouch.idToIndex[id] = outCount; 3808 mCurrentTouch.idBits.markBit(id); 3809 } 3810 } else { 3811 havePointerIds = false; 3812 } 3813 } 3814 3815 outCount += 1; 3816 } 3817 3818 mCurrentTouch.pointerCount = outCount; 3819 3820 syncTouch(when, havePointerIds); 3821 3822 mAccumulator.clear(); 3823} 3824 3825void MultiTouchInputMapper::configureRawAxes() { 3826 TouchInputMapper::configureRawAxes(); 3827 3828 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x); 3829 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y); 3830 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor); 3831 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor); 3832 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor); 3833 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor); 3834 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation); 3835 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure); 3836} 3837 3838 3839// --- JoystickInputMapper --- 3840 3841JoystickInputMapper::JoystickInputMapper(InputDevice* device) : 3842 InputMapper(device) { 3843} 3844 3845JoystickInputMapper::~JoystickInputMapper() { 3846} 3847 3848uint32_t JoystickInputMapper::getSources() { 3849 return AINPUT_SOURCE_JOYSTICK; 3850} 3851 3852void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 3853 InputMapper::populateDeviceInfo(info); 3854 3855 for (size_t i = 0; i < mAxes.size(); i++) { 3856 const Axis& axis = mAxes.valueAt(i); 3857 info->addMotionRange(axis.axisInfo.axis, axis.min, axis.max, axis.flat, axis.fuzz); 3858 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 3859 info->addMotionRange(axis.axisInfo.highAxis, axis.min, axis.max, axis.flat, axis.fuzz); 3860 } 3861 } 3862} 3863 3864void JoystickInputMapper::dump(String8& dump) { 3865 dump.append(INDENT2 "Joystick Input Mapper:\n"); 3866 3867 dump.append(INDENT3 "Axes:\n"); 3868 size_t numAxes = mAxes.size(); 3869 for (size_t i = 0; i < numAxes; i++) { 3870 const Axis& axis = mAxes.valueAt(i); 3871 const char* label = getAxisLabel(axis.axisInfo.axis); 3872 if (label) { 3873 dump.appendFormat(INDENT4 "%s", label); 3874 } else { 3875 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis); 3876 } 3877 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 3878 label = getAxisLabel(axis.axisInfo.highAxis); 3879 if (label) { 3880 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue); 3881 } else { 3882 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis, 3883 axis.axisInfo.splitValue); 3884 } 3885 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) { 3886 dump.append(" (invert)"); 3887 } 3888 3889 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n", 3890 axis.min, axis.max, axis.flat, axis.fuzz); 3891 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, " 3892 "highScale=%0.5f, highOffset=%0.5f\n", 3893 axis.scale, axis.offset, axis.highScale, axis.highOffset); 3894 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n", 3895 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue, 3896 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz); 3897 } 3898} 3899 3900void JoystickInputMapper::configure() { 3901 InputMapper::configure(); 3902 3903 // Collect all axes. 3904 for (int32_t abs = 0; abs <= ABS_MAX; abs++) { 3905 RawAbsoluteAxisInfo rawAxisInfo; 3906 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo); 3907 if (rawAxisInfo.valid) { 3908 // Map axis. 3909 AxisInfo axisInfo; 3910 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo); 3911 if (!explicitlyMapped) { 3912 // Axis is not explicitly mapped, will choose a generic axis later. 3913 axisInfo.mode = AxisInfo::MODE_NORMAL; 3914 axisInfo.axis = -1; 3915 } 3916 3917 // Apply flat override. 3918 int32_t rawFlat = axisInfo.flatOverride < 0 3919 ? rawAxisInfo.flat : axisInfo.flatOverride; 3920 3921 // Calculate scaling factors and limits. 3922 Axis axis; 3923 if (axisInfo.mode == AxisInfo::MODE_SPLIT) { 3924 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue); 3925 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue); 3926 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 3927 scale, 0.0f, highScale, 0.0f, 3928 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 3929 } else if (isCenteredAxis(axisInfo.axis)) { 3930 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); 3931 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale; 3932 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 3933 scale, offset, scale, offset, 3934 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 3935 } else { 3936 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); 3937 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 3938 scale, 0.0f, scale, 0.0f, 3939 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 3940 } 3941 3942 // To eliminate noise while the joystick is at rest, filter out small variations 3943 // in axis values up front. 3944 axis.filter = axis.flat * 0.25f; 3945 3946 mAxes.add(abs, axis); 3947 } 3948 } 3949 3950 // If there are too many axes, start dropping them. 3951 // Prefer to keep explicitly mapped axes. 3952 if (mAxes.size() > PointerCoords::MAX_AXES) { 3953 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.", 3954 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES); 3955 pruneAxes(true); 3956 pruneAxes(false); 3957 } 3958 3959 // Assign generic axis ids to remaining axes. 3960 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1; 3961 size_t numAxes = mAxes.size(); 3962 for (size_t i = 0; i < numAxes; i++) { 3963 Axis& axis = mAxes.editValueAt(i); 3964 if (axis.axisInfo.axis < 0) { 3965 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 3966 && haveAxis(nextGenericAxisId)) { 3967 nextGenericAxisId += 1; 3968 } 3969 3970 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) { 3971 axis.axisInfo.axis = nextGenericAxisId; 3972 nextGenericAxisId += 1; 3973 } else { 3974 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids " 3975 "have already been assigned to other axes.", 3976 getDeviceName().string(), mAxes.keyAt(i)); 3977 mAxes.removeItemsAt(i--); 3978 numAxes -= 1; 3979 } 3980 } 3981 } 3982} 3983 3984bool JoystickInputMapper::haveAxis(int32_t axisId) { 3985 size_t numAxes = mAxes.size(); 3986 for (size_t i = 0; i < numAxes; i++) { 3987 const Axis& axis = mAxes.valueAt(i); 3988 if (axis.axisInfo.axis == axisId 3989 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT 3990 && axis.axisInfo.highAxis == axisId)) { 3991 return true; 3992 } 3993 } 3994 return false; 3995} 3996 3997void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) { 3998 size_t i = mAxes.size(); 3999 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) { 4000 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) { 4001 continue; 4002 } 4003 LOGI("Discarding joystick '%s' axis %d because there are too many axes.", 4004 getDeviceName().string(), mAxes.keyAt(i)); 4005 mAxes.removeItemsAt(i); 4006 } 4007} 4008 4009bool JoystickInputMapper::isCenteredAxis(int32_t axis) { 4010 switch (axis) { 4011 case AMOTION_EVENT_AXIS_X: 4012 case AMOTION_EVENT_AXIS_Y: 4013 case AMOTION_EVENT_AXIS_Z: 4014 case AMOTION_EVENT_AXIS_RX: 4015 case AMOTION_EVENT_AXIS_RY: 4016 case AMOTION_EVENT_AXIS_RZ: 4017 case AMOTION_EVENT_AXIS_HAT_X: 4018 case AMOTION_EVENT_AXIS_HAT_Y: 4019 case AMOTION_EVENT_AXIS_ORIENTATION: 4020 case AMOTION_EVENT_AXIS_RUDDER: 4021 case AMOTION_EVENT_AXIS_WHEEL: 4022 return true; 4023 default: 4024 return false; 4025 } 4026} 4027 4028void JoystickInputMapper::reset() { 4029 // Recenter all axes. 4030 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 4031 4032 size_t numAxes = mAxes.size(); 4033 for (size_t i = 0; i < numAxes; i++) { 4034 Axis& axis = mAxes.editValueAt(i); 4035 axis.resetValue(); 4036 } 4037 4038 sync(when, true /*force*/); 4039 4040 InputMapper::reset(); 4041} 4042 4043void JoystickInputMapper::process(const RawEvent* rawEvent) { 4044 switch (rawEvent->type) { 4045 case EV_ABS: { 4046 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode); 4047 if (index >= 0) { 4048 Axis& axis = mAxes.editValueAt(index); 4049 float newValue, highNewValue; 4050 switch (axis.axisInfo.mode) { 4051 case AxisInfo::MODE_INVERT: 4052 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) 4053 * axis.scale + axis.offset; 4054 highNewValue = 0.0f; 4055 break; 4056 case AxisInfo::MODE_SPLIT: 4057 if (rawEvent->value < axis.axisInfo.splitValue) { 4058 newValue = (axis.axisInfo.splitValue - rawEvent->value) 4059 * axis.scale + axis.offset; 4060 highNewValue = 0.0f; 4061 } else if (rawEvent->value > axis.axisInfo.splitValue) { 4062 newValue = 0.0f; 4063 highNewValue = (rawEvent->value - axis.axisInfo.splitValue) 4064 * axis.highScale + axis.highOffset; 4065 } else { 4066 newValue = 0.0f; 4067 highNewValue = 0.0f; 4068 } 4069 break; 4070 default: 4071 newValue = rawEvent->value * axis.scale + axis.offset; 4072 highNewValue = 0.0f; 4073 break; 4074 } 4075 axis.newValue = newValue; 4076 axis.highNewValue = highNewValue; 4077 } 4078 break; 4079 } 4080 4081 case EV_SYN: 4082 switch (rawEvent->scanCode) { 4083 case SYN_REPORT: 4084 sync(rawEvent->when, false /*force*/); 4085 break; 4086 } 4087 break; 4088 } 4089} 4090 4091void JoystickInputMapper::sync(nsecs_t when, bool force) { 4092 if (!filterAxes(force)) { 4093 return; 4094 } 4095 4096 int32_t metaState = mContext->getGlobalMetaState(); 4097 4098 PointerCoords pointerCoords; 4099 pointerCoords.clear(); 4100 4101 size_t numAxes = mAxes.size(); 4102 for (size_t i = 0; i < numAxes; i++) { 4103 const Axis& axis = mAxes.valueAt(i); 4104 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue); 4105 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 4106 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue); 4107 } 4108 } 4109 4110 // Moving a joystick axis should not wake the devide because joysticks can 4111 // be fairly noisy even when not in use. On the other hand, pushing a gamepad 4112 // button will likely wake the device. 4113 // TODO: Use the input device configuration to control this behavior more finely. 4114 uint32_t policyFlags = 0; 4115 4116 int32_t pointerId = 0; 4117 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags, 4118 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 4119 1, &pointerId, &pointerCoords, 0, 0, 0); 4120} 4121 4122bool JoystickInputMapper::filterAxes(bool force) { 4123 bool atLeastOneSignificantChange = force; 4124 size_t numAxes = mAxes.size(); 4125 for (size_t i = 0; i < numAxes; i++) { 4126 Axis& axis = mAxes.editValueAt(i); 4127 if (force || hasValueChangedSignificantly(axis.filter, 4128 axis.newValue, axis.currentValue, axis.min, axis.max)) { 4129 axis.currentValue = axis.newValue; 4130 atLeastOneSignificantChange = true; 4131 } 4132 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 4133 if (force || hasValueChangedSignificantly(axis.filter, 4134 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) { 4135 axis.highCurrentValue = axis.highNewValue; 4136 atLeastOneSignificantChange = true; 4137 } 4138 } 4139 } 4140 return atLeastOneSignificantChange; 4141} 4142 4143bool JoystickInputMapper::hasValueChangedSignificantly( 4144 float filter, float newValue, float currentValue, float min, float max) { 4145 if (newValue != currentValue) { 4146 // Filter out small changes in value unless the value is converging on the axis 4147 // bounds or center point. This is intended to reduce the amount of information 4148 // sent to applications by particularly noisy joysticks (such as PS3). 4149 if (fabs(newValue - currentValue) > filter 4150 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) 4151 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) 4152 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) { 4153 return true; 4154 } 4155 } 4156 return false; 4157} 4158 4159bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange( 4160 float filter, float newValue, float currentValue, float thresholdValue) { 4161 float newDistance = fabs(newValue - thresholdValue); 4162 if (newDistance < filter) { 4163 float oldDistance = fabs(currentValue - thresholdValue); 4164 if (newDistance < oldDistance) { 4165 return true; 4166 } 4167 } 4168 return false; 4169} 4170 4171} // namespace android 4172