InputReader.cpp revision aa3855d5836d2a2d83baafdf6e40caf90d3dad1c
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "InputReader" 18 19//#define LOG_NDEBUG 0 20 21// Log debug messages for each raw event received from the EventHub. 22#define DEBUG_RAW_EVENTS 0 23 24// Log debug messages about touch screen filtering hacks. 25#define DEBUG_HACKS 0 26 27// Log debug messages about virtual key processing. 28#define DEBUG_VIRTUAL_KEYS 0 29 30// Log debug messages about pointers. 31#define DEBUG_POINTERS 0 32 33// Log debug messages about pointer assignment calculations. 34#define DEBUG_POINTER_ASSIGNMENT 0 35 36// Log debug messages about gesture detection. 37#define DEBUG_GESTURES 0 38 39 40#include "InputReader.h" 41 42#include <cutils/log.h> 43#include <ui/Keyboard.h> 44#include <ui/VirtualKeyMap.h> 45 46#include <stddef.h> 47#include <stdlib.h> 48#include <unistd.h> 49#include <errno.h> 50#include <limits.h> 51#include <math.h> 52 53#define INDENT " " 54#define INDENT2 " " 55#define INDENT3 " " 56#define INDENT4 " " 57 58namespace android { 59 60// --- Constants --- 61 62// Quiet time between certain gesture transitions. 63// Time to allow for all fingers or buttons to settle into a stable state before 64// starting a new gesture. 65static const nsecs_t QUIET_INTERVAL = 100 * 1000000; // 100 ms 66 67// The minimum speed that a pointer must travel for us to consider switching the active 68// touch pointer to it during a drag. This threshold is set to avoid switching due 69// to noise from a finger resting on the touch pad (perhaps just pressing it down). 70static const float DRAG_MIN_SWITCH_SPEED = 50.0f; // pixels per second 71 72// Tap gesture delay time. 73// The time between down and up must be less than this to be considered a tap. 74static const nsecs_t TAP_INTERVAL = 100 * 1000000; // 100 ms 75 76// The distance in pixels that the pointer is allowed to move from initial down 77// to up and still be called a tap. 78static const float TAP_SLOP = 5.0f; // 5 pixels 79 80// The transition from INDETERMINATE_MULTITOUCH to SWIPE or FREEFORM gesture mode is made when 81// all of the pointers have traveled this number of pixels from the start point. 82static const float MULTITOUCH_MIN_TRAVEL = 5.0f; 83 84// The transition from INDETERMINATE_MULTITOUCH to SWIPE gesture mode can only occur when the 85// cosine of the angle between the two vectors is greater than or equal to than this value 86// which indicates that the vectors are oriented in the same direction. 87// When the vectors are oriented in the exactly same direction, the cosine is 1.0. 88// (In exactly opposite directions, the cosine is -1.0.) 89static const float SWIPE_TRANSITION_ANGLE_COSINE = 0.5f; // cosine of 45 degrees 90 91 92// --- Static Functions --- 93 94template<typename T> 95inline static T abs(const T& value) { 96 return value < 0 ? - value : value; 97} 98 99template<typename T> 100inline static T min(const T& a, const T& b) { 101 return a < b ? a : b; 102} 103 104template<typename T> 105inline static void swap(T& a, T& b) { 106 T temp = a; 107 a = b; 108 b = temp; 109} 110 111inline static float avg(float x, float y) { 112 return (x + y) / 2; 113} 114 115inline static float pythag(float x, float y) { 116 return sqrtf(x * x + y * y); 117} 118 119inline static int32_t distanceSquared(int32_t x1, int32_t y1, int32_t x2, int32_t y2) { 120 int32_t dx = x1 - x2; 121 int32_t dy = y1 - y2; 122 return dx * dx + dy * dy; 123} 124 125inline static int32_t signExtendNybble(int32_t value) { 126 return value >= 8 ? value - 16 : value; 127} 128 129static inline const char* toString(bool value) { 130 return value ? "true" : "false"; 131} 132 133static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation, 134 const int32_t map[][4], size_t mapSize) { 135 if (orientation != DISPLAY_ORIENTATION_0) { 136 for (size_t i = 0; i < mapSize; i++) { 137 if (value == map[i][0]) { 138 return map[i][orientation]; 139 } 140 } 141 } 142 return value; 143} 144 145static const int32_t keyCodeRotationMap[][4] = { 146 // key codes enumerated counter-clockwise with the original (unrotated) key first 147 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation 148 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT }, 149 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN }, 150 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT }, 151 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP }, 152}; 153static const size_t keyCodeRotationMapSize = 154 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]); 155 156int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) { 157 return rotateValueUsingRotationMap(keyCode, orientation, 158 keyCodeRotationMap, keyCodeRotationMapSize); 159} 160 161static const int32_t edgeFlagRotationMap[][4] = { 162 // edge flags enumerated counter-clockwise with the original (unrotated) edge flag first 163 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation 164 { AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT, 165 AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT }, 166 { AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP, 167 AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM }, 168 { AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT, 169 AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT }, 170 { AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM, 171 AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP }, 172}; 173static const size_t edgeFlagRotationMapSize = 174 sizeof(edgeFlagRotationMap) / sizeof(edgeFlagRotationMap[0]); 175 176static int32_t rotateEdgeFlag(int32_t edgeFlag, int32_t orientation) { 177 return rotateValueUsingRotationMap(edgeFlag, orientation, 178 edgeFlagRotationMap, edgeFlagRotationMapSize); 179} 180 181static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) { 182 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0; 183} 184 185static uint32_t getButtonStateForScanCode(int32_t scanCode) { 186 // Currently all buttons are mapped to the primary button. 187 switch (scanCode) { 188 case BTN_LEFT: 189 case BTN_RIGHT: 190 case BTN_MIDDLE: 191 case BTN_SIDE: 192 case BTN_EXTRA: 193 case BTN_FORWARD: 194 case BTN_BACK: 195 case BTN_TASK: 196 return BUTTON_STATE_PRIMARY; 197 default: 198 return 0; 199 } 200} 201 202// Returns true if the pointer should be reported as being down given the specified 203// button states. 204static bool isPointerDown(uint32_t buttonState) { 205 return buttonState & BUTTON_STATE_PRIMARY; 206} 207 208static int32_t calculateEdgeFlagsUsingPointerBounds( 209 const sp<PointerControllerInterface>& pointerController, float x, float y) { 210 int32_t edgeFlags = 0; 211 float minX, minY, maxX, maxY; 212 if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) { 213 if (x <= minX) { 214 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_LEFT; 215 } else if (x >= maxX) { 216 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_RIGHT; 217 } 218 if (y <= minY) { 219 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_TOP; 220 } else if (y >= maxY) { 221 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_BOTTOM; 222 } 223 } 224 return edgeFlags; 225} 226 227 228// --- InputReader --- 229 230InputReader::InputReader(const sp<EventHubInterface>& eventHub, 231 const sp<InputReaderPolicyInterface>& policy, 232 const sp<InputDispatcherInterface>& dispatcher) : 233 mEventHub(eventHub), mPolicy(policy), mDispatcher(dispatcher), 234 mGlobalMetaState(0), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX) { 235 configureExcludedDevices(); 236 updateGlobalMetaState(); 237 updateInputConfiguration(); 238} 239 240InputReader::~InputReader() { 241 for (size_t i = 0; i < mDevices.size(); i++) { 242 delete mDevices.valueAt(i); 243 } 244} 245 246void InputReader::loopOnce() { 247 int32_t timeoutMillis = -1; 248 if (mNextTimeout != LLONG_MAX) { 249 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); 250 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout); 251 } 252 253 RawEvent rawEvent; 254 if (mEventHub->getEvent(timeoutMillis, &rawEvent)) { 255#if DEBUG_RAW_EVENTS 256 LOGD("Input event: device=%d type=0x%04x scancode=0x%04x keycode=0x%04x value=0x%04x", 257 rawEvent.deviceId, rawEvent.type, rawEvent.scanCode, rawEvent.keyCode, 258 rawEvent.value); 259#endif 260 process(&rawEvent); 261 } else { 262 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); 263#if DEBUG_RAW_EVENTS 264 LOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f); 265#endif 266 mNextTimeout = LLONG_MAX; 267 timeoutExpired(now); 268 } 269} 270 271void InputReader::process(const RawEvent* rawEvent) { 272 switch (rawEvent->type) { 273 case EventHubInterface::DEVICE_ADDED: 274 addDevice(rawEvent->deviceId); 275 break; 276 277 case EventHubInterface::DEVICE_REMOVED: 278 removeDevice(rawEvent->deviceId); 279 break; 280 281 case EventHubInterface::FINISHED_DEVICE_SCAN: 282 handleConfigurationChanged(rawEvent->when); 283 break; 284 285 default: 286 consumeEvent(rawEvent); 287 break; 288 } 289} 290 291void InputReader::addDevice(int32_t deviceId) { 292 String8 name = mEventHub->getDeviceName(deviceId); 293 uint32_t classes = mEventHub->getDeviceClasses(deviceId); 294 295 InputDevice* device = createDevice(deviceId, name, classes); 296 device->configure(); 297 298 if (device->isIgnored()) { 299 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string()); 300 } else { 301 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(), 302 device->getSources()); 303 } 304 305 bool added = false; 306 { // acquire device registry writer lock 307 RWLock::AutoWLock _wl(mDeviceRegistryLock); 308 309 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 310 if (deviceIndex < 0) { 311 mDevices.add(deviceId, device); 312 added = true; 313 } 314 } // release device registry writer lock 315 316 if (! added) { 317 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId); 318 delete device; 319 return; 320 } 321} 322 323void InputReader::removeDevice(int32_t deviceId) { 324 bool removed = false; 325 InputDevice* device = NULL; 326 { // acquire device registry writer lock 327 RWLock::AutoWLock _wl(mDeviceRegistryLock); 328 329 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 330 if (deviceIndex >= 0) { 331 device = mDevices.valueAt(deviceIndex); 332 mDevices.removeItemsAt(deviceIndex, 1); 333 removed = true; 334 } 335 } // release device registry writer lock 336 337 if (! removed) { 338 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId); 339 return; 340 } 341 342 if (device->isIgnored()) { 343 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)", 344 device->getId(), device->getName().string()); 345 } else { 346 LOGI("Device removed: id=%d, name='%s', sources=0x%08x", 347 device->getId(), device->getName().string(), device->getSources()); 348 } 349 350 device->reset(); 351 352 delete device; 353} 354 355InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) { 356 InputDevice* device = new InputDevice(this, deviceId, name); 357 358 // External devices. 359 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) { 360 device->setExternal(true); 361 } 362 363 // Switch-like devices. 364 if (classes & INPUT_DEVICE_CLASS_SWITCH) { 365 device->addMapper(new SwitchInputMapper(device)); 366 } 367 368 // Keyboard-like devices. 369 uint32_t keyboardSource = 0; 370 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC; 371 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) { 372 keyboardSource |= AINPUT_SOURCE_KEYBOARD; 373 } 374 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) { 375 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC; 376 } 377 if (classes & INPUT_DEVICE_CLASS_DPAD) { 378 keyboardSource |= AINPUT_SOURCE_DPAD; 379 } 380 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) { 381 keyboardSource |= AINPUT_SOURCE_GAMEPAD; 382 } 383 384 if (keyboardSource != 0) { 385 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType)); 386 } 387 388 // Cursor-like devices. 389 if (classes & INPUT_DEVICE_CLASS_CURSOR) { 390 device->addMapper(new CursorInputMapper(device)); 391 } 392 393 // Touchscreens and touchpad devices. 394 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) { 395 device->addMapper(new MultiTouchInputMapper(device)); 396 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) { 397 device->addMapper(new SingleTouchInputMapper(device)); 398 } 399 400 // Joystick-like devices. 401 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) { 402 device->addMapper(new JoystickInputMapper(device)); 403 } 404 405 return device; 406} 407 408void InputReader::consumeEvent(const RawEvent* rawEvent) { 409 int32_t deviceId = rawEvent->deviceId; 410 411 { // acquire device registry reader lock 412 RWLock::AutoRLock _rl(mDeviceRegistryLock); 413 414 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 415 if (deviceIndex < 0) { 416 LOGW("Discarding event for unknown deviceId %d.", deviceId); 417 return; 418 } 419 420 InputDevice* device = mDevices.valueAt(deviceIndex); 421 if (device->isIgnored()) { 422 //LOGD("Discarding event for ignored deviceId %d.", deviceId); 423 return; 424 } 425 426 device->process(rawEvent); 427 } // release device registry reader lock 428} 429 430void InputReader::timeoutExpired(nsecs_t when) { 431 { // acquire device registry reader lock 432 RWLock::AutoRLock _rl(mDeviceRegistryLock); 433 434 for (size_t i = 0; i < mDevices.size(); i++) { 435 InputDevice* device = mDevices.valueAt(i); 436 if (!device->isIgnored()) { 437 device->timeoutExpired(when); 438 } 439 } 440 } // release device registry reader lock 441} 442 443void InputReader::handleConfigurationChanged(nsecs_t when) { 444 // Reset global meta state because it depends on the list of all configured devices. 445 updateGlobalMetaState(); 446 447 // Update input configuration. 448 updateInputConfiguration(); 449 450 // Enqueue configuration changed. 451 mDispatcher->notifyConfigurationChanged(when); 452} 453 454void InputReader::configureExcludedDevices() { 455 Vector<String8> excludedDeviceNames; 456 mPolicy->getExcludedDeviceNames(excludedDeviceNames); 457 458 for (size_t i = 0; i < excludedDeviceNames.size(); i++) { 459 mEventHub->addExcludedDevice(excludedDeviceNames[i]); 460 } 461} 462 463void InputReader::updateGlobalMetaState() { 464 { // acquire state lock 465 AutoMutex _l(mStateLock); 466 467 mGlobalMetaState = 0; 468 469 { // acquire device registry reader lock 470 RWLock::AutoRLock _rl(mDeviceRegistryLock); 471 472 for (size_t i = 0; i < mDevices.size(); i++) { 473 InputDevice* device = mDevices.valueAt(i); 474 mGlobalMetaState |= device->getMetaState(); 475 } 476 } // release device registry reader lock 477 } // release state lock 478} 479 480int32_t InputReader::getGlobalMetaState() { 481 { // acquire state lock 482 AutoMutex _l(mStateLock); 483 484 return mGlobalMetaState; 485 } // release state lock 486} 487 488void InputReader::updateInputConfiguration() { 489 { // acquire state lock 490 AutoMutex _l(mStateLock); 491 492 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH; 493 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS; 494 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV; 495 { // acquire device registry reader lock 496 RWLock::AutoRLock _rl(mDeviceRegistryLock); 497 498 InputDeviceInfo deviceInfo; 499 for (size_t i = 0; i < mDevices.size(); i++) { 500 InputDevice* device = mDevices.valueAt(i); 501 device->getDeviceInfo(& deviceInfo); 502 uint32_t sources = deviceInfo.getSources(); 503 504 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) { 505 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER; 506 } 507 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) { 508 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL; 509 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) { 510 navigationConfig = InputConfiguration::NAVIGATION_DPAD; 511 } 512 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) { 513 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY; 514 } 515 } 516 } // release device registry reader lock 517 518 mInputConfiguration.touchScreen = touchScreenConfig; 519 mInputConfiguration.keyboard = keyboardConfig; 520 mInputConfiguration.navigation = navigationConfig; 521 } // release state lock 522} 523 524void InputReader::disableVirtualKeysUntil(nsecs_t time) { 525 mDisableVirtualKeysTimeout = time; 526} 527 528bool InputReader::shouldDropVirtualKey(nsecs_t now, 529 InputDevice* device, int32_t keyCode, int32_t scanCode) { 530 if (now < mDisableVirtualKeysTimeout) { 531 LOGI("Dropping virtual key from device %s because virtual keys are " 532 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d", 533 device->getName().string(), 534 (mDisableVirtualKeysTimeout - now) * 0.000001, 535 keyCode, scanCode); 536 return true; 537 } else { 538 return false; 539 } 540} 541 542void InputReader::fadePointer() { 543 { // acquire device registry reader lock 544 RWLock::AutoRLock _rl(mDeviceRegistryLock); 545 546 for (size_t i = 0; i < mDevices.size(); i++) { 547 InputDevice* device = mDevices.valueAt(i); 548 device->fadePointer(); 549 } 550 } // release device registry reader lock 551} 552 553void InputReader::requestTimeoutAtTime(nsecs_t when) { 554 if (when < mNextTimeout) { 555 mNextTimeout = when; 556 } 557} 558 559void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) { 560 { // acquire state lock 561 AutoMutex _l(mStateLock); 562 563 *outConfiguration = mInputConfiguration; 564 } // release state lock 565} 566 567status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) { 568 { // acquire device registry reader lock 569 RWLock::AutoRLock _rl(mDeviceRegistryLock); 570 571 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 572 if (deviceIndex < 0) { 573 return NAME_NOT_FOUND; 574 } 575 576 InputDevice* device = mDevices.valueAt(deviceIndex); 577 if (device->isIgnored()) { 578 return NAME_NOT_FOUND; 579 } 580 581 device->getDeviceInfo(outDeviceInfo); 582 return OK; 583 } // release device registy reader lock 584} 585 586void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) { 587 outDeviceIds.clear(); 588 589 { // acquire device registry reader lock 590 RWLock::AutoRLock _rl(mDeviceRegistryLock); 591 592 size_t numDevices = mDevices.size(); 593 for (size_t i = 0; i < numDevices; i++) { 594 InputDevice* device = mDevices.valueAt(i); 595 if (! device->isIgnored()) { 596 outDeviceIds.add(device->getId()); 597 } 598 } 599 } // release device registy reader lock 600} 601 602int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, 603 int32_t keyCode) { 604 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState); 605} 606 607int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, 608 int32_t scanCode) { 609 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState); 610} 611 612int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) { 613 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState); 614} 615 616int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code, 617 GetStateFunc getStateFunc) { 618 { // acquire device registry reader lock 619 RWLock::AutoRLock _rl(mDeviceRegistryLock); 620 621 int32_t result = AKEY_STATE_UNKNOWN; 622 if (deviceId >= 0) { 623 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 624 if (deviceIndex >= 0) { 625 InputDevice* device = mDevices.valueAt(deviceIndex); 626 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 627 result = (device->*getStateFunc)(sourceMask, code); 628 } 629 } 630 } else { 631 size_t numDevices = mDevices.size(); 632 for (size_t i = 0; i < numDevices; i++) { 633 InputDevice* device = mDevices.valueAt(i); 634 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 635 result = (device->*getStateFunc)(sourceMask, code); 636 if (result >= AKEY_STATE_DOWN) { 637 return result; 638 } 639 } 640 } 641 } 642 return result; 643 } // release device registy reader lock 644} 645 646bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, 647 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { 648 memset(outFlags, 0, numCodes); 649 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags); 650} 651 652bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes, 653 const int32_t* keyCodes, uint8_t* outFlags) { 654 { // acquire device registry reader lock 655 RWLock::AutoRLock _rl(mDeviceRegistryLock); 656 bool result = false; 657 if (deviceId >= 0) { 658 ssize_t deviceIndex = mDevices.indexOfKey(deviceId); 659 if (deviceIndex >= 0) { 660 InputDevice* device = mDevices.valueAt(deviceIndex); 661 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 662 result = device->markSupportedKeyCodes(sourceMask, 663 numCodes, keyCodes, outFlags); 664 } 665 } 666 } else { 667 size_t numDevices = mDevices.size(); 668 for (size_t i = 0; i < numDevices; i++) { 669 InputDevice* device = mDevices.valueAt(i); 670 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { 671 result |= device->markSupportedKeyCodes(sourceMask, 672 numCodes, keyCodes, outFlags); 673 } 674 } 675 } 676 return result; 677 } // release device registy reader lock 678} 679 680void InputReader::dump(String8& dump) { 681 mEventHub->dump(dump); 682 dump.append("\n"); 683 684 dump.append("Input Reader State:\n"); 685 686 { // acquire device registry reader lock 687 RWLock::AutoRLock _rl(mDeviceRegistryLock); 688 689 for (size_t i = 0; i < mDevices.size(); i++) { 690 mDevices.valueAt(i)->dump(dump); 691 } 692 } // release device registy reader lock 693} 694 695 696// --- InputReaderThread --- 697 698InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) : 699 Thread(/*canCallJava*/ true), mReader(reader) { 700} 701 702InputReaderThread::~InputReaderThread() { 703} 704 705bool InputReaderThread::threadLoop() { 706 mReader->loopOnce(); 707 return true; 708} 709 710 711// --- InputDevice --- 712 713InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) : 714 mContext(context), mId(id), mName(name), mSources(0), mIsExternal(false) { 715} 716 717InputDevice::~InputDevice() { 718 size_t numMappers = mMappers.size(); 719 for (size_t i = 0; i < numMappers; i++) { 720 delete mMappers[i]; 721 } 722 mMappers.clear(); 723} 724 725void InputDevice::dump(String8& dump) { 726 InputDeviceInfo deviceInfo; 727 getDeviceInfo(& deviceInfo); 728 729 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(), 730 deviceInfo.getName().string()); 731 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal)); 732 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources()); 733 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType()); 734 735 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges(); 736 if (!ranges.isEmpty()) { 737 dump.append(INDENT2 "Motion Ranges:\n"); 738 for (size_t i = 0; i < ranges.size(); i++) { 739 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i); 740 const char* label = getAxisLabel(range.axis); 741 char name[32]; 742 if (label) { 743 strncpy(name, label, sizeof(name)); 744 name[sizeof(name) - 1] = '\0'; 745 } else { 746 snprintf(name, sizeof(name), "%d", range.axis); 747 } 748 dump.appendFormat(INDENT3 "%s: source=0x%08x, " 749 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n", 750 name, range.source, range.min, range.max, range.flat, range.fuzz); 751 } 752 } 753 754 size_t numMappers = mMappers.size(); 755 for (size_t i = 0; i < numMappers; i++) { 756 InputMapper* mapper = mMappers[i]; 757 mapper->dump(dump); 758 } 759} 760 761void InputDevice::addMapper(InputMapper* mapper) { 762 mMappers.add(mapper); 763} 764 765void InputDevice::configure() { 766 if (! isIgnored()) { 767 mContext->getEventHub()->getConfiguration(mId, &mConfiguration); 768 } 769 770 mSources = 0; 771 772 size_t numMappers = mMappers.size(); 773 for (size_t i = 0; i < numMappers; i++) { 774 InputMapper* mapper = mMappers[i]; 775 mapper->configure(); 776 mSources |= mapper->getSources(); 777 } 778} 779 780void InputDevice::reset() { 781 size_t numMappers = mMappers.size(); 782 for (size_t i = 0; i < numMappers; i++) { 783 InputMapper* mapper = mMappers[i]; 784 mapper->reset(); 785 } 786} 787 788void InputDevice::process(const RawEvent* rawEvent) { 789 size_t numMappers = mMappers.size(); 790 for (size_t i = 0; i < numMappers; i++) { 791 InputMapper* mapper = mMappers[i]; 792 mapper->process(rawEvent); 793 } 794} 795 796void InputDevice::timeoutExpired(nsecs_t when) { 797 size_t numMappers = mMappers.size(); 798 for (size_t i = 0; i < numMappers; i++) { 799 InputMapper* mapper = mMappers[i]; 800 mapper->timeoutExpired(when); 801 } 802} 803 804void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) { 805 outDeviceInfo->initialize(mId, mName); 806 807 size_t numMappers = mMappers.size(); 808 for (size_t i = 0; i < numMappers; i++) { 809 InputMapper* mapper = mMappers[i]; 810 mapper->populateDeviceInfo(outDeviceInfo); 811 } 812} 813 814int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 815 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState); 816} 817 818int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 819 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState); 820} 821 822int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 823 return getState(sourceMask, switchCode, & InputMapper::getSwitchState); 824} 825 826int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { 827 int32_t result = AKEY_STATE_UNKNOWN; 828 size_t numMappers = mMappers.size(); 829 for (size_t i = 0; i < numMappers; i++) { 830 InputMapper* mapper = mMappers[i]; 831 if (sourcesMatchMask(mapper->getSources(), sourceMask)) { 832 result = (mapper->*getStateFunc)(sourceMask, code); 833 if (result >= AKEY_STATE_DOWN) { 834 return result; 835 } 836 } 837 } 838 return result; 839} 840 841bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 842 const int32_t* keyCodes, uint8_t* outFlags) { 843 bool result = false; 844 size_t numMappers = mMappers.size(); 845 for (size_t i = 0; i < numMappers; i++) { 846 InputMapper* mapper = mMappers[i]; 847 if (sourcesMatchMask(mapper->getSources(), sourceMask)) { 848 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); 849 } 850 } 851 return result; 852} 853 854int32_t InputDevice::getMetaState() { 855 int32_t result = 0; 856 size_t numMappers = mMappers.size(); 857 for (size_t i = 0; i < numMappers; i++) { 858 InputMapper* mapper = mMappers[i]; 859 result |= mapper->getMetaState(); 860 } 861 return result; 862} 863 864void InputDevice::fadePointer() { 865 size_t numMappers = mMappers.size(); 866 for (size_t i = 0; i < numMappers; i++) { 867 InputMapper* mapper = mMappers[i]; 868 mapper->fadePointer(); 869 } 870} 871 872 873// --- InputMapper --- 874 875InputMapper::InputMapper(InputDevice* device) : 876 mDevice(device), mContext(device->getContext()) { 877} 878 879InputMapper::~InputMapper() { 880} 881 882void InputMapper::populateDeviceInfo(InputDeviceInfo* info) { 883 info->addSource(getSources()); 884} 885 886void InputMapper::dump(String8& dump) { 887} 888 889void InputMapper::configure() { 890} 891 892void InputMapper::reset() { 893} 894 895void InputMapper::timeoutExpired(nsecs_t when) { 896} 897 898int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 899 return AKEY_STATE_UNKNOWN; 900} 901 902int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 903 return AKEY_STATE_UNKNOWN; 904} 905 906int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 907 return AKEY_STATE_UNKNOWN; 908} 909 910bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 911 const int32_t* keyCodes, uint8_t* outFlags) { 912 return false; 913} 914 915int32_t InputMapper::getMetaState() { 916 return 0; 917} 918 919void InputMapper::fadePointer() { 920} 921 922void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump, 923 const RawAbsoluteAxisInfo& axis, const char* name) { 924 if (axis.valid) { 925 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d\n", 926 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz); 927 } else { 928 dump.appendFormat(INDENT4 "%s: unknown range\n", name); 929 } 930} 931 932 933// --- SwitchInputMapper --- 934 935SwitchInputMapper::SwitchInputMapper(InputDevice* device) : 936 InputMapper(device) { 937} 938 939SwitchInputMapper::~SwitchInputMapper() { 940} 941 942uint32_t SwitchInputMapper::getSources() { 943 return AINPUT_SOURCE_SWITCH; 944} 945 946void SwitchInputMapper::process(const RawEvent* rawEvent) { 947 switch (rawEvent->type) { 948 case EV_SW: 949 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value); 950 break; 951 } 952} 953 954void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) { 955 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0); 956} 957 958int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { 959 return getEventHub()->getSwitchState(getDeviceId(), switchCode); 960} 961 962 963// --- KeyboardInputMapper --- 964 965KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, 966 uint32_t source, int32_t keyboardType) : 967 InputMapper(device), mSource(source), 968 mKeyboardType(keyboardType) { 969 initializeLocked(); 970} 971 972KeyboardInputMapper::~KeyboardInputMapper() { 973} 974 975void KeyboardInputMapper::initializeLocked() { 976 mLocked.metaState = AMETA_NONE; 977 mLocked.downTime = 0; 978} 979 980uint32_t KeyboardInputMapper::getSources() { 981 return mSource; 982} 983 984void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 985 InputMapper::populateDeviceInfo(info); 986 987 info->setKeyboardType(mKeyboardType); 988} 989 990void KeyboardInputMapper::dump(String8& dump) { 991 { // acquire lock 992 AutoMutex _l(mLock); 993 dump.append(INDENT2 "Keyboard Input Mapper:\n"); 994 dumpParameters(dump); 995 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType); 996 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size()); 997 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState); 998 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime); 999 } // release lock 1000} 1001 1002 1003void KeyboardInputMapper::configure() { 1004 InputMapper::configure(); 1005 1006 // Configure basic parameters. 1007 configureParameters(); 1008 1009 // Reset LEDs. 1010 { 1011 AutoMutex _l(mLock); 1012 resetLedStateLocked(); 1013 } 1014} 1015 1016void KeyboardInputMapper::configureParameters() { 1017 mParameters.orientationAware = false; 1018 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"), 1019 mParameters.orientationAware); 1020 1021 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1; 1022} 1023 1024void KeyboardInputMapper::dumpParameters(String8& dump) { 1025 dump.append(INDENT3 "Parameters:\n"); 1026 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 1027 mParameters.associatedDisplayId); 1028 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 1029 toString(mParameters.orientationAware)); 1030} 1031 1032void KeyboardInputMapper::reset() { 1033 for (;;) { 1034 int32_t keyCode, scanCode; 1035 { // acquire lock 1036 AutoMutex _l(mLock); 1037 1038 // Synthesize key up event on reset if keys are currently down. 1039 if (mLocked.keyDowns.isEmpty()) { 1040 initializeLocked(); 1041 resetLedStateLocked(); 1042 break; // done 1043 } 1044 1045 const KeyDown& keyDown = mLocked.keyDowns.top(); 1046 keyCode = keyDown.keyCode; 1047 scanCode = keyDown.scanCode; 1048 } // release lock 1049 1050 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 1051 processKey(when, false, keyCode, scanCode, 0); 1052 } 1053 1054 InputMapper::reset(); 1055 getContext()->updateGlobalMetaState(); 1056} 1057 1058void KeyboardInputMapper::process(const RawEvent* rawEvent) { 1059 switch (rawEvent->type) { 1060 case EV_KEY: { 1061 int32_t scanCode = rawEvent->scanCode; 1062 if (isKeyboardOrGamepadKey(scanCode)) { 1063 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode, 1064 rawEvent->flags); 1065 } 1066 break; 1067 } 1068 } 1069} 1070 1071bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) { 1072 return scanCode < BTN_MOUSE 1073 || scanCode >= KEY_OK 1074 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE) 1075 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI); 1076} 1077 1078void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode, 1079 int32_t scanCode, uint32_t policyFlags) { 1080 int32_t newMetaState; 1081 nsecs_t downTime; 1082 bool metaStateChanged = false; 1083 1084 { // acquire lock 1085 AutoMutex _l(mLock); 1086 1087 if (down) { 1088 // Rotate key codes according to orientation if needed. 1089 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock. 1090 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) { 1091 int32_t orientation; 1092 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId, 1093 NULL, NULL, & orientation)) { 1094 orientation = DISPLAY_ORIENTATION_0; 1095 } 1096 1097 keyCode = rotateKeyCode(keyCode, orientation); 1098 } 1099 1100 // Add key down. 1101 ssize_t keyDownIndex = findKeyDownLocked(scanCode); 1102 if (keyDownIndex >= 0) { 1103 // key repeat, be sure to use same keycode as before in case of rotation 1104 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode; 1105 } else { 1106 // key down 1107 if ((policyFlags & POLICY_FLAG_VIRTUAL) 1108 && mContext->shouldDropVirtualKey(when, 1109 getDevice(), keyCode, scanCode)) { 1110 return; 1111 } 1112 1113 mLocked.keyDowns.push(); 1114 KeyDown& keyDown = mLocked.keyDowns.editTop(); 1115 keyDown.keyCode = keyCode; 1116 keyDown.scanCode = scanCode; 1117 } 1118 1119 mLocked.downTime = when; 1120 } else { 1121 // Remove key down. 1122 ssize_t keyDownIndex = findKeyDownLocked(scanCode); 1123 if (keyDownIndex >= 0) { 1124 // key up, be sure to use same keycode as before in case of rotation 1125 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode; 1126 mLocked.keyDowns.removeAt(size_t(keyDownIndex)); 1127 } else { 1128 // key was not actually down 1129 LOGI("Dropping key up from device %s because the key was not down. " 1130 "keyCode=%d, scanCode=%d", 1131 getDeviceName().string(), keyCode, scanCode); 1132 return; 1133 } 1134 } 1135 1136 int32_t oldMetaState = mLocked.metaState; 1137 newMetaState = updateMetaState(keyCode, down, oldMetaState); 1138 if (oldMetaState != newMetaState) { 1139 mLocked.metaState = newMetaState; 1140 metaStateChanged = true; 1141 updateLedStateLocked(false); 1142 } 1143 1144 downTime = mLocked.downTime; 1145 } // release lock 1146 1147 // Key down on external an keyboard should wake the device. 1148 // We don't do this for internal keyboards to prevent them from waking up in your pocket. 1149 // For internal keyboards, the key layout file should specify the policy flags for 1150 // each wake key individually. 1151 // TODO: Use the input device configuration to control this behavior more finely. 1152 if (down && getDevice()->isExternal() 1153 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) { 1154 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 1155 } 1156 1157 if (metaStateChanged) { 1158 getContext()->updateGlobalMetaState(); 1159 } 1160 1161 if (down && !isMetaKey(keyCode)) { 1162 getContext()->fadePointer(); 1163 } 1164 1165 getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags, 1166 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, 1167 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime); 1168} 1169 1170ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) { 1171 size_t n = mLocked.keyDowns.size(); 1172 for (size_t i = 0; i < n; i++) { 1173 if (mLocked.keyDowns[i].scanCode == scanCode) { 1174 return i; 1175 } 1176 } 1177 return -1; 1178} 1179 1180int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 1181 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode); 1182} 1183 1184int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 1185 return getEventHub()->getScanCodeState(getDeviceId(), scanCode); 1186} 1187 1188bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 1189 const int32_t* keyCodes, uint8_t* outFlags) { 1190 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags); 1191} 1192 1193int32_t KeyboardInputMapper::getMetaState() { 1194 { // acquire lock 1195 AutoMutex _l(mLock); 1196 return mLocked.metaState; 1197 } // release lock 1198} 1199 1200void KeyboardInputMapper::resetLedStateLocked() { 1201 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL); 1202 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML); 1203 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL); 1204 1205 updateLedStateLocked(true); 1206} 1207 1208void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) { 1209 ledState.avail = getEventHub()->hasLed(getDeviceId(), led); 1210 ledState.on = false; 1211} 1212 1213void KeyboardInputMapper::updateLedStateLocked(bool reset) { 1214 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL, 1215 AMETA_CAPS_LOCK_ON, reset); 1216 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML, 1217 AMETA_NUM_LOCK_ON, reset); 1218 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL, 1219 AMETA_SCROLL_LOCK_ON, reset); 1220} 1221 1222void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState, 1223 int32_t led, int32_t modifier, bool reset) { 1224 if (ledState.avail) { 1225 bool desiredState = (mLocked.metaState & modifier) != 0; 1226 if (reset || ledState.on != desiredState) { 1227 getEventHub()->setLedState(getDeviceId(), led, desiredState); 1228 ledState.on = desiredState; 1229 } 1230 } 1231} 1232 1233 1234// --- CursorInputMapper --- 1235 1236CursorInputMapper::CursorInputMapper(InputDevice* device) : 1237 InputMapper(device) { 1238 initializeLocked(); 1239} 1240 1241CursorInputMapper::~CursorInputMapper() { 1242} 1243 1244uint32_t CursorInputMapper::getSources() { 1245 return mSource; 1246} 1247 1248void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 1249 InputMapper::populateDeviceInfo(info); 1250 1251 if (mParameters.mode == Parameters::MODE_POINTER) { 1252 float minX, minY, maxX, maxY; 1253 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) { 1254 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f); 1255 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f); 1256 } 1257 } else { 1258 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale); 1259 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale); 1260 } 1261 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f); 1262 1263 if (mHaveVWheel) { 1264 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f); 1265 } 1266 if (mHaveHWheel) { 1267 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f); 1268 } 1269} 1270 1271void CursorInputMapper::dump(String8& dump) { 1272 { // acquire lock 1273 AutoMutex _l(mLock); 1274 dump.append(INDENT2 "Cursor Input Mapper:\n"); 1275 dumpParameters(dump); 1276 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale); 1277 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale); 1278 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision); 1279 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision); 1280 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel)); 1281 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel)); 1282 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale); 1283 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale); 1284 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState); 1285 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState))); 1286 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime); 1287 } // release lock 1288} 1289 1290void CursorInputMapper::configure() { 1291 InputMapper::configure(); 1292 1293 // Configure basic parameters. 1294 configureParameters(); 1295 1296 // Configure device mode. 1297 switch (mParameters.mode) { 1298 case Parameters::MODE_POINTER: 1299 mSource = AINPUT_SOURCE_MOUSE; 1300 mXPrecision = 1.0f; 1301 mYPrecision = 1.0f; 1302 mXScale = 1.0f; 1303 mYScale = 1.0f; 1304 mPointerController = getPolicy()->obtainPointerController(getDeviceId()); 1305 break; 1306 case Parameters::MODE_NAVIGATION: 1307 mSource = AINPUT_SOURCE_TRACKBALL; 1308 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD; 1309 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD; 1310 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; 1311 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; 1312 break; 1313 } 1314 1315 mVWheelScale = 1.0f; 1316 mHWheelScale = 1.0f; 1317 1318 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL); 1319 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL); 1320} 1321 1322void CursorInputMapper::configureParameters() { 1323 mParameters.mode = Parameters::MODE_POINTER; 1324 String8 cursorModeString; 1325 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) { 1326 if (cursorModeString == "navigation") { 1327 mParameters.mode = Parameters::MODE_NAVIGATION; 1328 } else if (cursorModeString != "pointer" && cursorModeString != "default") { 1329 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string()); 1330 } 1331 } 1332 1333 mParameters.orientationAware = false; 1334 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"), 1335 mParameters.orientationAware); 1336 1337 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER 1338 || mParameters.orientationAware ? 0 : -1; 1339} 1340 1341void CursorInputMapper::dumpParameters(String8& dump) { 1342 dump.append(INDENT3 "Parameters:\n"); 1343 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 1344 mParameters.associatedDisplayId); 1345 1346 switch (mParameters.mode) { 1347 case Parameters::MODE_POINTER: 1348 dump.append(INDENT4 "Mode: pointer\n"); 1349 break; 1350 case Parameters::MODE_NAVIGATION: 1351 dump.append(INDENT4 "Mode: navigation\n"); 1352 break; 1353 default: 1354 assert(false); 1355 } 1356 1357 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 1358 toString(mParameters.orientationAware)); 1359} 1360 1361void CursorInputMapper::initializeLocked() { 1362 mAccumulator.clear(); 1363 1364 mLocked.buttonState = 0; 1365 mLocked.downTime = 0; 1366} 1367 1368void CursorInputMapper::reset() { 1369 for (;;) { 1370 uint32_t buttonState; 1371 { // acquire lock 1372 AutoMutex _l(mLock); 1373 1374 buttonState = mLocked.buttonState; 1375 if (!buttonState) { 1376 initializeLocked(); 1377 break; // done 1378 } 1379 } // release lock 1380 1381 // Synthesize button up event on reset. 1382 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 1383 mAccumulator.clear(); 1384 mAccumulator.buttonDown = 0; 1385 mAccumulator.buttonUp = buttonState; 1386 mAccumulator.fields = Accumulator::FIELD_BUTTONS; 1387 sync(when); 1388 } 1389 1390 InputMapper::reset(); 1391} 1392 1393void CursorInputMapper::process(const RawEvent* rawEvent) { 1394 switch (rawEvent->type) { 1395 case EV_KEY: { 1396 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode); 1397 if (buttonState) { 1398 if (rawEvent->value) { 1399 mAccumulator.buttonDown = buttonState; 1400 mAccumulator.buttonUp = 0; 1401 } else { 1402 mAccumulator.buttonDown = 0; 1403 mAccumulator.buttonUp = buttonState; 1404 } 1405 mAccumulator.fields |= Accumulator::FIELD_BUTTONS; 1406 1407 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and 1408 // we need to ensure that we report the up/down promptly. 1409 sync(rawEvent->when); 1410 break; 1411 } 1412 break; 1413 } 1414 1415 case EV_REL: 1416 switch (rawEvent->scanCode) { 1417 case REL_X: 1418 mAccumulator.fields |= Accumulator::FIELD_REL_X; 1419 mAccumulator.relX = rawEvent->value; 1420 break; 1421 case REL_Y: 1422 mAccumulator.fields |= Accumulator::FIELD_REL_Y; 1423 mAccumulator.relY = rawEvent->value; 1424 break; 1425 case REL_WHEEL: 1426 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL; 1427 mAccumulator.relWheel = rawEvent->value; 1428 break; 1429 case REL_HWHEEL: 1430 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL; 1431 mAccumulator.relHWheel = rawEvent->value; 1432 break; 1433 } 1434 break; 1435 1436 case EV_SYN: 1437 switch (rawEvent->scanCode) { 1438 case SYN_REPORT: 1439 sync(rawEvent->when); 1440 break; 1441 } 1442 break; 1443 } 1444} 1445 1446void CursorInputMapper::sync(nsecs_t when) { 1447 uint32_t fields = mAccumulator.fields; 1448 if (fields == 0) { 1449 return; // no new state changes, so nothing to do 1450 } 1451 1452 int32_t motionEventAction; 1453 int32_t motionEventEdgeFlags; 1454 PointerCoords pointerCoords; 1455 nsecs_t downTime; 1456 float vscroll, hscroll; 1457 { // acquire lock 1458 AutoMutex _l(mLock); 1459 1460 bool down, downChanged; 1461 bool wasDown = isPointerDown(mLocked.buttonState); 1462 bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS; 1463 if (buttonsChanged) { 1464 mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown) 1465 & ~mAccumulator.buttonUp; 1466 1467 down = isPointerDown(mLocked.buttonState); 1468 1469 if (!wasDown && down) { 1470 mLocked.downTime = when; 1471 downChanged = true; 1472 } else if (wasDown && !down) { 1473 downChanged = true; 1474 } else { 1475 downChanged = false; 1476 } 1477 } else { 1478 down = wasDown; 1479 downChanged = false; 1480 } 1481 1482 downTime = mLocked.downTime; 1483 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f; 1484 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f; 1485 1486 if (downChanged) { 1487 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP; 1488 } else if (down || mPointerController == NULL) { 1489 motionEventAction = AMOTION_EVENT_ACTION_MOVE; 1490 } else { 1491 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE; 1492 } 1493 1494 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0 1495 && (deltaX != 0.0f || deltaY != 0.0f)) { 1496 // Rotate motion based on display orientation if needed. 1497 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock. 1498 int32_t orientation; 1499 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId, 1500 NULL, NULL, & orientation)) { 1501 orientation = DISPLAY_ORIENTATION_0; 1502 } 1503 1504 float temp; 1505 switch (orientation) { 1506 case DISPLAY_ORIENTATION_90: 1507 temp = deltaX; 1508 deltaX = deltaY; 1509 deltaY = -temp; 1510 break; 1511 1512 case DISPLAY_ORIENTATION_180: 1513 deltaX = -deltaX; 1514 deltaY = -deltaY; 1515 break; 1516 1517 case DISPLAY_ORIENTATION_270: 1518 temp = deltaX; 1519 deltaX = -deltaY; 1520 deltaY = temp; 1521 break; 1522 } 1523 } 1524 1525 pointerCoords.clear(); 1526 1527 motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE; 1528 1529 if (mPointerController != NULL) { 1530 mPointerController->move(deltaX, deltaY); 1531 if (buttonsChanged) { 1532 mPointerController->setButtonState(mLocked.buttonState); 1533 } 1534 1535 float x, y; 1536 mPointerController->getPosition(&x, &y); 1537 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); 1538 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 1539 1540 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) { 1541 motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds( 1542 mPointerController, x, y); 1543 } 1544 } else { 1545 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); 1546 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); 1547 } 1548 1549 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f); 1550 1551 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) { 1552 vscroll = mAccumulator.relWheel; 1553 } else { 1554 vscroll = 0; 1555 } 1556 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) { 1557 hscroll = mAccumulator.relHWheel; 1558 } else { 1559 hscroll = 0; 1560 } 1561 if (hscroll != 0 || vscroll != 0) { 1562 mPointerController->unfade(); 1563 } 1564 } // release lock 1565 1566 // Moving an external trackball or mouse should wake the device. 1567 // We don't do this for internal cursor devices to prevent them from waking up 1568 // the device in your pocket. 1569 // TODO: Use the input device configuration to control this behavior more finely. 1570 uint32_t policyFlags = 0; 1571 if (getDevice()->isExternal()) { 1572 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 1573 } 1574 1575 int32_t metaState = mContext->getGlobalMetaState(); 1576 int32_t pointerId = 0; 1577 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags, 1578 motionEventAction, 0, metaState, motionEventEdgeFlags, 1579 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime); 1580 1581 mAccumulator.clear(); 1582 1583 if (vscroll != 0 || hscroll != 0) { 1584 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); 1585 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); 1586 1587 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags, 1588 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 1589 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime); 1590 } 1591} 1592 1593int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 1594 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) { 1595 return getEventHub()->getScanCodeState(getDeviceId(), scanCode); 1596 } else { 1597 return AKEY_STATE_UNKNOWN; 1598 } 1599} 1600 1601void CursorInputMapper::fadePointer() { 1602 { // acquire lock 1603 AutoMutex _l(mLock); 1604 if (mPointerController != NULL) { 1605 mPointerController->fade(); 1606 } 1607 } // release lock 1608} 1609 1610 1611// --- TouchInputMapper --- 1612 1613TouchInputMapper::TouchInputMapper(InputDevice* device) : 1614 InputMapper(device) { 1615 mLocked.surfaceOrientation = -1; 1616 mLocked.surfaceWidth = -1; 1617 mLocked.surfaceHeight = -1; 1618 1619 initializeLocked(); 1620} 1621 1622TouchInputMapper::~TouchInputMapper() { 1623} 1624 1625uint32_t TouchInputMapper::getSources() { 1626 return mTouchSource | mPointerSource; 1627} 1628 1629void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 1630 InputMapper::populateDeviceInfo(info); 1631 1632 { // acquire lock 1633 AutoMutex _l(mLock); 1634 1635 // Ensure surface information is up to date so that orientation changes are 1636 // noticed immediately. 1637 if (!configureSurfaceLocked()) { 1638 return; 1639 } 1640 1641 info->addMotionRange(mLocked.orientedRanges.x); 1642 info->addMotionRange(mLocked.orientedRanges.y); 1643 1644 if (mLocked.orientedRanges.havePressure) { 1645 info->addMotionRange(mLocked.orientedRanges.pressure); 1646 } 1647 1648 if (mLocked.orientedRanges.haveSize) { 1649 info->addMotionRange(mLocked.orientedRanges.size); 1650 } 1651 1652 if (mLocked.orientedRanges.haveTouchSize) { 1653 info->addMotionRange(mLocked.orientedRanges.touchMajor); 1654 info->addMotionRange(mLocked.orientedRanges.touchMinor); 1655 } 1656 1657 if (mLocked.orientedRanges.haveToolSize) { 1658 info->addMotionRange(mLocked.orientedRanges.toolMajor); 1659 info->addMotionRange(mLocked.orientedRanges.toolMinor); 1660 } 1661 1662 if (mLocked.orientedRanges.haveOrientation) { 1663 info->addMotionRange(mLocked.orientedRanges.orientation); 1664 } 1665 1666 if (mPointerController != NULL) { 1667 float minX, minY, maxX, maxY; 1668 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) { 1669 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource, 1670 minX, maxX, 0.0f, 0.0f); 1671 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource, 1672 minY, maxY, 0.0f, 0.0f); 1673 } 1674 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource, 1675 0.0f, 1.0f, 0.0f, 0.0f); 1676 } 1677 } // release lock 1678} 1679 1680void TouchInputMapper::dump(String8& dump) { 1681 { // acquire lock 1682 AutoMutex _l(mLock); 1683 dump.append(INDENT2 "Touch Input Mapper:\n"); 1684 dumpParameters(dump); 1685 dumpVirtualKeysLocked(dump); 1686 dumpRawAxes(dump); 1687 dumpCalibration(dump); 1688 dumpSurfaceLocked(dump); 1689 1690 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n"); 1691 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale); 1692 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale); 1693 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision); 1694 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision); 1695 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale); 1696 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale); 1697 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias); 1698 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale); 1699 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias); 1700 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale); 1701 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale); 1702 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale); 1703 1704 dump.appendFormat(INDENT3 "Last Touch:\n"); 1705 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount); 1706 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState); 1707 1708 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) { 1709 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n"); 1710 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n", 1711 mLocked.pointerGestureXMovementScale); 1712 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n", 1713 mLocked.pointerGestureYMovementScale); 1714 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n", 1715 mLocked.pointerGestureXZoomScale); 1716 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n", 1717 mLocked.pointerGestureYZoomScale); 1718 dump.appendFormat(INDENT4 "MaxSwipeWidthSquared: %d\n", 1719 mLocked.pointerGestureMaxSwipeWidthSquared); 1720 } 1721 } // release lock 1722} 1723 1724void TouchInputMapper::initializeLocked() { 1725 mCurrentTouch.clear(); 1726 mLastTouch.clear(); 1727 mDownTime = 0; 1728 1729 for (uint32_t i = 0; i < MAX_POINTERS; i++) { 1730 mAveragingTouchFilter.historyStart[i] = 0; 1731 mAveragingTouchFilter.historyEnd[i] = 0; 1732 } 1733 1734 mJumpyTouchFilter.jumpyPointsDropped = 0; 1735 1736 mLocked.currentVirtualKey.down = false; 1737 1738 mLocked.orientedRanges.havePressure = false; 1739 mLocked.orientedRanges.haveSize = false; 1740 mLocked.orientedRanges.haveTouchSize = false; 1741 mLocked.orientedRanges.haveToolSize = false; 1742 mLocked.orientedRanges.haveOrientation = false; 1743 1744 mPointerGesture.reset(); 1745} 1746 1747void TouchInputMapper::configure() { 1748 InputMapper::configure(); 1749 1750 // Configure basic parameters. 1751 configureParameters(); 1752 1753 // Configure sources. 1754 switch (mParameters.deviceType) { 1755 case Parameters::DEVICE_TYPE_TOUCH_SCREEN: 1756 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN; 1757 mPointerSource = 0; 1758 break; 1759 case Parameters::DEVICE_TYPE_TOUCH_PAD: 1760 mTouchSource = AINPUT_SOURCE_TOUCHPAD; 1761 mPointerSource = 0; 1762 break; 1763 case Parameters::DEVICE_TYPE_POINTER: 1764 mTouchSource = AINPUT_SOURCE_TOUCHPAD; 1765 mPointerSource = AINPUT_SOURCE_MOUSE; 1766 break; 1767 default: 1768 assert(false); 1769 } 1770 1771 // Configure absolute axis information. 1772 configureRawAxes(); 1773 1774 // Prepare input device calibration. 1775 parseCalibration(); 1776 resolveCalibration(); 1777 1778 { // acquire lock 1779 AutoMutex _l(mLock); 1780 1781 // Configure surface dimensions and orientation. 1782 configureSurfaceLocked(); 1783 } // release lock 1784} 1785 1786void TouchInputMapper::configureParameters() { 1787 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents(); 1788 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents(); 1789 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents(); 1790 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime(); 1791 1792 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X) 1793 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) { 1794 // The device is a cursor device with a touch pad attached. 1795 // By default don't use the touch pad to move the pointer. 1796 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; 1797 } else { 1798 // The device is just a touch pad. 1799 // By default use the touch pad to move the pointer and to perform related gestures. 1800 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; 1801 } 1802 1803 String8 deviceTypeString; 1804 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"), 1805 deviceTypeString)) { 1806 if (deviceTypeString == "touchScreen") { 1807 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; 1808 } else if (deviceTypeString == "touchPad") { 1809 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; 1810 } else if (deviceTypeString == "pointer") { 1811 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; 1812 } else { 1813 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string()); 1814 } 1815 } 1816 1817 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN; 1818 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"), 1819 mParameters.orientationAware); 1820 1821 mParameters.associatedDisplayId = mParameters.orientationAware 1822 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN 1823 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER 1824 ? 0 : -1; 1825} 1826 1827void TouchInputMapper::dumpParameters(String8& dump) { 1828 dump.append(INDENT3 "Parameters:\n"); 1829 1830 switch (mParameters.deviceType) { 1831 case Parameters::DEVICE_TYPE_TOUCH_SCREEN: 1832 dump.append(INDENT4 "DeviceType: touchScreen\n"); 1833 break; 1834 case Parameters::DEVICE_TYPE_TOUCH_PAD: 1835 dump.append(INDENT4 "DeviceType: touchPad\n"); 1836 break; 1837 case Parameters::DEVICE_TYPE_POINTER: 1838 dump.append(INDENT4 "DeviceType: pointer\n"); 1839 break; 1840 default: 1841 assert(false); 1842 } 1843 1844 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n", 1845 mParameters.associatedDisplayId); 1846 dump.appendFormat(INDENT4 "OrientationAware: %s\n", 1847 toString(mParameters.orientationAware)); 1848 1849 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n", 1850 toString(mParameters.useBadTouchFilter)); 1851 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n", 1852 toString(mParameters.useAveragingTouchFilter)); 1853 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n", 1854 toString(mParameters.useJumpyTouchFilter)); 1855} 1856 1857void TouchInputMapper::configureRawAxes() { 1858 mRawAxes.x.clear(); 1859 mRawAxes.y.clear(); 1860 mRawAxes.pressure.clear(); 1861 mRawAxes.touchMajor.clear(); 1862 mRawAxes.touchMinor.clear(); 1863 mRawAxes.toolMajor.clear(); 1864 mRawAxes.toolMinor.clear(); 1865 mRawAxes.orientation.clear(); 1866} 1867 1868void TouchInputMapper::dumpRawAxes(String8& dump) { 1869 dump.append(INDENT3 "Raw Axes:\n"); 1870 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X"); 1871 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y"); 1872 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure"); 1873 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor"); 1874 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor"); 1875 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor"); 1876 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor"); 1877 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation"); 1878} 1879 1880bool TouchInputMapper::configureSurfaceLocked() { 1881 // Ensure we have valid X and Y axes. 1882 if (!mRawAxes.x.valid || !mRawAxes.y.valid) { 1883 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! " 1884 "The device will be inoperable.", getDeviceName().string()); 1885 return false; 1886 } 1887 1888 // Update orientation and dimensions if needed. 1889 int32_t orientation = DISPLAY_ORIENTATION_0; 1890 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1; 1891 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1; 1892 1893 if (mParameters.associatedDisplayId >= 0) { 1894 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock. 1895 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId, 1896 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight, 1897 &mLocked.associatedDisplayOrientation)) { 1898 return false; 1899 } 1900 1901 // A touch screen inherits the dimensions of the display. 1902 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) { 1903 width = mLocked.associatedDisplayWidth; 1904 height = mLocked.associatedDisplayHeight; 1905 } 1906 1907 // The device inherits the orientation of the display if it is orientation aware. 1908 if (mParameters.orientationAware) { 1909 orientation = mLocked.associatedDisplayOrientation; 1910 } 1911 } 1912 1913 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER 1914 && mPointerController == NULL) { 1915 mPointerController = getPolicy()->obtainPointerController(getDeviceId()); 1916 } 1917 1918 bool orientationChanged = mLocked.surfaceOrientation != orientation; 1919 if (orientationChanged) { 1920 mLocked.surfaceOrientation = orientation; 1921 } 1922 1923 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height; 1924 if (sizeChanged) { 1925 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d", 1926 getDeviceId(), getDeviceName().string(), width, height); 1927 1928 mLocked.surfaceWidth = width; 1929 mLocked.surfaceHeight = height; 1930 1931 // Configure X and Y factors. 1932 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1); 1933 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1); 1934 mLocked.xPrecision = 1.0f / mLocked.xScale; 1935 mLocked.yPrecision = 1.0f / mLocked.yScale; 1936 1937 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X; 1938 mLocked.orientedRanges.x.source = mTouchSource; 1939 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y; 1940 mLocked.orientedRanges.y.source = mTouchSource; 1941 1942 configureVirtualKeysLocked(); 1943 1944 // Scale factor for terms that are not oriented in a particular axis. 1945 // If the pixels are square then xScale == yScale otherwise we fake it 1946 // by choosing an average. 1947 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale); 1948 1949 // Size of diagonal axis. 1950 float diagonalSize = pythag(width, height); 1951 1952 // TouchMajor and TouchMinor factors. 1953 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) { 1954 mLocked.orientedRanges.haveTouchSize = true; 1955 1956 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR; 1957 mLocked.orientedRanges.touchMajor.source = mTouchSource; 1958 mLocked.orientedRanges.touchMajor.min = 0; 1959 mLocked.orientedRanges.touchMajor.max = diagonalSize; 1960 mLocked.orientedRanges.touchMajor.flat = 0; 1961 mLocked.orientedRanges.touchMajor.fuzz = 0; 1962 1963 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor; 1964 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR; 1965 } 1966 1967 // ToolMajor and ToolMinor factors. 1968 mLocked.toolSizeLinearScale = 0; 1969 mLocked.toolSizeLinearBias = 0; 1970 mLocked.toolSizeAreaScale = 0; 1971 mLocked.toolSizeAreaBias = 0; 1972 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) { 1973 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) { 1974 if (mCalibration.haveToolSizeLinearScale) { 1975 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale; 1976 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) { 1977 mLocked.toolSizeLinearScale = float(min(width, height)) 1978 / mRawAxes.toolMajor.maxValue; 1979 } 1980 1981 if (mCalibration.haveToolSizeLinearBias) { 1982 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias; 1983 } 1984 } else if (mCalibration.toolSizeCalibration == 1985 Calibration::TOOL_SIZE_CALIBRATION_AREA) { 1986 if (mCalibration.haveToolSizeLinearScale) { 1987 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale; 1988 } else { 1989 mLocked.toolSizeLinearScale = min(width, height); 1990 } 1991 1992 if (mCalibration.haveToolSizeLinearBias) { 1993 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias; 1994 } 1995 1996 if (mCalibration.haveToolSizeAreaScale) { 1997 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale; 1998 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) { 1999 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue; 2000 } 2001 2002 if (mCalibration.haveToolSizeAreaBias) { 2003 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias; 2004 } 2005 } 2006 2007 mLocked.orientedRanges.haveToolSize = true; 2008 2009 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR; 2010 mLocked.orientedRanges.toolMajor.source = mTouchSource; 2011 mLocked.orientedRanges.toolMajor.min = 0; 2012 mLocked.orientedRanges.toolMajor.max = diagonalSize; 2013 mLocked.orientedRanges.toolMajor.flat = 0; 2014 mLocked.orientedRanges.toolMajor.fuzz = 0; 2015 2016 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor; 2017 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR; 2018 } 2019 2020 // Pressure factors. 2021 mLocked.pressureScale = 0; 2022 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) { 2023 RawAbsoluteAxisInfo rawPressureAxis; 2024 switch (mCalibration.pressureSource) { 2025 case Calibration::PRESSURE_SOURCE_PRESSURE: 2026 rawPressureAxis = mRawAxes.pressure; 2027 break; 2028 case Calibration::PRESSURE_SOURCE_TOUCH: 2029 rawPressureAxis = mRawAxes.touchMajor; 2030 break; 2031 default: 2032 rawPressureAxis.clear(); 2033 } 2034 2035 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL 2036 || mCalibration.pressureCalibration 2037 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) { 2038 if (mCalibration.havePressureScale) { 2039 mLocked.pressureScale = mCalibration.pressureScale; 2040 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) { 2041 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue; 2042 } 2043 } 2044 2045 mLocked.orientedRanges.havePressure = true; 2046 2047 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE; 2048 mLocked.orientedRanges.pressure.source = mTouchSource; 2049 mLocked.orientedRanges.pressure.min = 0; 2050 mLocked.orientedRanges.pressure.max = 1.0; 2051 mLocked.orientedRanges.pressure.flat = 0; 2052 mLocked.orientedRanges.pressure.fuzz = 0; 2053 } 2054 2055 // Size factors. 2056 mLocked.sizeScale = 0; 2057 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) { 2058 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) { 2059 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) { 2060 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue; 2061 } 2062 } 2063 2064 mLocked.orientedRanges.haveSize = true; 2065 2066 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE; 2067 mLocked.orientedRanges.size.source = mTouchSource; 2068 mLocked.orientedRanges.size.min = 0; 2069 mLocked.orientedRanges.size.max = 1.0; 2070 mLocked.orientedRanges.size.flat = 0; 2071 mLocked.orientedRanges.size.fuzz = 0; 2072 } 2073 2074 // Orientation 2075 mLocked.orientationScale = 0; 2076 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) { 2077 if (mCalibration.orientationCalibration 2078 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) { 2079 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) { 2080 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue; 2081 } 2082 } 2083 2084 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION; 2085 mLocked.orientedRanges.orientation.source = mTouchSource; 2086 mLocked.orientedRanges.orientation.min = - M_PI_2; 2087 mLocked.orientedRanges.orientation.max = M_PI_2; 2088 mLocked.orientedRanges.orientation.flat = 0; 2089 mLocked.orientedRanges.orientation.fuzz = 0; 2090 } 2091 } 2092 2093 if (orientationChanged || sizeChanged) { 2094 // Compute oriented surface dimensions, precision, scales and ranges. 2095 // Note that the maximum value reported is an inclusive maximum value so it is one 2096 // unit less than the total width or height of surface. 2097 switch (mLocked.surfaceOrientation) { 2098 case DISPLAY_ORIENTATION_90: 2099 case DISPLAY_ORIENTATION_270: 2100 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight; 2101 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth; 2102 2103 mLocked.orientedXPrecision = mLocked.yPrecision; 2104 mLocked.orientedYPrecision = mLocked.xPrecision; 2105 2106 mLocked.orientedRanges.x.min = 0; 2107 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue) 2108 * mLocked.yScale; 2109 mLocked.orientedRanges.x.flat = 0; 2110 mLocked.orientedRanges.x.fuzz = mLocked.yScale; 2111 2112 mLocked.orientedRanges.y.min = 0; 2113 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue) 2114 * mLocked.xScale; 2115 mLocked.orientedRanges.y.flat = 0; 2116 mLocked.orientedRanges.y.fuzz = mLocked.xScale; 2117 break; 2118 2119 default: 2120 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth; 2121 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight; 2122 2123 mLocked.orientedXPrecision = mLocked.xPrecision; 2124 mLocked.orientedYPrecision = mLocked.yPrecision; 2125 2126 mLocked.orientedRanges.x.min = 0; 2127 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue) 2128 * mLocked.xScale; 2129 mLocked.orientedRanges.x.flat = 0; 2130 mLocked.orientedRanges.x.fuzz = mLocked.xScale; 2131 2132 mLocked.orientedRanges.y.min = 0; 2133 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue) 2134 * mLocked.yScale; 2135 mLocked.orientedRanges.y.flat = 0; 2136 mLocked.orientedRanges.y.fuzz = mLocked.yScale; 2137 break; 2138 } 2139 2140 // Compute pointer gesture detection parameters. 2141 // TODO: These factors should not be hardcoded. 2142 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) { 2143 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1; 2144 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1; 2145 2146 // Scale movements such that one whole swipe of the touch pad covers a portion 2147 // of the display along whichever axis of the touch pad is longer. 2148 // Assume that the touch pad has a square aspect ratio such that movements in 2149 // X and Y of the same number of raw units cover the same physical distance. 2150 const float scaleFactor = 0.8f; 2151 2152 mLocked.pointerGestureXMovementScale = rawWidth > rawHeight 2153 ? scaleFactor * float(mLocked.associatedDisplayWidth) / rawWidth 2154 : scaleFactor * float(mLocked.associatedDisplayHeight) / rawHeight; 2155 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale; 2156 2157 // Scale zooms to cover a smaller range of the display than movements do. 2158 // This value determines the area around the pointer that is affected by freeform 2159 // pointer gestures. 2160 mLocked.pointerGestureXZoomScale = mLocked.pointerGestureXMovementScale * 0.4f; 2161 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureYMovementScale * 0.4f; 2162 2163 // Max width between pointers to detect a swipe gesture is 3/4 of the short 2164 // axis of the touch pad. Touches that are wider than this are translated 2165 // into freeform gestures. 2166 mLocked.pointerGestureMaxSwipeWidthSquared = min(rawWidth, rawHeight) * 3 / 4; 2167 mLocked.pointerGestureMaxSwipeWidthSquared *= 2168 mLocked.pointerGestureMaxSwipeWidthSquared; 2169 } 2170 } 2171 2172 return true; 2173} 2174 2175void TouchInputMapper::dumpSurfaceLocked(String8& dump) { 2176 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth); 2177 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight); 2178 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation); 2179} 2180 2181void TouchInputMapper::configureVirtualKeysLocked() { 2182 Vector<VirtualKeyDefinition> virtualKeyDefinitions; 2183 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions); 2184 2185 mLocked.virtualKeys.clear(); 2186 2187 if (virtualKeyDefinitions.size() == 0) { 2188 return; 2189 } 2190 2191 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size()); 2192 2193 int32_t touchScreenLeft = mRawAxes.x.minValue; 2194 int32_t touchScreenTop = mRawAxes.y.minValue; 2195 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1; 2196 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1; 2197 2198 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) { 2199 const VirtualKeyDefinition& virtualKeyDefinition = 2200 virtualKeyDefinitions[i]; 2201 2202 mLocked.virtualKeys.add(); 2203 VirtualKey& virtualKey = mLocked.virtualKeys.editTop(); 2204 2205 virtualKey.scanCode = virtualKeyDefinition.scanCode; 2206 int32_t keyCode; 2207 uint32_t flags; 2208 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 2209 & keyCode, & flags)) { 2210 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", 2211 virtualKey.scanCode); 2212 mLocked.virtualKeys.pop(); // drop the key 2213 continue; 2214 } 2215 2216 virtualKey.keyCode = keyCode; 2217 virtualKey.flags = flags; 2218 2219 // convert the key definition's display coordinates into touch coordinates for a hit box 2220 int32_t halfWidth = virtualKeyDefinition.width / 2; 2221 int32_t halfHeight = virtualKeyDefinition.height / 2; 2222 2223 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) 2224 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft; 2225 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth) 2226 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft; 2227 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) 2228 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop; 2229 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) 2230 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop; 2231 } 2232} 2233 2234void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) { 2235 if (!mLocked.virtualKeys.isEmpty()) { 2236 dump.append(INDENT3 "Virtual Keys:\n"); 2237 2238 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) { 2239 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i); 2240 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, " 2241 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n", 2242 i, virtualKey.scanCode, virtualKey.keyCode, 2243 virtualKey.hitLeft, virtualKey.hitRight, 2244 virtualKey.hitTop, virtualKey.hitBottom); 2245 } 2246 } 2247} 2248 2249void TouchInputMapper::parseCalibration() { 2250 const PropertyMap& in = getDevice()->getConfiguration(); 2251 Calibration& out = mCalibration; 2252 2253 // Touch Size 2254 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT; 2255 String8 touchSizeCalibrationString; 2256 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) { 2257 if (touchSizeCalibrationString == "none") { 2258 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE; 2259 } else if (touchSizeCalibrationString == "geometric") { 2260 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC; 2261 } else if (touchSizeCalibrationString == "pressure") { 2262 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE; 2263 } else if (touchSizeCalibrationString != "default") { 2264 LOGW("Invalid value for touch.touchSize.calibration: '%s'", 2265 touchSizeCalibrationString.string()); 2266 } 2267 } 2268 2269 // Tool Size 2270 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT; 2271 String8 toolSizeCalibrationString; 2272 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) { 2273 if (toolSizeCalibrationString == "none") { 2274 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE; 2275 } else if (toolSizeCalibrationString == "geometric") { 2276 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC; 2277 } else if (toolSizeCalibrationString == "linear") { 2278 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR; 2279 } else if (toolSizeCalibrationString == "area") { 2280 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA; 2281 } else if (toolSizeCalibrationString != "default") { 2282 LOGW("Invalid value for touch.toolSize.calibration: '%s'", 2283 toolSizeCalibrationString.string()); 2284 } 2285 } 2286 2287 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"), 2288 out.toolSizeLinearScale); 2289 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"), 2290 out.toolSizeLinearBias); 2291 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"), 2292 out.toolSizeAreaScale); 2293 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"), 2294 out.toolSizeAreaBias); 2295 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"), 2296 out.toolSizeIsSummed); 2297 2298 // Pressure 2299 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT; 2300 String8 pressureCalibrationString; 2301 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) { 2302 if (pressureCalibrationString == "none") { 2303 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; 2304 } else if (pressureCalibrationString == "physical") { 2305 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; 2306 } else if (pressureCalibrationString == "amplitude") { 2307 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE; 2308 } else if (pressureCalibrationString != "default") { 2309 LOGW("Invalid value for touch.pressure.calibration: '%s'", 2310 pressureCalibrationString.string()); 2311 } 2312 } 2313 2314 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT; 2315 String8 pressureSourceString; 2316 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) { 2317 if (pressureSourceString == "pressure") { 2318 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE; 2319 } else if (pressureSourceString == "touch") { 2320 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH; 2321 } else if (pressureSourceString != "default") { 2322 LOGW("Invalid value for touch.pressure.source: '%s'", 2323 pressureSourceString.string()); 2324 } 2325 } 2326 2327 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), 2328 out.pressureScale); 2329 2330 // Size 2331 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT; 2332 String8 sizeCalibrationString; 2333 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) { 2334 if (sizeCalibrationString == "none") { 2335 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; 2336 } else if (sizeCalibrationString == "normalized") { 2337 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED; 2338 } else if (sizeCalibrationString != "default") { 2339 LOGW("Invalid value for touch.size.calibration: '%s'", 2340 sizeCalibrationString.string()); 2341 } 2342 } 2343 2344 // Orientation 2345 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT; 2346 String8 orientationCalibrationString; 2347 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) { 2348 if (orientationCalibrationString == "none") { 2349 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; 2350 } else if (orientationCalibrationString == "interpolated") { 2351 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; 2352 } else if (orientationCalibrationString == "vector") { 2353 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR; 2354 } else if (orientationCalibrationString != "default") { 2355 LOGW("Invalid value for touch.orientation.calibration: '%s'", 2356 orientationCalibrationString.string()); 2357 } 2358 } 2359} 2360 2361void TouchInputMapper::resolveCalibration() { 2362 // Pressure 2363 switch (mCalibration.pressureSource) { 2364 case Calibration::PRESSURE_SOURCE_DEFAULT: 2365 if (mRawAxes.pressure.valid) { 2366 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE; 2367 } else if (mRawAxes.touchMajor.valid) { 2368 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH; 2369 } 2370 break; 2371 2372 case Calibration::PRESSURE_SOURCE_PRESSURE: 2373 if (! mRawAxes.pressure.valid) { 2374 LOGW("Calibration property touch.pressure.source is 'pressure' but " 2375 "the pressure axis is not available."); 2376 } 2377 break; 2378 2379 case Calibration::PRESSURE_SOURCE_TOUCH: 2380 if (! mRawAxes.touchMajor.valid) { 2381 LOGW("Calibration property touch.pressure.source is 'touch' but " 2382 "the touchMajor axis is not available."); 2383 } 2384 break; 2385 2386 default: 2387 break; 2388 } 2389 2390 switch (mCalibration.pressureCalibration) { 2391 case Calibration::PRESSURE_CALIBRATION_DEFAULT: 2392 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) { 2393 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE; 2394 } else { 2395 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; 2396 } 2397 break; 2398 2399 default: 2400 break; 2401 } 2402 2403 // Tool Size 2404 switch (mCalibration.toolSizeCalibration) { 2405 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT: 2406 if (mRawAxes.toolMajor.valid) { 2407 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR; 2408 } else { 2409 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE; 2410 } 2411 break; 2412 2413 default: 2414 break; 2415 } 2416 2417 // Touch Size 2418 switch (mCalibration.touchSizeCalibration) { 2419 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT: 2420 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE 2421 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) { 2422 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE; 2423 } else { 2424 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE; 2425 } 2426 break; 2427 2428 default: 2429 break; 2430 } 2431 2432 // Size 2433 switch (mCalibration.sizeCalibration) { 2434 case Calibration::SIZE_CALIBRATION_DEFAULT: 2435 if (mRawAxes.toolMajor.valid) { 2436 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED; 2437 } else { 2438 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; 2439 } 2440 break; 2441 2442 default: 2443 break; 2444 } 2445 2446 // Orientation 2447 switch (mCalibration.orientationCalibration) { 2448 case Calibration::ORIENTATION_CALIBRATION_DEFAULT: 2449 if (mRawAxes.orientation.valid) { 2450 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; 2451 } else { 2452 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; 2453 } 2454 break; 2455 2456 default: 2457 break; 2458 } 2459} 2460 2461void TouchInputMapper::dumpCalibration(String8& dump) { 2462 dump.append(INDENT3 "Calibration:\n"); 2463 2464 // Touch Size 2465 switch (mCalibration.touchSizeCalibration) { 2466 case Calibration::TOUCH_SIZE_CALIBRATION_NONE: 2467 dump.append(INDENT4 "touch.touchSize.calibration: none\n"); 2468 break; 2469 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC: 2470 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n"); 2471 break; 2472 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE: 2473 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n"); 2474 break; 2475 default: 2476 assert(false); 2477 } 2478 2479 // Tool Size 2480 switch (mCalibration.toolSizeCalibration) { 2481 case Calibration::TOOL_SIZE_CALIBRATION_NONE: 2482 dump.append(INDENT4 "touch.toolSize.calibration: none\n"); 2483 break; 2484 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC: 2485 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n"); 2486 break; 2487 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR: 2488 dump.append(INDENT4 "touch.toolSize.calibration: linear\n"); 2489 break; 2490 case Calibration::TOOL_SIZE_CALIBRATION_AREA: 2491 dump.append(INDENT4 "touch.toolSize.calibration: area\n"); 2492 break; 2493 default: 2494 assert(false); 2495 } 2496 2497 if (mCalibration.haveToolSizeLinearScale) { 2498 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n", 2499 mCalibration.toolSizeLinearScale); 2500 } 2501 2502 if (mCalibration.haveToolSizeLinearBias) { 2503 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n", 2504 mCalibration.toolSizeLinearBias); 2505 } 2506 2507 if (mCalibration.haveToolSizeAreaScale) { 2508 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n", 2509 mCalibration.toolSizeAreaScale); 2510 } 2511 2512 if (mCalibration.haveToolSizeAreaBias) { 2513 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n", 2514 mCalibration.toolSizeAreaBias); 2515 } 2516 2517 if (mCalibration.haveToolSizeIsSummed) { 2518 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n", 2519 toString(mCalibration.toolSizeIsSummed)); 2520 } 2521 2522 // Pressure 2523 switch (mCalibration.pressureCalibration) { 2524 case Calibration::PRESSURE_CALIBRATION_NONE: 2525 dump.append(INDENT4 "touch.pressure.calibration: none\n"); 2526 break; 2527 case Calibration::PRESSURE_CALIBRATION_PHYSICAL: 2528 dump.append(INDENT4 "touch.pressure.calibration: physical\n"); 2529 break; 2530 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: 2531 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n"); 2532 break; 2533 default: 2534 assert(false); 2535 } 2536 2537 switch (mCalibration.pressureSource) { 2538 case Calibration::PRESSURE_SOURCE_PRESSURE: 2539 dump.append(INDENT4 "touch.pressure.source: pressure\n"); 2540 break; 2541 case Calibration::PRESSURE_SOURCE_TOUCH: 2542 dump.append(INDENT4 "touch.pressure.source: touch\n"); 2543 break; 2544 case Calibration::PRESSURE_SOURCE_DEFAULT: 2545 break; 2546 default: 2547 assert(false); 2548 } 2549 2550 if (mCalibration.havePressureScale) { 2551 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n", 2552 mCalibration.pressureScale); 2553 } 2554 2555 // Size 2556 switch (mCalibration.sizeCalibration) { 2557 case Calibration::SIZE_CALIBRATION_NONE: 2558 dump.append(INDENT4 "touch.size.calibration: none\n"); 2559 break; 2560 case Calibration::SIZE_CALIBRATION_NORMALIZED: 2561 dump.append(INDENT4 "touch.size.calibration: normalized\n"); 2562 break; 2563 default: 2564 assert(false); 2565 } 2566 2567 // Orientation 2568 switch (mCalibration.orientationCalibration) { 2569 case Calibration::ORIENTATION_CALIBRATION_NONE: 2570 dump.append(INDENT4 "touch.orientation.calibration: none\n"); 2571 break; 2572 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: 2573 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n"); 2574 break; 2575 case Calibration::ORIENTATION_CALIBRATION_VECTOR: 2576 dump.append(INDENT4 "touch.orientation.calibration: vector\n"); 2577 break; 2578 default: 2579 assert(false); 2580 } 2581} 2582 2583void TouchInputMapper::reset() { 2584 // Synthesize touch up event if touch is currently down. 2585 // This will also take care of finishing virtual key processing if needed. 2586 if (mLastTouch.pointerCount != 0) { 2587 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 2588 mCurrentTouch.clear(); 2589 syncTouch(when, true); 2590 } 2591 2592 { // acquire lock 2593 AutoMutex _l(mLock); 2594 initializeLocked(); 2595 } // release lock 2596 2597 InputMapper::reset(); 2598} 2599 2600void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) { 2601#if DEBUG_RAW_EVENTS 2602 if (!havePointerIds) { 2603 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount); 2604 } else { 2605 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, " 2606 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount, 2607 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value, 2608 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value, 2609 mLastTouch.idBits.value & mCurrentTouch.idBits.value, 2610 mLastTouch.idBits.value, mCurrentTouch.idBits.value); 2611 } 2612#endif 2613 2614 // Preprocess pointer data. 2615 if (mParameters.useBadTouchFilter) { 2616 if (applyBadTouchFilter()) { 2617 havePointerIds = false; 2618 } 2619 } 2620 2621 if (mParameters.useJumpyTouchFilter) { 2622 if (applyJumpyTouchFilter()) { 2623 havePointerIds = false; 2624 } 2625 } 2626 2627 if (!havePointerIds) { 2628 calculatePointerIds(); 2629 } 2630 2631 TouchData temp; 2632 TouchData* savedTouch; 2633 if (mParameters.useAveragingTouchFilter) { 2634 temp.copyFrom(mCurrentTouch); 2635 savedTouch = & temp; 2636 2637 applyAveragingTouchFilter(); 2638 } else { 2639 savedTouch = & mCurrentTouch; 2640 } 2641 2642 uint32_t policyFlags = 0; 2643 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) { 2644 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) { 2645 // If this is a touch screen, hide the pointer on an initial down. 2646 getContext()->fadePointer(); 2647 } 2648 2649 // Initial downs on external touch devices should wake the device. 2650 // We don't do this for internal touch screens to prevent them from waking 2651 // up in your pocket. 2652 // TODO: Use the input device configuration to control this behavior more finely. 2653 if (getDevice()->isExternal()) { 2654 policyFlags |= POLICY_FLAG_WAKE_DROPPED; 2655 } 2656 } 2657 2658 // Process touches and virtual keys. 2659 TouchResult touchResult = consumeOffScreenTouches(when, policyFlags); 2660 if (touchResult == DISPATCH_TOUCH) { 2661 suppressSwipeOntoVirtualKeys(when); 2662 if (mPointerController != NULL) { 2663 dispatchPointerGestures(when, policyFlags); 2664 } 2665 dispatchTouches(when, policyFlags); 2666 } 2667 2668 // Copy current touch to last touch in preparation for the next cycle. 2669 // Keep the button state so we can track edge-triggered button state changes. 2670 if (touchResult == DROP_STROKE) { 2671 mLastTouch.clear(); 2672 mLastTouch.buttonState = savedTouch->buttonState; 2673 } else { 2674 mLastTouch.copyFrom(*savedTouch); 2675 } 2676} 2677 2678TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches( 2679 nsecs_t when, uint32_t policyFlags) { 2680 int32_t keyEventAction, keyEventFlags; 2681 int32_t keyCode, scanCode, downTime; 2682 TouchResult touchResult; 2683 2684 { // acquire lock 2685 AutoMutex _l(mLock); 2686 2687 // Update surface size and orientation, including virtual key positions. 2688 if (! configureSurfaceLocked()) { 2689 return DROP_STROKE; 2690 } 2691 2692 // Check for virtual key press. 2693 if (mLocked.currentVirtualKey.down) { 2694 if (mCurrentTouch.pointerCount == 0) { 2695 // Pointer went up while virtual key was down. 2696 mLocked.currentVirtualKey.down = false; 2697#if DEBUG_VIRTUAL_KEYS 2698 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d", 2699 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode); 2700#endif 2701 keyEventAction = AKEY_EVENT_ACTION_UP; 2702 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY; 2703 touchResult = SKIP_TOUCH; 2704 goto DispatchVirtualKey; 2705 } 2706 2707 if (mCurrentTouch.pointerCount == 1) { 2708 int32_t x = mCurrentTouch.pointers[0].x; 2709 int32_t y = mCurrentTouch.pointers[0].y; 2710 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y); 2711 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) { 2712 // Pointer is still within the space of the virtual key. 2713 return SKIP_TOUCH; 2714 } 2715 } 2716 2717 // Pointer left virtual key area or another pointer also went down. 2718 // Send key cancellation and drop the stroke so subsequent motions will be 2719 // considered fresh downs. This is useful when the user swipes away from the 2720 // virtual key area into the main display surface. 2721 mLocked.currentVirtualKey.down = false; 2722#if DEBUG_VIRTUAL_KEYS 2723 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", 2724 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode); 2725#endif 2726 keyEventAction = AKEY_EVENT_ACTION_UP; 2727 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY 2728 | AKEY_EVENT_FLAG_CANCELED; 2729 2730 // Check whether the pointer moved inside the display area where we should 2731 // start a new stroke. 2732 int32_t x = mCurrentTouch.pointers[0].x; 2733 int32_t y = mCurrentTouch.pointers[0].y; 2734 if (isPointInsideSurfaceLocked(x, y)) { 2735 mLastTouch.clear(); 2736 touchResult = DISPATCH_TOUCH; 2737 } else { 2738 touchResult = DROP_STROKE; 2739 } 2740 } else { 2741 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) { 2742 // Pointer just went down. Handle off-screen touches, if needed. 2743 int32_t x = mCurrentTouch.pointers[0].x; 2744 int32_t y = mCurrentTouch.pointers[0].y; 2745 if (! isPointInsideSurfaceLocked(x, y)) { 2746 // If exactly one pointer went down, check for virtual key hit. 2747 // Otherwise we will drop the entire stroke. 2748 if (mCurrentTouch.pointerCount == 1) { 2749 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y); 2750 if (virtualKey) { 2751 if (mContext->shouldDropVirtualKey(when, getDevice(), 2752 virtualKey->keyCode, virtualKey->scanCode)) { 2753 return DROP_STROKE; 2754 } 2755 2756 mLocked.currentVirtualKey.down = true; 2757 mLocked.currentVirtualKey.downTime = when; 2758 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode; 2759 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode; 2760#if DEBUG_VIRTUAL_KEYS 2761 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d", 2762 mLocked.currentVirtualKey.keyCode, 2763 mLocked.currentVirtualKey.scanCode); 2764#endif 2765 keyEventAction = AKEY_EVENT_ACTION_DOWN; 2766 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM 2767 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY; 2768 touchResult = SKIP_TOUCH; 2769 goto DispatchVirtualKey; 2770 } 2771 } 2772 return DROP_STROKE; 2773 } 2774 } 2775 return DISPATCH_TOUCH; 2776 } 2777 2778 DispatchVirtualKey: 2779 // Collect remaining state needed to dispatch virtual key. 2780 keyCode = mLocked.currentVirtualKey.keyCode; 2781 scanCode = mLocked.currentVirtualKey.scanCode; 2782 downTime = mLocked.currentVirtualKey.downTime; 2783 } // release lock 2784 2785 // Dispatch virtual key. 2786 int32_t metaState = mContext->getGlobalMetaState(); 2787 policyFlags |= POLICY_FLAG_VIRTUAL; 2788 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags, 2789 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); 2790 return touchResult; 2791} 2792 2793void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) { 2794 // Disable all virtual key touches that happen within a short time interval of the 2795 // most recent touch. The idea is to filter out stray virtual key presses when 2796 // interacting with the touch screen. 2797 // 2798 // Problems we're trying to solve: 2799 // 2800 // 1. While scrolling a list or dragging the window shade, the user swipes down into a 2801 // virtual key area that is implemented by a separate touch panel and accidentally 2802 // triggers a virtual key. 2803 // 2804 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen 2805 // area and accidentally triggers a virtual key. This often happens when virtual keys 2806 // are layed out below the screen near to where the on screen keyboard's space bar 2807 // is displayed. 2808 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) { 2809 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime); 2810 } 2811} 2812 2813void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) { 2814 uint32_t currentPointerCount = mCurrentTouch.pointerCount; 2815 uint32_t lastPointerCount = mLastTouch.pointerCount; 2816 if (currentPointerCount == 0 && lastPointerCount == 0) { 2817 return; // nothing to do! 2818 } 2819 2820 // Update current touch coordinates. 2821 int32_t edgeFlags; 2822 float xPrecision, yPrecision; 2823 prepareTouches(&edgeFlags, &xPrecision, &yPrecision); 2824 2825 // Dispatch motions. 2826 BitSet32 currentIdBits = mCurrentTouch.idBits; 2827 BitSet32 lastIdBits = mLastTouch.idBits; 2828 uint32_t metaState = getContext()->getGlobalMetaState(); 2829 2830 if (currentIdBits == lastIdBits) { 2831 // No pointer id changes so this is a move event. 2832 // The dispatcher takes care of batching moves so we don't have to deal with that here. 2833 dispatchMotion(when, policyFlags, mTouchSource, 2834 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 2835 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1, 2836 xPrecision, yPrecision, mDownTime); 2837 } else { 2838 // There may be pointers going up and pointers going down and pointers moving 2839 // all at the same time. 2840 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value); 2841 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value); 2842 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value); 2843 BitSet32 dispatchedIdBits(lastIdBits.value); 2844 2845 // Update last coordinates of pointers that have moved so that we observe the new 2846 // pointer positions at the same time as other pointers that have just gone up. 2847 bool moveNeeded = updateMovedPointerCoords( 2848 mCurrentTouchCoords, mCurrentTouch.idToIndex, 2849 mLastTouchCoords, mLastTouch.idToIndex, 2850 moveIdBits); 2851 2852 // Dispatch pointer up events. 2853 while (!upIdBits.isEmpty()) { 2854 uint32_t upId = upIdBits.firstMarkedBit(); 2855 upIdBits.clearBit(upId); 2856 2857 dispatchMotion(when, policyFlags, mTouchSource, 2858 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0, 2859 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId, 2860 xPrecision, yPrecision, mDownTime); 2861 dispatchedIdBits.clearBit(upId); 2862 } 2863 2864 // Dispatch move events if any of the remaining pointers moved from their old locations. 2865 // Although applications receive new locations as part of individual pointer up 2866 // events, they do not generally handle them except when presented in a move event. 2867 if (moveNeeded) { 2868 assert(moveIdBits.value == dispatchedIdBits.value); 2869 dispatchMotion(when, policyFlags, mTouchSource, 2870 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0, 2871 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1, 2872 xPrecision, yPrecision, mDownTime); 2873 } 2874 2875 // Dispatch pointer down events using the new pointer locations. 2876 while (!downIdBits.isEmpty()) { 2877 uint32_t downId = downIdBits.firstMarkedBit(); 2878 downIdBits.clearBit(downId); 2879 dispatchedIdBits.markBit(downId); 2880 2881 if (dispatchedIdBits.count() == 1) { 2882 // First pointer is going down. Set down time. 2883 mDownTime = when; 2884 } else { 2885 // Only send edge flags with first pointer down. 2886 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE; 2887 } 2888 2889 dispatchMotion(when, policyFlags, mTouchSource, 2890 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags, 2891 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId, 2892 xPrecision, yPrecision, mDownTime); 2893 } 2894 } 2895 2896 // Update state for next time. 2897 for (uint32_t i = 0; i < currentPointerCount; i++) { 2898 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]); 2899 } 2900} 2901 2902void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags, 2903 float* outXPrecision, float* outYPrecision) { 2904 uint32_t currentPointerCount = mCurrentTouch.pointerCount; 2905 uint32_t lastPointerCount = mLastTouch.pointerCount; 2906 2907 AutoMutex _l(mLock); 2908 2909 // Walk through the the active pointers and map touch screen coordinates (TouchData) into 2910 // display or surface coordinates (PointerCoords) and adjust for display orientation. 2911 for (uint32_t i = 0; i < currentPointerCount; i++) { 2912 const PointerData& in = mCurrentTouch.pointers[i]; 2913 2914 // ToolMajor and ToolMinor 2915 float toolMajor, toolMinor; 2916 switch (mCalibration.toolSizeCalibration) { 2917 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC: 2918 toolMajor = in.toolMajor * mLocked.geometricScale; 2919 if (mRawAxes.toolMinor.valid) { 2920 toolMinor = in.toolMinor * mLocked.geometricScale; 2921 } else { 2922 toolMinor = toolMajor; 2923 } 2924 break; 2925 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR: 2926 toolMajor = in.toolMajor != 0 2927 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias 2928 : 0; 2929 if (mRawAxes.toolMinor.valid) { 2930 toolMinor = in.toolMinor != 0 2931 ? in.toolMinor * mLocked.toolSizeLinearScale 2932 + mLocked.toolSizeLinearBias 2933 : 0; 2934 } else { 2935 toolMinor = toolMajor; 2936 } 2937 break; 2938 case Calibration::TOOL_SIZE_CALIBRATION_AREA: 2939 if (in.toolMajor != 0) { 2940 float diameter = sqrtf(in.toolMajor 2941 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias); 2942 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias; 2943 } else { 2944 toolMajor = 0; 2945 } 2946 toolMinor = toolMajor; 2947 break; 2948 default: 2949 toolMajor = 0; 2950 toolMinor = 0; 2951 break; 2952 } 2953 2954 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) { 2955 toolMajor /= currentPointerCount; 2956 toolMinor /= currentPointerCount; 2957 } 2958 2959 // Pressure 2960 float rawPressure; 2961 switch (mCalibration.pressureSource) { 2962 case Calibration::PRESSURE_SOURCE_PRESSURE: 2963 rawPressure = in.pressure; 2964 break; 2965 case Calibration::PRESSURE_SOURCE_TOUCH: 2966 rawPressure = in.touchMajor; 2967 break; 2968 default: 2969 rawPressure = 0; 2970 } 2971 2972 float pressure; 2973 switch (mCalibration.pressureCalibration) { 2974 case Calibration::PRESSURE_CALIBRATION_PHYSICAL: 2975 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: 2976 pressure = rawPressure * mLocked.pressureScale; 2977 break; 2978 default: 2979 pressure = 1; 2980 break; 2981 } 2982 2983 // TouchMajor and TouchMinor 2984 float touchMajor, touchMinor; 2985 switch (mCalibration.touchSizeCalibration) { 2986 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC: 2987 touchMajor = in.touchMajor * mLocked.geometricScale; 2988 if (mRawAxes.touchMinor.valid) { 2989 touchMinor = in.touchMinor * mLocked.geometricScale; 2990 } else { 2991 touchMinor = touchMajor; 2992 } 2993 break; 2994 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE: 2995 touchMajor = toolMajor * pressure; 2996 touchMinor = toolMinor * pressure; 2997 break; 2998 default: 2999 touchMajor = 0; 3000 touchMinor = 0; 3001 break; 3002 } 3003 3004 if (touchMajor > toolMajor) { 3005 touchMajor = toolMajor; 3006 } 3007 if (touchMinor > toolMinor) { 3008 touchMinor = toolMinor; 3009 } 3010 3011 // Size 3012 float size; 3013 switch (mCalibration.sizeCalibration) { 3014 case Calibration::SIZE_CALIBRATION_NORMALIZED: { 3015 float rawSize = mRawAxes.toolMinor.valid 3016 ? avg(in.toolMajor, in.toolMinor) 3017 : in.toolMajor; 3018 size = rawSize * mLocked.sizeScale; 3019 break; 3020 } 3021 default: 3022 size = 0; 3023 break; 3024 } 3025 3026 // Orientation 3027 float orientation; 3028 switch (mCalibration.orientationCalibration) { 3029 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: 3030 orientation = in.orientation * mLocked.orientationScale; 3031 break; 3032 case Calibration::ORIENTATION_CALIBRATION_VECTOR: { 3033 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4); 3034 int32_t c2 = signExtendNybble(in.orientation & 0x0f); 3035 if (c1 != 0 || c2 != 0) { 3036 orientation = atan2f(c1, c2) * 0.5f; 3037 float scale = 1.0f + pythag(c1, c2) / 16.0f; 3038 touchMajor *= scale; 3039 touchMinor /= scale; 3040 toolMajor *= scale; 3041 toolMinor /= scale; 3042 } else { 3043 orientation = 0; 3044 } 3045 break; 3046 } 3047 default: 3048 orientation = 0; 3049 } 3050 3051 // X and Y 3052 // Adjust coords for surface orientation. 3053 float x, y; 3054 switch (mLocked.surfaceOrientation) { 3055 case DISPLAY_ORIENTATION_90: 3056 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale; 3057 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale; 3058 orientation -= M_PI_2; 3059 if (orientation < - M_PI_2) { 3060 orientation += M_PI; 3061 } 3062 break; 3063 case DISPLAY_ORIENTATION_180: 3064 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale; 3065 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale; 3066 break; 3067 case DISPLAY_ORIENTATION_270: 3068 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale; 3069 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale; 3070 orientation += M_PI_2; 3071 if (orientation > M_PI_2) { 3072 orientation -= M_PI; 3073 } 3074 break; 3075 default: 3076 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale; 3077 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale; 3078 break; 3079 } 3080 3081 // Write output coords. 3082 PointerCoords& out = mCurrentTouchCoords[i]; 3083 out.clear(); 3084 out.setAxisValue(AMOTION_EVENT_AXIS_X, x); 3085 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y); 3086 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure); 3087 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size); 3088 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor); 3089 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor); 3090 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor); 3091 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor); 3092 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation); 3093 } 3094 3095 // Check edge flags by looking only at the first pointer since the flags are 3096 // global to the event. 3097 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE; 3098 if (lastPointerCount == 0 && currentPointerCount > 0) { 3099 const PointerData& in = mCurrentTouch.pointers[0]; 3100 3101 if (in.x <= mRawAxes.x.minValue) { 3102 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT, 3103 mLocked.surfaceOrientation); 3104 } else if (in.x >= mRawAxes.x.maxValue) { 3105 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT, 3106 mLocked.surfaceOrientation); 3107 } 3108 if (in.y <= mRawAxes.y.minValue) { 3109 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP, 3110 mLocked.surfaceOrientation); 3111 } else if (in.y >= mRawAxes.y.maxValue) { 3112 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM, 3113 mLocked.surfaceOrientation); 3114 } 3115 } 3116 3117 *outXPrecision = mLocked.orientedXPrecision; 3118 *outYPrecision = mLocked.orientedYPrecision; 3119} 3120 3121void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags) { 3122 // Update current gesture coordinates. 3123 bool cancelPreviousGesture, finishPreviousGesture; 3124 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture); 3125 3126 // Send events! 3127 uint32_t metaState = getContext()->getGlobalMetaState(); 3128 3129 // Update last coordinates of pointers that have moved so that we observe the new 3130 // pointer positions at the same time as other pointers that have just gone up. 3131 bool down = mPointerGesture.currentGestureMode == PointerGesture::CLICK_OR_DRAG 3132 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE 3133 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM; 3134 bool moveNeeded = false; 3135 if (down && !cancelPreviousGesture && !finishPreviousGesture 3136 && mPointerGesture.lastGesturePointerCount != 0 3137 && mPointerGesture.currentGesturePointerCount != 0) { 3138 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value 3139 & mPointerGesture.lastGestureIdBits.value); 3140 moveNeeded = updateMovedPointerCoords( 3141 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 3142 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, 3143 movedGestureIdBits); 3144 } 3145 3146 // Send motion events for all pointers that went up or were canceled. 3147 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits); 3148 if (!dispatchedGestureIdBits.isEmpty()) { 3149 if (cancelPreviousGesture) { 3150 dispatchMotion(when, policyFlags, mPointerSource, 3151 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 3152 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, 3153 dispatchedGestureIdBits, -1, 3154 0, 0, mPointerGesture.downTime); 3155 3156 dispatchedGestureIdBits.clear(); 3157 } else { 3158 BitSet32 upGestureIdBits; 3159 if (finishPreviousGesture) { 3160 upGestureIdBits = dispatchedGestureIdBits; 3161 } else { 3162 upGestureIdBits.value = dispatchedGestureIdBits.value 3163 & ~mPointerGesture.currentGestureIdBits.value; 3164 } 3165 while (!upGestureIdBits.isEmpty()) { 3166 uint32_t id = upGestureIdBits.firstMarkedBit(); 3167 upGestureIdBits.clearBit(id); 3168 3169 dispatchMotion(when, policyFlags, mPointerSource, 3170 AMOTION_EVENT_ACTION_POINTER_UP, 0, 3171 metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 3172 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, 3173 dispatchedGestureIdBits, id, 3174 0, 0, mPointerGesture.downTime); 3175 3176 dispatchedGestureIdBits.clearBit(id); 3177 } 3178 } 3179 } 3180 3181 // Send motion events for all pointers that moved. 3182 if (moveNeeded) { 3183 dispatchMotion(when, policyFlags, mPointerSource, 3184 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 3185 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 3186 dispatchedGestureIdBits, -1, 3187 0, 0, mPointerGesture.downTime); 3188 } 3189 3190 // Send motion events for all pointers that went down. 3191 if (down) { 3192 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value 3193 & ~dispatchedGestureIdBits.value); 3194 while (!downGestureIdBits.isEmpty()) { 3195 uint32_t id = downGestureIdBits.firstMarkedBit(); 3196 downGestureIdBits.clearBit(id); 3197 dispatchedGestureIdBits.markBit(id); 3198 3199 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE; 3200 if (dispatchedGestureIdBits.count() == 1) { 3201 // First pointer is going down. Calculate edge flags and set down time. 3202 uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; 3203 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index]; 3204 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController, 3205 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X), 3206 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y)); 3207 mPointerGesture.downTime = when; 3208 } 3209 3210 dispatchMotion(when, policyFlags, mPointerSource, 3211 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags, 3212 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 3213 dispatchedGestureIdBits, id, 3214 0, 0, mPointerGesture.downTime); 3215 } 3216 } 3217 3218 // Send down and up for a tap. 3219 if (mPointerGesture.currentGestureMode == PointerGesture::TAP) { 3220 const PointerCoords& coords = mPointerGesture.currentGestureCoords[0]; 3221 int32_t edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController, 3222 coords.getAxisValue(AMOTION_EVENT_AXIS_X), 3223 coords.getAxisValue(AMOTION_EVENT_AXIS_Y)); 3224 nsecs_t downTime = mPointerGesture.downTime = mPointerGesture.tapTime; 3225 mPointerGesture.resetTapTime(); 3226 3227 dispatchMotion(downTime, policyFlags, mPointerSource, 3228 AMOTION_EVENT_ACTION_DOWN, 0, metaState, edgeFlags, 3229 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 3230 mPointerGesture.currentGestureIdBits, -1, 3231 0, 0, downTime); 3232 dispatchMotion(when, policyFlags, mPointerSource, 3233 AMOTION_EVENT_ACTION_UP, 0, metaState, edgeFlags, 3234 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 3235 mPointerGesture.currentGestureIdBits, -1, 3236 0, 0, downTime); 3237 } 3238 3239 // Send motion events for hover. 3240 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) { 3241 dispatchMotion(when, policyFlags, mPointerSource, 3242 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 3243 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, 3244 mPointerGesture.currentGestureIdBits, -1, 3245 0, 0, mPointerGesture.downTime); 3246 } 3247 3248 // Update state. 3249 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode; 3250 if (!down) { 3251 mPointerGesture.lastGesturePointerCount = 0; 3252 mPointerGesture.lastGestureIdBits.clear(); 3253 } else { 3254 uint32_t currentGesturePointerCount = mPointerGesture.currentGesturePointerCount; 3255 mPointerGesture.lastGesturePointerCount = currentGesturePointerCount; 3256 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits; 3257 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) { 3258 uint32_t id = idBits.firstMarkedBit(); 3259 idBits.clearBit(id); 3260 uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; 3261 mPointerGesture.lastGestureCoords[index].copyFrom( 3262 mPointerGesture.currentGestureCoords[index]); 3263 mPointerGesture.lastGestureIdToIndex[id] = index; 3264 } 3265 } 3266} 3267 3268void TouchInputMapper::preparePointerGestures(nsecs_t when, 3269 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture) { 3270 *outCancelPreviousGesture = false; 3271 *outFinishPreviousGesture = false; 3272 3273 AutoMutex _l(mLock); 3274 3275 // Update the velocity tracker. 3276 { 3277 VelocityTracker::Position positions[MAX_POINTERS]; 3278 uint32_t count = 0; 3279 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) { 3280 uint32_t id = idBits.firstMarkedBit(); 3281 idBits.clearBit(id); 3282 uint32_t index = mCurrentTouch.idToIndex[id]; 3283 positions[count].x = mCurrentTouch.pointers[index].x 3284 * mLocked.pointerGestureXMovementScale; 3285 positions[count].y = mCurrentTouch.pointers[index].y 3286 * mLocked.pointerGestureYMovementScale; 3287 } 3288 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions); 3289 } 3290 3291 // Pick a new active touch id if needed. 3292 // Choose an arbitrary pointer that just went down, if there is one. 3293 // Otherwise choose an arbitrary remaining pointer. 3294 // This guarantees we always have an active touch id when there is at least one pointer. 3295 // We always switch to the newest pointer down because that's usually where the user's 3296 // attention is focused. 3297 int32_t activeTouchId; 3298 BitSet32 downTouchIdBits(mCurrentTouch.idBits.value & ~mLastTouch.idBits.value); 3299 if (!downTouchIdBits.isEmpty()) { 3300 activeTouchId = mPointerGesture.activeTouchId = downTouchIdBits.firstMarkedBit(); 3301 } else { 3302 activeTouchId = mPointerGesture.activeTouchId; 3303 if (activeTouchId < 0 || !mCurrentTouch.idBits.hasBit(activeTouchId)) { 3304 if (!mCurrentTouch.idBits.isEmpty()) { 3305 activeTouchId = mPointerGesture.activeTouchId = 3306 mCurrentTouch.idBits.firstMarkedBit(); 3307 } else { 3308 activeTouchId = mPointerGesture.activeTouchId = -1; 3309 } 3310 } 3311 } 3312 3313 // Update the touch origin data to track where each finger originally went down. 3314 if (mCurrentTouch.pointerCount == 0 || mPointerGesture.touchOrigin.pointerCount == 0) { 3315 // Fast path when all fingers have gone up or down. 3316 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch); 3317 } else { 3318 // Slow path when only some fingers have gone up or down. 3319 for (BitSet32 idBits(mPointerGesture.touchOrigin.idBits.value 3320 & ~mCurrentTouch.idBits.value); !idBits.isEmpty(); ) { 3321 uint32_t id = idBits.firstMarkedBit(); 3322 idBits.clearBit(id); 3323 mPointerGesture.touchOrigin.idBits.clearBit(id); 3324 uint32_t index = mPointerGesture.touchOrigin.idToIndex[id]; 3325 uint32_t count = --mPointerGesture.touchOrigin.pointerCount; 3326 while (index < count) { 3327 mPointerGesture.touchOrigin.pointers[index] = 3328 mPointerGesture.touchOrigin.pointers[index + 1]; 3329 uint32_t movedId = mPointerGesture.touchOrigin.pointers[index].id; 3330 mPointerGesture.touchOrigin.idToIndex[movedId] = index; 3331 index += 1; 3332 } 3333 } 3334 for (BitSet32 idBits(mCurrentTouch.idBits.value 3335 & ~mPointerGesture.touchOrigin.idBits.value); !idBits.isEmpty(); ) { 3336 uint32_t id = idBits.firstMarkedBit(); 3337 idBits.clearBit(id); 3338 mPointerGesture.touchOrigin.idBits.markBit(id); 3339 uint32_t index = mPointerGesture.touchOrigin.pointerCount++; 3340 mPointerGesture.touchOrigin.pointers[index] = 3341 mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]]; 3342 mPointerGesture.touchOrigin.idToIndex[id] = index; 3343 } 3344 } 3345 3346 // Determine whether we are in quiet time. 3347 bool isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL; 3348 if (!isQuietTime) { 3349 if ((mPointerGesture.lastGestureMode == PointerGesture::SWIPE 3350 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) 3351 && mCurrentTouch.pointerCount < 2) { 3352 // Enter quiet time when exiting swipe or freeform state. 3353 // This is to prevent accidentally entering the hover state and flinging the 3354 // pointer when finishing a swipe and there is still one pointer left onscreen. 3355 isQuietTime = true; 3356 } else if (mPointerGesture.lastGestureMode == PointerGesture::CLICK_OR_DRAG 3357 && mCurrentTouch.pointerCount >= 2 3358 && !isPointerDown(mCurrentTouch.buttonState)) { 3359 // Enter quiet time when releasing the button and there are still two or more 3360 // fingers down. This may indicate that one finger was used to press the button 3361 // but it has not gone up yet. 3362 isQuietTime = true; 3363 } 3364 if (isQuietTime) { 3365 mPointerGesture.quietTime = when; 3366 } 3367 } 3368 3369 // Switch states based on button and pointer state. 3370 if (isQuietTime) { 3371 // Case 1: Quiet time. (QUIET) 3372#if DEBUG_GESTURES 3373 LOGD("Gestures: QUIET for next %0.3fms", 3374 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f); 3375#endif 3376 *outFinishPreviousGesture = true; 3377 3378 mPointerGesture.activeGestureId = -1; 3379 mPointerGesture.currentGestureMode = PointerGesture::QUIET; 3380 mPointerGesture.currentGesturePointerCount = 0; 3381 mPointerGesture.currentGestureIdBits.clear(); 3382 } else if (isPointerDown(mCurrentTouch.buttonState)) { 3383 // Case 2: Button is pressed. (DRAG) 3384 // The pointer follows the active touch point. 3385 // Emit DOWN, MOVE, UP events at the pointer location. 3386 // 3387 // Only the active touch matters; other fingers are ignored. This policy helps 3388 // to handle the case where the user places a second finger on the touch pad 3389 // to apply the necessary force to depress an integrated button below the surface. 3390 // We don't want the second finger to be delivered to applications. 3391 // 3392 // For this to work well, we need to make sure to track the pointer that is really 3393 // active. If the user first puts one finger down to click then adds another 3394 // finger to drag then the active pointer should switch to the finger that is 3395 // being dragged. 3396#if DEBUG_GESTURES 3397 LOGD("Gestures: CLICK_OR_DRAG activeTouchId=%d, " 3398 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount); 3399#endif 3400 // Reset state when just starting. 3401 if (mPointerGesture.lastGestureMode != PointerGesture::CLICK_OR_DRAG) { 3402 *outFinishPreviousGesture = true; 3403 mPointerGesture.activeGestureId = 0; 3404 } 3405 3406 // Switch pointers if needed. 3407 // Find the fastest pointer and follow it. 3408 if (activeTouchId >= 0) { 3409 if (mCurrentTouch.pointerCount > 1) { 3410 int32_t bestId = -1; 3411 float bestSpeed = DRAG_MIN_SWITCH_SPEED; 3412 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) { 3413 uint32_t id = mCurrentTouch.pointers[i].id; 3414 float vx, vy; 3415 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) { 3416 float speed = pythag(vx, vy); 3417 if (speed > bestSpeed) { 3418 bestId = id; 3419 bestSpeed = speed; 3420 } 3421 } 3422 } 3423 if (bestId >= 0 && bestId != activeTouchId) { 3424 mPointerGesture.activeTouchId = activeTouchId = bestId; 3425#if DEBUG_GESTURES 3426 LOGD("Gestures: CLICK_OR_DRAG switched pointers, " 3427 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed); 3428#endif 3429 } 3430 } 3431 3432 if (mLastTouch.idBits.hasBit(activeTouchId)) { 3433 const PointerData& currentPointer = 3434 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]]; 3435 const PointerData& lastPointer = 3436 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]]; 3437 float deltaX = (currentPointer.x - lastPointer.x) 3438 * mLocked.pointerGestureXMovementScale; 3439 float deltaY = (currentPointer.y - lastPointer.y) 3440 * mLocked.pointerGestureYMovementScale; 3441 mPointerController->move(deltaX, deltaY); 3442 } 3443 } 3444 3445 float x, y; 3446 mPointerController->getPosition(&x, &y); 3447 3448 mPointerGesture.currentGestureMode = PointerGesture::CLICK_OR_DRAG; 3449 mPointerGesture.currentGesturePointerCount = 1; 3450 mPointerGesture.currentGestureIdBits.clear(); 3451 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); 3452 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; 3453 mPointerGesture.currentGestureCoords[0].clear(); 3454 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); 3455 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); 3456 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 3457 } else if (mCurrentTouch.pointerCount == 0) { 3458 // Case 3. No fingers down and button is not pressed. (NEUTRAL) 3459 *outFinishPreviousGesture = true; 3460 3461 // Watch for taps coming out of HOVER or INDETERMINATE_MULTITOUCH mode. 3462 bool tapped = false; 3463 if (mPointerGesture.lastGestureMode == PointerGesture::HOVER 3464 || mPointerGesture.lastGestureMode 3465 == PointerGesture::INDETERMINATE_MULTITOUCH) { 3466 if (when <= mPointerGesture.tapTime + TAP_INTERVAL) { 3467 float x, y; 3468 mPointerController->getPosition(&x, &y); 3469 if (fabs(x - mPointerGesture.initialPointerX) <= TAP_SLOP 3470 && fabs(y - mPointerGesture.initialPointerY) <= TAP_SLOP) { 3471#if DEBUG_GESTURES 3472 LOGD("Gestures: TAP"); 3473#endif 3474 mPointerGesture.activeGestureId = 0; 3475 mPointerGesture.currentGestureMode = PointerGesture::TAP; 3476 mPointerGesture.currentGesturePointerCount = 1; 3477 mPointerGesture.currentGestureIdBits.clear(); 3478 mPointerGesture.currentGestureIdBits.markBit( 3479 mPointerGesture.activeGestureId); 3480 mPointerGesture.currentGestureIdToIndex[ 3481 mPointerGesture.activeGestureId] = 0; 3482 mPointerGesture.currentGestureCoords[0].clear(); 3483 mPointerGesture.currentGestureCoords[0].setAxisValue( 3484 AMOTION_EVENT_AXIS_X, mPointerGesture.initialPointerX); 3485 mPointerGesture.currentGestureCoords[0].setAxisValue( 3486 AMOTION_EVENT_AXIS_Y, mPointerGesture.initialPointerY); 3487 mPointerGesture.currentGestureCoords[0].setAxisValue( 3488 AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 3489 tapped = true; 3490 } else { 3491#if DEBUG_GESTURES 3492 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", 3493 x - mPointerGesture.initialPointerX, 3494 y - mPointerGesture.initialPointerY); 3495#endif 3496 } 3497 } else { 3498#if DEBUG_GESTURES 3499 LOGD("Gestures: Not a TAP, delay=%lld", 3500 when - mPointerGesture.tapTime); 3501#endif 3502 } 3503 } 3504 if (!tapped) { 3505#if DEBUG_GESTURES 3506 LOGD("Gestures: NEUTRAL"); 3507#endif 3508 mPointerGesture.activeGestureId = -1; 3509 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL; 3510 mPointerGesture.currentGesturePointerCount = 0; 3511 mPointerGesture.currentGestureIdBits.clear(); 3512 } 3513 } else if (mCurrentTouch.pointerCount == 1) { 3514 // Case 4. Exactly one finger down, button is not pressed. (HOVER) 3515 // The pointer follows the active touch point. 3516 // Emit HOVER_MOVE events at the pointer location. 3517 assert(activeTouchId >= 0); 3518 3519#if DEBUG_GESTURES 3520 LOGD("Gestures: HOVER"); 3521#endif 3522 3523 if (mLastTouch.idBits.hasBit(activeTouchId)) { 3524 const PointerData& currentPointer = 3525 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]]; 3526 const PointerData& lastPointer = 3527 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]]; 3528 float deltaX = (currentPointer.x - lastPointer.x) 3529 * mLocked.pointerGestureXMovementScale; 3530 float deltaY = (currentPointer.y - lastPointer.y) 3531 * mLocked.pointerGestureYMovementScale; 3532 mPointerController->move(deltaX, deltaY); 3533 } 3534 3535 *outFinishPreviousGesture = true; 3536 mPointerGesture.activeGestureId = 0; 3537 3538 float x, y; 3539 mPointerController->getPosition(&x, &y); 3540 3541 mPointerGesture.currentGestureMode = PointerGesture::HOVER; 3542 mPointerGesture.currentGesturePointerCount = 1; 3543 mPointerGesture.currentGestureIdBits.clear(); 3544 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); 3545 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; 3546 mPointerGesture.currentGestureCoords[0].clear(); 3547 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); 3548 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); 3549 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f); 3550 3551 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) { 3552 mPointerGesture.tapTime = when; 3553 mPointerGesture.initialPointerX = x; 3554 mPointerGesture.initialPointerY = y; 3555 } 3556 } else { 3557 // Case 5. At least two fingers down, button is not pressed. (SWIPE or FREEFORM 3558 // or INDETERMINATE_MULTITOUCH) 3559 // Initially we watch and wait for something interesting to happen so as to 3560 // avoid making a spurious guess as to the nature of the gesture. For example, 3561 // the fingers may be in transition to some other state such as pressing or 3562 // releasing the button or we may be performing a two finger tap. 3563 // 3564 // Fix the centroid of the figure when the gesture actually starts. 3565 // We do not recalculate the centroid at any other time during the gesture because 3566 // it would affect the relationship of the touch points relative to the pointer location. 3567 assert(activeTouchId >= 0); 3568 3569 uint32_t currentTouchPointerCount = mCurrentTouch.pointerCount; 3570 if (currentTouchPointerCount > MAX_POINTERS) { 3571 currentTouchPointerCount = MAX_POINTERS; 3572 } 3573 3574 if (mPointerGesture.lastGestureMode != PointerGesture::INDETERMINATE_MULTITOUCH 3575 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE 3576 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { 3577 mPointerGesture.currentGestureMode = PointerGesture::INDETERMINATE_MULTITOUCH; 3578 3579 *outFinishPreviousGesture = true; 3580 mPointerGesture.activeGestureId = -1; 3581 3582 // Remember the initial pointer location. 3583 // Everything we do will be relative to this location. 3584 mPointerController->getPosition(&mPointerGesture.initialPointerX, 3585 &mPointerGesture.initialPointerY); 3586 3587 // Track taps. 3588 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) { 3589 mPointerGesture.tapTime = when; 3590 } 3591 3592 // Reset the touch origin to be relative to exactly where the fingers are now 3593 // in case they have moved some distance away as part of a previous gesture. 3594 // We want to know how far the fingers have traveled since we started considering 3595 // a multitouch gesture. 3596 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch); 3597 } else { 3598 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode; 3599 } 3600 3601 if (mPointerGesture.currentGestureMode == PointerGesture::INDETERMINATE_MULTITOUCH) { 3602 // Wait for the pointers to start moving before doing anything. 3603 bool decideNow = true; 3604 for (uint32_t i = 0; i < currentTouchPointerCount; i++) { 3605 const PointerData& current = mCurrentTouch.pointers[i]; 3606 const PointerData& origin = mPointerGesture.touchOrigin.pointers[ 3607 mPointerGesture.touchOrigin.idToIndex[current.id]]; 3608 float distance = pythag( 3609 (current.x - origin.x) * mLocked.pointerGestureXZoomScale, 3610 (current.y - origin.y) * mLocked.pointerGestureYZoomScale); 3611 if (distance < MULTITOUCH_MIN_TRAVEL) { 3612 decideNow = false; 3613 break; 3614 } 3615 } 3616 3617 if (decideNow) { 3618 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; 3619 if (currentTouchPointerCount == 2 3620 && distanceSquared( 3621 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y, 3622 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y) 3623 <= mLocked.pointerGestureMaxSwipeWidthSquared) { 3624 const PointerData& current1 = mCurrentTouch.pointers[0]; 3625 const PointerData& current2 = mCurrentTouch.pointers[1]; 3626 const PointerData& origin1 = mPointerGesture.touchOrigin.pointers[ 3627 mPointerGesture.touchOrigin.idToIndex[current1.id]]; 3628 const PointerData& origin2 = mPointerGesture.touchOrigin.pointers[ 3629 mPointerGesture.touchOrigin.idToIndex[current2.id]]; 3630 3631 float x1 = (current1.x - origin1.x) * mLocked.pointerGestureXZoomScale; 3632 float y1 = (current1.y - origin1.y) * mLocked.pointerGestureYZoomScale; 3633 float x2 = (current2.x - origin2.x) * mLocked.pointerGestureXZoomScale; 3634 float y2 = (current2.y - origin2.y) * mLocked.pointerGestureYZoomScale; 3635 float magnitude1 = pythag(x1, y1); 3636 float magnitude2 = pythag(x2, y2); 3637 3638 // Calculate the dot product of the vectors. 3639 // When the vectors are oriented in approximately the same direction, 3640 // the angle betweeen them is near zero and the cosine of the angle 3641 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2). 3642 // We know that the magnitude is at least MULTITOUCH_MIN_TRAVEL because 3643 // we checked it above. 3644 float dot = x1 * x2 + y1 * y2; 3645 float cosine = dot / (magnitude1 * magnitude2); // denominator always > 0 3646 if (cosine > SWIPE_TRANSITION_ANGLE_COSINE) { 3647 mPointerGesture.currentGestureMode = PointerGesture::SWIPE; 3648 } 3649 } 3650 3651 // Remember the initial centroid for the duration of the gesture. 3652 mPointerGesture.initialCentroidX = 0; 3653 mPointerGesture.initialCentroidY = 0; 3654 for (uint32_t i = 0; i < currentTouchPointerCount; i++) { 3655 const PointerData& touch = mCurrentTouch.pointers[i]; 3656 mPointerGesture.initialCentroidX += touch.x; 3657 mPointerGesture.initialCentroidY += touch.y; 3658 } 3659 mPointerGesture.initialCentroidX /= int32_t(currentTouchPointerCount); 3660 mPointerGesture.initialCentroidY /= int32_t(currentTouchPointerCount); 3661 3662 mPointerGesture.activeGestureId = 0; 3663 } 3664 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { 3665 // Switch to FREEFORM if additional pointers go down. 3666 if (currentTouchPointerCount > 2) { 3667 *outCancelPreviousGesture = true; 3668 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; 3669 } 3670 } 3671 3672 if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { 3673 // SWIPE mode. 3674#if DEBUG_GESTURES 3675 LOGD("Gestures: SWIPE activeTouchId=%d," 3676 "activeGestureId=%d, currentTouchPointerCount=%d", 3677 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount); 3678#endif 3679 assert(mPointerGesture.activeGestureId >= 0); 3680 3681 float x = (mCurrentTouch.pointers[0].x + mCurrentTouch.pointers[1].x 3682 - mPointerGesture.initialCentroidX * 2) * 0.5f 3683 * mLocked.pointerGestureXMovementScale + mPointerGesture.initialPointerX; 3684 float y = (mCurrentTouch.pointers[0].y + mCurrentTouch.pointers[1].y 3685 - mPointerGesture.initialCentroidY * 2) * 0.5f 3686 * mLocked.pointerGestureYMovementScale + mPointerGesture.initialPointerY; 3687 3688 mPointerGesture.currentGesturePointerCount = 1; 3689 mPointerGesture.currentGestureIdBits.clear(); 3690 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); 3691 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; 3692 mPointerGesture.currentGestureCoords[0].clear(); 3693 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); 3694 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); 3695 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 3696 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) { 3697 // FREEFORM mode. 3698#if DEBUG_GESTURES 3699 LOGD("Gestures: FREEFORM activeTouchId=%d," 3700 "activeGestureId=%d, currentTouchPointerCount=%d", 3701 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount); 3702#endif 3703 assert(mPointerGesture.activeGestureId >= 0); 3704 3705 mPointerGesture.currentGesturePointerCount = currentTouchPointerCount; 3706 mPointerGesture.currentGestureIdBits.clear(); 3707 3708 BitSet32 mappedTouchIdBits; 3709 BitSet32 usedGestureIdBits; 3710 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { 3711 // Initially, assign the active gesture id to the active touch point 3712 // if there is one. No other touch id bits are mapped yet. 3713 if (!*outCancelPreviousGesture) { 3714 mappedTouchIdBits.markBit(activeTouchId); 3715 usedGestureIdBits.markBit(mPointerGesture.activeGestureId); 3716 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] = 3717 mPointerGesture.activeGestureId; 3718 } else { 3719 mPointerGesture.activeGestureId = -1; 3720 } 3721 } else { 3722 // Otherwise, assume we mapped all touches from the previous frame. 3723 // Reuse all mappings that are still applicable. 3724 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value; 3725 usedGestureIdBits = mPointerGesture.lastGestureIdBits; 3726 3727 // Check whether we need to choose a new active gesture id because the 3728 // current went went up. 3729 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value); 3730 !upTouchIdBits.isEmpty(); ) { 3731 uint32_t upTouchId = upTouchIdBits.firstMarkedBit(); 3732 upTouchIdBits.clearBit(upTouchId); 3733 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId]; 3734 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) { 3735 mPointerGesture.activeGestureId = -1; 3736 break; 3737 } 3738 } 3739 } 3740 3741#if DEBUG_GESTURES 3742 LOGD("Gestures: FREEFORM follow up " 3743 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, " 3744 "activeGestureId=%d", 3745 mappedTouchIdBits.value, usedGestureIdBits.value, 3746 mPointerGesture.activeGestureId); 3747#endif 3748 3749 for (uint32_t i = 0; i < currentTouchPointerCount; i++) { 3750 uint32_t touchId = mCurrentTouch.pointers[i].id; 3751 uint32_t gestureId; 3752 if (!mappedTouchIdBits.hasBit(touchId)) { 3753 gestureId = usedGestureIdBits.firstUnmarkedBit(); 3754 usedGestureIdBits.markBit(gestureId); 3755 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId; 3756#if DEBUG_GESTURES 3757 LOGD("Gestures: FREEFORM " 3758 "new mapping for touch id %d -> gesture id %d", 3759 touchId, gestureId); 3760#endif 3761 } else { 3762 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId]; 3763#if DEBUG_GESTURES 3764 LOGD("Gestures: FREEFORM " 3765 "existing mapping for touch id %d -> gesture id %d", 3766 touchId, gestureId); 3767#endif 3768 } 3769 mPointerGesture.currentGestureIdBits.markBit(gestureId); 3770 mPointerGesture.currentGestureIdToIndex[gestureId] = i; 3771 3772 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.initialCentroidX) 3773 * mLocked.pointerGestureXZoomScale + mPointerGesture.initialPointerX; 3774 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.initialCentroidY) 3775 * mLocked.pointerGestureYZoomScale + mPointerGesture.initialPointerY; 3776 3777 mPointerGesture.currentGestureCoords[i].clear(); 3778 mPointerGesture.currentGestureCoords[i].setAxisValue( 3779 AMOTION_EVENT_AXIS_X, x); 3780 mPointerGesture.currentGestureCoords[i].setAxisValue( 3781 AMOTION_EVENT_AXIS_Y, y); 3782 mPointerGesture.currentGestureCoords[i].setAxisValue( 3783 AMOTION_EVENT_AXIS_PRESSURE, 1.0f); 3784 } 3785 3786 if (mPointerGesture.activeGestureId < 0) { 3787 mPointerGesture.activeGestureId = 3788 mPointerGesture.currentGestureIdBits.firstMarkedBit(); 3789#if DEBUG_GESTURES 3790 LOGD("Gestures: FREEFORM new " 3791 "activeGestureId=%d", mPointerGesture.activeGestureId); 3792#endif 3793 } 3794 } else { 3795 // INDETERMINATE_MULTITOUCH mode. 3796 // Do nothing. 3797#if DEBUG_GESTURES 3798 LOGD("Gestures: INDETERMINATE_MULTITOUCH"); 3799#endif 3800 } 3801 } 3802 3803 // Unfade the pointer if the user is doing anything with the touch pad. 3804 mPointerController->setButtonState(mCurrentTouch.buttonState); 3805 if (mCurrentTouch.buttonState || mCurrentTouch.pointerCount != 0) { 3806 mPointerController->unfade(); 3807 } 3808 3809#if DEBUG_GESTURES 3810 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, " 3811 "currentGestureMode=%d, currentGesturePointerCount=%d, currentGestureIdBits=0x%08x, " 3812 "lastGestureMode=%d, lastGesturePointerCount=%d, lastGestureIdBits=0x%08x", 3813 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture), 3814 mPointerGesture.currentGestureMode, mPointerGesture.currentGesturePointerCount, 3815 mPointerGesture.currentGestureIdBits.value, 3816 mPointerGesture.lastGestureMode, mPointerGesture.lastGesturePointerCount, 3817 mPointerGesture.lastGestureIdBits.value); 3818 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) { 3819 uint32_t id = idBits.firstMarkedBit(); 3820 idBits.clearBit(id); 3821 uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; 3822 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index]; 3823 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f", 3824 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X), 3825 coords.getAxisValue(AMOTION_EVENT_AXIS_Y), 3826 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); 3827 } 3828 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) { 3829 uint32_t id = idBits.firstMarkedBit(); 3830 idBits.clearBit(id); 3831 uint32_t index = mPointerGesture.lastGestureIdToIndex[id]; 3832 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index]; 3833 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f", 3834 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X), 3835 coords.getAxisValue(AMOTION_EVENT_AXIS_Y), 3836 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); 3837 } 3838#endif 3839} 3840 3841void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source, 3842 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags, 3843 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits, 3844 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) { 3845 PointerCoords pointerCoords[MAX_POINTERS]; 3846 int32_t pointerIds[MAX_POINTERS]; 3847 uint32_t pointerCount = 0; 3848 while (!idBits.isEmpty()) { 3849 uint32_t id = idBits.firstMarkedBit(); 3850 idBits.clearBit(id); 3851 uint32_t index = idToIndex[id]; 3852 pointerIds[pointerCount] = id; 3853 pointerCoords[pointerCount].copyFrom(coords[index]); 3854 3855 if (changedId >= 0 && id == uint32_t(changedId)) { 3856 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; 3857 } 3858 3859 pointerCount += 1; 3860 } 3861 3862 assert(pointerCount != 0); 3863 3864 if (changedId >= 0 && pointerCount == 1) { 3865 // Replace initial down and final up action. 3866 // We can compare the action without masking off the changed pointer index 3867 // because we know the index is 0. 3868 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) { 3869 action = AMOTION_EVENT_ACTION_DOWN; 3870 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) { 3871 action = AMOTION_EVENT_ACTION_UP; 3872 } else { 3873 // Can't happen. 3874 assert(false); 3875 } 3876 } 3877 3878 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags, 3879 action, flags, metaState, edgeFlags, 3880 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime); 3881} 3882 3883bool TouchInputMapper::updateMovedPointerCoords( 3884 const PointerCoords* inCoords, const uint32_t* inIdToIndex, 3885 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const { 3886 bool changed = false; 3887 while (!idBits.isEmpty()) { 3888 uint32_t id = idBits.firstMarkedBit(); 3889 idBits.clearBit(id); 3890 3891 uint32_t inIndex = inIdToIndex[id]; 3892 uint32_t outIndex = outIdToIndex[id]; 3893 const PointerCoords& curInCoords = inCoords[inIndex]; 3894 PointerCoords& curOutCoords = outCoords[outIndex]; 3895 3896 if (curInCoords != curOutCoords) { 3897 curOutCoords.copyFrom(curInCoords); 3898 changed = true; 3899 } 3900 } 3901 return changed; 3902} 3903 3904void TouchInputMapper::fadePointer() { 3905 { // acquire lock 3906 AutoMutex _l(mLock); 3907 if (mPointerController != NULL) { 3908 mPointerController->fade(); 3909 } 3910 } // release lock 3911} 3912 3913bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) { 3914 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue 3915 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue; 3916} 3917 3918const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked( 3919 int32_t x, int32_t y) { 3920 size_t numVirtualKeys = mLocked.virtualKeys.size(); 3921 for (size_t i = 0; i < numVirtualKeys; i++) { 3922 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 3923 3924#if DEBUG_VIRTUAL_KEYS 3925 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, " 3926 "left=%d, top=%d, right=%d, bottom=%d", 3927 x, y, 3928 virtualKey.keyCode, virtualKey.scanCode, 3929 virtualKey.hitLeft, virtualKey.hitTop, 3930 virtualKey.hitRight, virtualKey.hitBottom); 3931#endif 3932 3933 if (virtualKey.isHit(x, y)) { 3934 return & virtualKey; 3935 } 3936 } 3937 3938 return NULL; 3939} 3940 3941void TouchInputMapper::calculatePointerIds() { 3942 uint32_t currentPointerCount = mCurrentTouch.pointerCount; 3943 uint32_t lastPointerCount = mLastTouch.pointerCount; 3944 3945 if (currentPointerCount == 0) { 3946 // No pointers to assign. 3947 mCurrentTouch.idBits.clear(); 3948 } else if (lastPointerCount == 0) { 3949 // All pointers are new. 3950 mCurrentTouch.idBits.clear(); 3951 for (uint32_t i = 0; i < currentPointerCount; i++) { 3952 mCurrentTouch.pointers[i].id = i; 3953 mCurrentTouch.idToIndex[i] = i; 3954 mCurrentTouch.idBits.markBit(i); 3955 } 3956 } else if (currentPointerCount == 1 && lastPointerCount == 1) { 3957 // Only one pointer and no change in count so it must have the same id as before. 3958 uint32_t id = mLastTouch.pointers[0].id; 3959 mCurrentTouch.pointers[0].id = id; 3960 mCurrentTouch.idToIndex[id] = 0; 3961 mCurrentTouch.idBits.value = BitSet32::valueForBit(id); 3962 } else { 3963 // General case. 3964 // We build a heap of squared euclidean distances between current and last pointers 3965 // associated with the current and last pointer indices. Then, we find the best 3966 // match (by distance) for each current pointer. 3967 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS]; 3968 3969 uint32_t heapSize = 0; 3970 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount; 3971 currentPointerIndex++) { 3972 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount; 3973 lastPointerIndex++) { 3974 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x 3975 - mLastTouch.pointers[lastPointerIndex].x; 3976 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y 3977 - mLastTouch.pointers[lastPointerIndex].y; 3978 3979 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY); 3980 3981 // Insert new element into the heap (sift up). 3982 heap[heapSize].currentPointerIndex = currentPointerIndex; 3983 heap[heapSize].lastPointerIndex = lastPointerIndex; 3984 heap[heapSize].distance = distance; 3985 heapSize += 1; 3986 } 3987 } 3988 3989 // Heapify 3990 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) { 3991 startIndex -= 1; 3992 for (uint32_t parentIndex = startIndex; ;) { 3993 uint32_t childIndex = parentIndex * 2 + 1; 3994 if (childIndex >= heapSize) { 3995 break; 3996 } 3997 3998 if (childIndex + 1 < heapSize 3999 && heap[childIndex + 1].distance < heap[childIndex].distance) { 4000 childIndex += 1; 4001 } 4002 4003 if (heap[parentIndex].distance <= heap[childIndex].distance) { 4004 break; 4005 } 4006 4007 swap(heap[parentIndex], heap[childIndex]); 4008 parentIndex = childIndex; 4009 } 4010 } 4011 4012#if DEBUG_POINTER_ASSIGNMENT 4013 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize); 4014 for (size_t i = 0; i < heapSize; i++) { 4015 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", 4016 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, 4017 heap[i].distance); 4018 } 4019#endif 4020 4021 // Pull matches out by increasing order of distance. 4022 // To avoid reassigning pointers that have already been matched, the loop keeps track 4023 // of which last and current pointers have been matched using the matchedXXXBits variables. 4024 // It also tracks the used pointer id bits. 4025 BitSet32 matchedLastBits(0); 4026 BitSet32 matchedCurrentBits(0); 4027 BitSet32 usedIdBits(0); 4028 bool first = true; 4029 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) { 4030 for (;;) { 4031 if (first) { 4032 // The first time through the loop, we just consume the root element of 4033 // the heap (the one with smallest distance). 4034 first = false; 4035 } else { 4036 // Previous iterations consumed the root element of the heap. 4037 // Pop root element off of the heap (sift down). 4038 heapSize -= 1; 4039 assert(heapSize > 0); 4040 4041 // Sift down. 4042 heap[0] = heap[heapSize]; 4043 for (uint32_t parentIndex = 0; ;) { 4044 uint32_t childIndex = parentIndex * 2 + 1; 4045 if (childIndex >= heapSize) { 4046 break; 4047 } 4048 4049 if (childIndex + 1 < heapSize 4050 && heap[childIndex + 1].distance < heap[childIndex].distance) { 4051 childIndex += 1; 4052 } 4053 4054 if (heap[parentIndex].distance <= heap[childIndex].distance) { 4055 break; 4056 } 4057 4058 swap(heap[parentIndex], heap[childIndex]); 4059 parentIndex = childIndex; 4060 } 4061 4062#if DEBUG_POINTER_ASSIGNMENT 4063 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize); 4064 for (size_t i = 0; i < heapSize; i++) { 4065 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", 4066 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, 4067 heap[i].distance); 4068 } 4069#endif 4070 } 4071 4072 uint32_t currentPointerIndex = heap[0].currentPointerIndex; 4073 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched 4074 4075 uint32_t lastPointerIndex = heap[0].lastPointerIndex; 4076 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched 4077 4078 matchedCurrentBits.markBit(currentPointerIndex); 4079 matchedLastBits.markBit(lastPointerIndex); 4080 4081 uint32_t id = mLastTouch.pointers[lastPointerIndex].id; 4082 mCurrentTouch.pointers[currentPointerIndex].id = id; 4083 mCurrentTouch.idToIndex[id] = currentPointerIndex; 4084 usedIdBits.markBit(id); 4085 4086#if DEBUG_POINTER_ASSIGNMENT 4087 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld", 4088 lastPointerIndex, currentPointerIndex, id, heap[0].distance); 4089#endif 4090 break; 4091 } 4092 } 4093 4094 // Assign fresh ids to new pointers. 4095 if (currentPointerCount > lastPointerCount) { 4096 for (uint32_t i = currentPointerCount - lastPointerCount; ;) { 4097 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit(); 4098 uint32_t id = usedIdBits.firstUnmarkedBit(); 4099 4100 mCurrentTouch.pointers[currentPointerIndex].id = id; 4101 mCurrentTouch.idToIndex[id] = currentPointerIndex; 4102 usedIdBits.markBit(id); 4103 4104#if DEBUG_POINTER_ASSIGNMENT 4105 LOGD("calculatePointerIds - assigned: cur=%d, id=%d", 4106 currentPointerIndex, id); 4107#endif 4108 4109 if (--i == 0) break; // done 4110 matchedCurrentBits.markBit(currentPointerIndex); 4111 } 4112 } 4113 4114 // Fix id bits. 4115 mCurrentTouch.idBits = usedIdBits; 4116 } 4117} 4118 4119/* Special hack for devices that have bad screen data: if one of the 4120 * points has moved more than a screen height from the last position, 4121 * then drop it. */ 4122bool TouchInputMapper::applyBadTouchFilter() { 4123 uint32_t pointerCount = mCurrentTouch.pointerCount; 4124 4125 // Nothing to do if there are no points. 4126 if (pointerCount == 0) { 4127 return false; 4128 } 4129 4130 // Don't do anything if a finger is going down or up. We run 4131 // here before assigning pointer IDs, so there isn't a good 4132 // way to do per-finger matching. 4133 if (pointerCount != mLastTouch.pointerCount) { 4134 return false; 4135 } 4136 4137 // We consider a single movement across more than a 7/16 of 4138 // the long size of the screen to be bad. This was a magic value 4139 // determined by looking at the maximum distance it is feasible 4140 // to actually move in one sample. 4141 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16; 4142 4143 // XXX The original code in InputDevice.java included commented out 4144 // code for testing the X axis. Note that when we drop a point 4145 // we don't actually restore the old X either. Strange. 4146 // The old code also tries to track when bad points were previously 4147 // detected but it turns out that due to the placement of a "break" 4148 // at the end of the loop, we never set mDroppedBadPoint to true 4149 // so it is effectively dead code. 4150 // Need to figure out if the old code is busted or just overcomplicated 4151 // but working as intended. 4152 4153 // Look through all new points and see if any are farther than 4154 // acceptable from all previous points. 4155 for (uint32_t i = pointerCount; i-- > 0; ) { 4156 int32_t y = mCurrentTouch.pointers[i].y; 4157 int32_t closestY = INT_MAX; 4158 int32_t closestDeltaY = 0; 4159 4160#if DEBUG_HACKS 4161 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y); 4162#endif 4163 4164 for (uint32_t j = pointerCount; j-- > 0; ) { 4165 int32_t lastY = mLastTouch.pointers[j].y; 4166 int32_t deltaY = abs(y - lastY); 4167 4168#if DEBUG_HACKS 4169 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d", 4170 j, lastY, deltaY); 4171#endif 4172 4173 if (deltaY < maxDeltaY) { 4174 goto SkipSufficientlyClosePoint; 4175 } 4176 if (deltaY < closestDeltaY) { 4177 closestDeltaY = deltaY; 4178 closestY = lastY; 4179 } 4180 } 4181 4182 // Must not have found a close enough match. 4183#if DEBUG_HACKS 4184 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d", 4185 i, y, closestY, closestDeltaY, maxDeltaY); 4186#endif 4187 4188 mCurrentTouch.pointers[i].y = closestY; 4189 return true; // XXX original code only corrects one point 4190 4191 SkipSufficientlyClosePoint: ; 4192 } 4193 4194 // No change. 4195 return false; 4196} 4197 4198/* Special hack for devices that have bad screen data: drop points where 4199 * the coordinate value for one axis has jumped to the other pointer's location. 4200 */ 4201bool TouchInputMapper::applyJumpyTouchFilter() { 4202 uint32_t pointerCount = mCurrentTouch.pointerCount; 4203 if (mLastTouch.pointerCount != pointerCount) { 4204#if DEBUG_HACKS 4205 LOGD("JumpyTouchFilter: Different pointer count %d -> %d", 4206 mLastTouch.pointerCount, pointerCount); 4207 for (uint32_t i = 0; i < pointerCount; i++) { 4208 LOGD(" Pointer %d (%d, %d)", i, 4209 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y); 4210 } 4211#endif 4212 4213 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) { 4214 if (mLastTouch.pointerCount == 1 && pointerCount == 2) { 4215 // Just drop the first few events going from 1 to 2 pointers. 4216 // They're bad often enough that they're not worth considering. 4217 mCurrentTouch.pointerCount = 1; 4218 mJumpyTouchFilter.jumpyPointsDropped += 1; 4219 4220#if DEBUG_HACKS 4221 LOGD("JumpyTouchFilter: Pointer 2 dropped"); 4222#endif 4223 return true; 4224 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) { 4225 // The event when we go from 2 -> 1 tends to be messed up too 4226 mCurrentTouch.pointerCount = 2; 4227 mCurrentTouch.pointers[0] = mLastTouch.pointers[0]; 4228 mCurrentTouch.pointers[1] = mLastTouch.pointers[1]; 4229 mJumpyTouchFilter.jumpyPointsDropped += 1; 4230 4231#if DEBUG_HACKS 4232 for (int32_t i = 0; i < 2; i++) { 4233 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i, 4234 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y); 4235 } 4236#endif 4237 return true; 4238 } 4239 } 4240 // Reset jumpy points dropped on other transitions or if limit exceeded. 4241 mJumpyTouchFilter.jumpyPointsDropped = 0; 4242 4243#if DEBUG_HACKS 4244 LOGD("JumpyTouchFilter: Transition - drop limit reset"); 4245#endif 4246 return false; 4247 } 4248 4249 // We have the same number of pointers as last time. 4250 // A 'jumpy' point is one where the coordinate value for one axis 4251 // has jumped to the other pointer's location. No need to do anything 4252 // else if we only have one pointer. 4253 if (pointerCount < 2) { 4254 return false; 4255 } 4256 4257 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) { 4258 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR; 4259 4260 // We only replace the single worst jumpy point as characterized by pointer distance 4261 // in a single axis. 4262 int32_t badPointerIndex = -1; 4263 int32_t badPointerReplacementIndex = -1; 4264 int32_t badPointerDistance = INT_MIN; // distance to be corrected 4265 4266 for (uint32_t i = pointerCount; i-- > 0; ) { 4267 int32_t x = mCurrentTouch.pointers[i].x; 4268 int32_t y = mCurrentTouch.pointers[i].y; 4269 4270#if DEBUG_HACKS 4271 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y); 4272#endif 4273 4274 // Check if a touch point is too close to another's coordinates 4275 bool dropX = false, dropY = false; 4276 for (uint32_t j = 0; j < pointerCount; j++) { 4277 if (i == j) { 4278 continue; 4279 } 4280 4281 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) { 4282 dropX = true; 4283 break; 4284 } 4285 4286 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) { 4287 dropY = true; 4288 break; 4289 } 4290 } 4291 if (! dropX && ! dropY) { 4292 continue; // not jumpy 4293 } 4294 4295 // Find a replacement candidate by comparing with older points on the 4296 // complementary (non-jumpy) axis. 4297 int32_t distance = INT_MIN; // distance to be corrected 4298 int32_t replacementIndex = -1; 4299 4300 if (dropX) { 4301 // X looks too close. Find an older replacement point with a close Y. 4302 int32_t smallestDeltaY = INT_MAX; 4303 for (uint32_t j = 0; j < pointerCount; j++) { 4304 int32_t deltaY = abs(y - mLastTouch.pointers[j].y); 4305 if (deltaY < smallestDeltaY) { 4306 smallestDeltaY = deltaY; 4307 replacementIndex = j; 4308 } 4309 } 4310 distance = abs(x - mLastTouch.pointers[replacementIndex].x); 4311 } else { 4312 // Y looks too close. Find an older replacement point with a close X. 4313 int32_t smallestDeltaX = INT_MAX; 4314 for (uint32_t j = 0; j < pointerCount; j++) { 4315 int32_t deltaX = abs(x - mLastTouch.pointers[j].x); 4316 if (deltaX < smallestDeltaX) { 4317 smallestDeltaX = deltaX; 4318 replacementIndex = j; 4319 } 4320 } 4321 distance = abs(y - mLastTouch.pointers[replacementIndex].y); 4322 } 4323 4324 // If replacing this pointer would correct a worse error than the previous ones 4325 // considered, then use this replacement instead. 4326 if (distance > badPointerDistance) { 4327 badPointerIndex = i; 4328 badPointerReplacementIndex = replacementIndex; 4329 badPointerDistance = distance; 4330 } 4331 } 4332 4333 // Correct the jumpy pointer if one was found. 4334 if (badPointerIndex >= 0) { 4335#if DEBUG_HACKS 4336 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)", 4337 badPointerIndex, 4338 mLastTouch.pointers[badPointerReplacementIndex].x, 4339 mLastTouch.pointers[badPointerReplacementIndex].y); 4340#endif 4341 4342 mCurrentTouch.pointers[badPointerIndex].x = 4343 mLastTouch.pointers[badPointerReplacementIndex].x; 4344 mCurrentTouch.pointers[badPointerIndex].y = 4345 mLastTouch.pointers[badPointerReplacementIndex].y; 4346 mJumpyTouchFilter.jumpyPointsDropped += 1; 4347 return true; 4348 } 4349 } 4350 4351 mJumpyTouchFilter.jumpyPointsDropped = 0; 4352 return false; 4353} 4354 4355/* Special hack for devices that have bad screen data: aggregate and 4356 * compute averages of the coordinate data, to reduce the amount of 4357 * jitter seen by applications. */ 4358void TouchInputMapper::applyAveragingTouchFilter() { 4359 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) { 4360 uint32_t id = mCurrentTouch.pointers[currentIndex].id; 4361 int32_t x = mCurrentTouch.pointers[currentIndex].x; 4362 int32_t y = mCurrentTouch.pointers[currentIndex].y; 4363 int32_t pressure; 4364 switch (mCalibration.pressureSource) { 4365 case Calibration::PRESSURE_SOURCE_PRESSURE: 4366 pressure = mCurrentTouch.pointers[currentIndex].pressure; 4367 break; 4368 case Calibration::PRESSURE_SOURCE_TOUCH: 4369 pressure = mCurrentTouch.pointers[currentIndex].touchMajor; 4370 break; 4371 default: 4372 pressure = 1; 4373 break; 4374 } 4375 4376 if (mLastTouch.idBits.hasBit(id)) { 4377 // Pointer was down before and is still down now. 4378 // Compute average over history trace. 4379 uint32_t start = mAveragingTouchFilter.historyStart[id]; 4380 uint32_t end = mAveragingTouchFilter.historyEnd[id]; 4381 4382 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x; 4383 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y; 4384 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY); 4385 4386#if DEBUG_HACKS 4387 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld", 4388 id, distance); 4389#endif 4390 4391 if (distance < AVERAGING_DISTANCE_LIMIT) { 4392 // Increment end index in preparation for recording new historical data. 4393 end += 1; 4394 if (end > AVERAGING_HISTORY_SIZE) { 4395 end = 0; 4396 } 4397 4398 // If the end index has looped back to the start index then we have filled 4399 // the historical trace up to the desired size so we drop the historical 4400 // data at the start of the trace. 4401 if (end == start) { 4402 start += 1; 4403 if (start > AVERAGING_HISTORY_SIZE) { 4404 start = 0; 4405 } 4406 } 4407 4408 // Add the raw data to the historical trace. 4409 mAveragingTouchFilter.historyStart[id] = start; 4410 mAveragingTouchFilter.historyEnd[id] = end; 4411 mAveragingTouchFilter.historyData[end].pointers[id].x = x; 4412 mAveragingTouchFilter.historyData[end].pointers[id].y = y; 4413 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure; 4414 4415 // Average over all historical positions in the trace by total pressure. 4416 int32_t averagedX = 0; 4417 int32_t averagedY = 0; 4418 int32_t totalPressure = 0; 4419 for (;;) { 4420 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x; 4421 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y; 4422 int32_t historicalPressure = mAveragingTouchFilter.historyData[start] 4423 .pointers[id].pressure; 4424 4425 averagedX += historicalX * historicalPressure; 4426 averagedY += historicalY * historicalPressure; 4427 totalPressure += historicalPressure; 4428 4429 if (start == end) { 4430 break; 4431 } 4432 4433 start += 1; 4434 if (start > AVERAGING_HISTORY_SIZE) { 4435 start = 0; 4436 } 4437 } 4438 4439 if (totalPressure != 0) { 4440 averagedX /= totalPressure; 4441 averagedY /= totalPressure; 4442 4443#if DEBUG_HACKS 4444 LOGD("AveragingTouchFilter: Pointer id %d - " 4445 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure, 4446 averagedX, averagedY); 4447#endif 4448 4449 mCurrentTouch.pointers[currentIndex].x = averagedX; 4450 mCurrentTouch.pointers[currentIndex].y = averagedY; 4451 } 4452 } else { 4453#if DEBUG_HACKS 4454 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id); 4455#endif 4456 } 4457 } else { 4458#if DEBUG_HACKS 4459 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id); 4460#endif 4461 } 4462 4463 // Reset pointer history. 4464 mAveragingTouchFilter.historyStart[id] = 0; 4465 mAveragingTouchFilter.historyEnd[id] = 0; 4466 mAveragingTouchFilter.historyData[0].pointers[id].x = x; 4467 mAveragingTouchFilter.historyData[0].pointers[id].y = y; 4468 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure; 4469 } 4470} 4471 4472int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { 4473 { // acquire lock 4474 AutoMutex _l(mLock); 4475 4476 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) { 4477 return AKEY_STATE_VIRTUAL; 4478 } 4479 4480 size_t numVirtualKeys = mLocked.virtualKeys.size(); 4481 for (size_t i = 0; i < numVirtualKeys; i++) { 4482 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 4483 if (virtualKey.keyCode == keyCode) { 4484 return AKEY_STATE_UP; 4485 } 4486 } 4487 } // release lock 4488 4489 return AKEY_STATE_UNKNOWN; 4490} 4491 4492int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { 4493 { // acquire lock 4494 AutoMutex _l(mLock); 4495 4496 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) { 4497 return AKEY_STATE_VIRTUAL; 4498 } 4499 4500 size_t numVirtualKeys = mLocked.virtualKeys.size(); 4501 for (size_t i = 0; i < numVirtualKeys; i++) { 4502 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 4503 if (virtualKey.scanCode == scanCode) { 4504 return AKEY_STATE_UP; 4505 } 4506 } 4507 } // release lock 4508 4509 return AKEY_STATE_UNKNOWN; 4510} 4511 4512bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 4513 const int32_t* keyCodes, uint8_t* outFlags) { 4514 { // acquire lock 4515 AutoMutex _l(mLock); 4516 4517 size_t numVirtualKeys = mLocked.virtualKeys.size(); 4518 for (size_t i = 0; i < numVirtualKeys; i++) { 4519 const VirtualKey& virtualKey = mLocked.virtualKeys[i]; 4520 4521 for (size_t i = 0; i < numCodes; i++) { 4522 if (virtualKey.keyCode == keyCodes[i]) { 4523 outFlags[i] = 1; 4524 } 4525 } 4526 } 4527 } // release lock 4528 4529 return true; 4530} 4531 4532 4533// --- SingleTouchInputMapper --- 4534 4535SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) : 4536 TouchInputMapper(device) { 4537 initialize(); 4538} 4539 4540SingleTouchInputMapper::~SingleTouchInputMapper() { 4541} 4542 4543void SingleTouchInputMapper::initialize() { 4544 mAccumulator.clear(); 4545 4546 mDown = false; 4547 mX = 0; 4548 mY = 0; 4549 mPressure = 0; // default to 0 for devices that don't report pressure 4550 mToolWidth = 0; // default to 0 for devices that don't report tool width 4551 mButtonState = 0; 4552} 4553 4554void SingleTouchInputMapper::reset() { 4555 TouchInputMapper::reset(); 4556 4557 initialize(); 4558 } 4559 4560void SingleTouchInputMapper::process(const RawEvent* rawEvent) { 4561 switch (rawEvent->type) { 4562 case EV_KEY: 4563 switch (rawEvent->scanCode) { 4564 case BTN_TOUCH: 4565 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH; 4566 mAccumulator.btnTouch = rawEvent->value != 0; 4567 // Don't sync immediately. Wait until the next SYN_REPORT since we might 4568 // not have received valid position information yet. This logic assumes that 4569 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet. 4570 break; 4571 default: 4572 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) { 4573 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode); 4574 if (buttonState) { 4575 if (rawEvent->value) { 4576 mAccumulator.buttonDown |= buttonState; 4577 } else { 4578 mAccumulator.buttonUp |= buttonState; 4579 } 4580 mAccumulator.fields |= Accumulator::FIELD_BUTTONS; 4581 } 4582 } 4583 break; 4584 } 4585 break; 4586 4587 case EV_ABS: 4588 switch (rawEvent->scanCode) { 4589 case ABS_X: 4590 mAccumulator.fields |= Accumulator::FIELD_ABS_X; 4591 mAccumulator.absX = rawEvent->value; 4592 break; 4593 case ABS_Y: 4594 mAccumulator.fields |= Accumulator::FIELD_ABS_Y; 4595 mAccumulator.absY = rawEvent->value; 4596 break; 4597 case ABS_PRESSURE: 4598 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE; 4599 mAccumulator.absPressure = rawEvent->value; 4600 break; 4601 case ABS_TOOL_WIDTH: 4602 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH; 4603 mAccumulator.absToolWidth = rawEvent->value; 4604 break; 4605 } 4606 break; 4607 4608 case EV_SYN: 4609 switch (rawEvent->scanCode) { 4610 case SYN_REPORT: 4611 sync(rawEvent->when); 4612 break; 4613 } 4614 break; 4615 } 4616} 4617 4618void SingleTouchInputMapper::sync(nsecs_t when) { 4619 uint32_t fields = mAccumulator.fields; 4620 if (fields == 0) { 4621 return; // no new state changes, so nothing to do 4622 } 4623 4624 if (fields & Accumulator::FIELD_BTN_TOUCH) { 4625 mDown = mAccumulator.btnTouch; 4626 } 4627 4628 if (fields & Accumulator::FIELD_ABS_X) { 4629 mX = mAccumulator.absX; 4630 } 4631 4632 if (fields & Accumulator::FIELD_ABS_Y) { 4633 mY = mAccumulator.absY; 4634 } 4635 4636 if (fields & Accumulator::FIELD_ABS_PRESSURE) { 4637 mPressure = mAccumulator.absPressure; 4638 } 4639 4640 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) { 4641 mToolWidth = mAccumulator.absToolWidth; 4642 } 4643 4644 if (fields & Accumulator::FIELD_BUTTONS) { 4645 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp; 4646 } 4647 4648 mCurrentTouch.clear(); 4649 4650 if (mDown) { 4651 mCurrentTouch.pointerCount = 1; 4652 mCurrentTouch.pointers[0].id = 0; 4653 mCurrentTouch.pointers[0].x = mX; 4654 mCurrentTouch.pointers[0].y = mY; 4655 mCurrentTouch.pointers[0].pressure = mPressure; 4656 mCurrentTouch.pointers[0].touchMajor = 0; 4657 mCurrentTouch.pointers[0].touchMinor = 0; 4658 mCurrentTouch.pointers[0].toolMajor = mToolWidth; 4659 mCurrentTouch.pointers[0].toolMinor = mToolWidth; 4660 mCurrentTouch.pointers[0].orientation = 0; 4661 mCurrentTouch.idToIndex[0] = 0; 4662 mCurrentTouch.idBits.markBit(0); 4663 mCurrentTouch.buttonState = mButtonState; 4664 } 4665 4666 syncTouch(when, true); 4667 4668 mAccumulator.clear(); 4669} 4670 4671void SingleTouchInputMapper::configureRawAxes() { 4672 TouchInputMapper::configureRawAxes(); 4673 4674 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x); 4675 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y); 4676 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure); 4677 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor); 4678} 4679 4680 4681// --- MultiTouchInputMapper --- 4682 4683MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) : 4684 TouchInputMapper(device) { 4685 initialize(); 4686} 4687 4688MultiTouchInputMapper::~MultiTouchInputMapper() { 4689} 4690 4691void MultiTouchInputMapper::initialize() { 4692 mAccumulator.clear(); 4693 mButtonState = 0; 4694} 4695 4696void MultiTouchInputMapper::reset() { 4697 TouchInputMapper::reset(); 4698 4699 initialize(); 4700} 4701 4702void MultiTouchInputMapper::process(const RawEvent* rawEvent) { 4703 switch (rawEvent->type) { 4704 case EV_KEY: { 4705 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) { 4706 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode); 4707 if (buttonState) { 4708 if (rawEvent->value) { 4709 mAccumulator.buttonDown |= buttonState; 4710 } else { 4711 mAccumulator.buttonUp |= buttonState; 4712 } 4713 } 4714 } 4715 break; 4716 } 4717 4718 case EV_ABS: { 4719 uint32_t pointerIndex = mAccumulator.pointerCount; 4720 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex]; 4721 4722 switch (rawEvent->scanCode) { 4723 case ABS_MT_POSITION_X: 4724 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X; 4725 pointer->absMTPositionX = rawEvent->value; 4726 break; 4727 case ABS_MT_POSITION_Y: 4728 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y; 4729 pointer->absMTPositionY = rawEvent->value; 4730 break; 4731 case ABS_MT_TOUCH_MAJOR: 4732 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR; 4733 pointer->absMTTouchMajor = rawEvent->value; 4734 break; 4735 case ABS_MT_TOUCH_MINOR: 4736 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR; 4737 pointer->absMTTouchMinor = rawEvent->value; 4738 break; 4739 case ABS_MT_WIDTH_MAJOR: 4740 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR; 4741 pointer->absMTWidthMajor = rawEvent->value; 4742 break; 4743 case ABS_MT_WIDTH_MINOR: 4744 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR; 4745 pointer->absMTWidthMinor = rawEvent->value; 4746 break; 4747 case ABS_MT_ORIENTATION: 4748 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION; 4749 pointer->absMTOrientation = rawEvent->value; 4750 break; 4751 case ABS_MT_TRACKING_ID: 4752 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID; 4753 pointer->absMTTrackingId = rawEvent->value; 4754 break; 4755 case ABS_MT_PRESSURE: 4756 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE; 4757 pointer->absMTPressure = rawEvent->value; 4758 break; 4759 } 4760 break; 4761 } 4762 4763 case EV_SYN: 4764 switch (rawEvent->scanCode) { 4765 case SYN_MT_REPORT: { 4766 // MultiTouch Sync: The driver has returned all data for *one* of the pointers. 4767 uint32_t pointerIndex = mAccumulator.pointerCount; 4768 4769 if (mAccumulator.pointers[pointerIndex].fields) { 4770 if (pointerIndex == MAX_POINTERS) { 4771 LOGW("MultiTouch device driver returned more than maximum of %d pointers.", 4772 MAX_POINTERS); 4773 } else { 4774 pointerIndex += 1; 4775 mAccumulator.pointerCount = pointerIndex; 4776 } 4777 } 4778 4779 mAccumulator.pointers[pointerIndex].clear(); 4780 break; 4781 } 4782 4783 case SYN_REPORT: 4784 sync(rawEvent->when); 4785 break; 4786 } 4787 break; 4788 } 4789} 4790 4791void MultiTouchInputMapper::sync(nsecs_t when) { 4792 static const uint32_t REQUIRED_FIELDS = 4793 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y; 4794 4795 uint32_t inCount = mAccumulator.pointerCount; 4796 uint32_t outCount = 0; 4797 bool havePointerIds = true; 4798 4799 mCurrentTouch.clear(); 4800 4801 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) { 4802 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex]; 4803 uint32_t fields = inPointer.fields; 4804 4805 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) { 4806 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up. 4807 // Drop this finger. 4808 continue; 4809 } 4810 4811 PointerData& outPointer = mCurrentTouch.pointers[outCount]; 4812 outPointer.x = inPointer.absMTPositionX; 4813 outPointer.y = inPointer.absMTPositionY; 4814 4815 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) { 4816 if (inPointer.absMTPressure <= 0) { 4817 // Some devices send sync packets with X / Y but with a 0 pressure to indicate 4818 // a pointer going up. Drop this finger. 4819 continue; 4820 } 4821 outPointer.pressure = inPointer.absMTPressure; 4822 } else { 4823 // Default pressure to 0 if absent. 4824 outPointer.pressure = 0; 4825 } 4826 4827 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) { 4828 if (inPointer.absMTTouchMajor <= 0) { 4829 // Some devices send sync packets with X / Y but with a 0 touch major to indicate 4830 // a pointer going up. Drop this finger. 4831 continue; 4832 } 4833 outPointer.touchMajor = inPointer.absMTTouchMajor; 4834 } else { 4835 // Default touch area to 0 if absent. 4836 outPointer.touchMajor = 0; 4837 } 4838 4839 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) { 4840 outPointer.touchMinor = inPointer.absMTTouchMinor; 4841 } else { 4842 // Assume touch area is circular. 4843 outPointer.touchMinor = outPointer.touchMajor; 4844 } 4845 4846 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) { 4847 outPointer.toolMajor = inPointer.absMTWidthMajor; 4848 } else { 4849 // Default tool area to 0 if absent. 4850 outPointer.toolMajor = 0; 4851 } 4852 4853 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) { 4854 outPointer.toolMinor = inPointer.absMTWidthMinor; 4855 } else { 4856 // Assume tool area is circular. 4857 outPointer.toolMinor = outPointer.toolMajor; 4858 } 4859 4860 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) { 4861 outPointer.orientation = inPointer.absMTOrientation; 4862 } else { 4863 // Default orientation to vertical if absent. 4864 outPointer.orientation = 0; 4865 } 4866 4867 // Assign pointer id using tracking id if available. 4868 if (havePointerIds) { 4869 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) { 4870 uint32_t id = uint32_t(inPointer.absMTTrackingId); 4871 4872 if (id > MAX_POINTER_ID) { 4873#if DEBUG_POINTERS 4874 LOGD("Pointers: Ignoring driver provided pointer id %d because " 4875 "it is larger than max supported id %d", 4876 id, MAX_POINTER_ID); 4877#endif 4878 havePointerIds = false; 4879 } 4880 else { 4881 outPointer.id = id; 4882 mCurrentTouch.idToIndex[id] = outCount; 4883 mCurrentTouch.idBits.markBit(id); 4884 } 4885 } else { 4886 havePointerIds = false; 4887 } 4888 } 4889 4890 outCount += 1; 4891 } 4892 4893 mCurrentTouch.pointerCount = outCount; 4894 4895 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp; 4896 mCurrentTouch.buttonState = mButtonState; 4897 4898 syncTouch(when, havePointerIds); 4899 4900 mAccumulator.clear(); 4901} 4902 4903void MultiTouchInputMapper::configureRawAxes() { 4904 TouchInputMapper::configureRawAxes(); 4905 4906 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x); 4907 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y); 4908 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor); 4909 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor); 4910 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor); 4911 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor); 4912 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation); 4913 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure); 4914} 4915 4916 4917// --- JoystickInputMapper --- 4918 4919JoystickInputMapper::JoystickInputMapper(InputDevice* device) : 4920 InputMapper(device) { 4921} 4922 4923JoystickInputMapper::~JoystickInputMapper() { 4924} 4925 4926uint32_t JoystickInputMapper::getSources() { 4927 return AINPUT_SOURCE_JOYSTICK; 4928} 4929 4930void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) { 4931 InputMapper::populateDeviceInfo(info); 4932 4933 for (size_t i = 0; i < mAxes.size(); i++) { 4934 const Axis& axis = mAxes.valueAt(i); 4935 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK, 4936 axis.min, axis.max, axis.flat, axis.fuzz); 4937 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 4938 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK, 4939 axis.min, axis.max, axis.flat, axis.fuzz); 4940 } 4941 } 4942} 4943 4944void JoystickInputMapper::dump(String8& dump) { 4945 dump.append(INDENT2 "Joystick Input Mapper:\n"); 4946 4947 dump.append(INDENT3 "Axes:\n"); 4948 size_t numAxes = mAxes.size(); 4949 for (size_t i = 0; i < numAxes; i++) { 4950 const Axis& axis = mAxes.valueAt(i); 4951 const char* label = getAxisLabel(axis.axisInfo.axis); 4952 if (label) { 4953 dump.appendFormat(INDENT4 "%s", label); 4954 } else { 4955 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis); 4956 } 4957 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 4958 label = getAxisLabel(axis.axisInfo.highAxis); 4959 if (label) { 4960 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue); 4961 } else { 4962 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis, 4963 axis.axisInfo.splitValue); 4964 } 4965 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) { 4966 dump.append(" (invert)"); 4967 } 4968 4969 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n", 4970 axis.min, axis.max, axis.flat, axis.fuzz); 4971 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, " 4972 "highScale=%0.5f, highOffset=%0.5f\n", 4973 axis.scale, axis.offset, axis.highScale, axis.highOffset); 4974 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n", 4975 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue, 4976 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz); 4977 } 4978} 4979 4980void JoystickInputMapper::configure() { 4981 InputMapper::configure(); 4982 4983 // Collect all axes. 4984 for (int32_t abs = 0; abs <= ABS_MAX; abs++) { 4985 RawAbsoluteAxisInfo rawAxisInfo; 4986 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo); 4987 if (rawAxisInfo.valid) { 4988 // Map axis. 4989 AxisInfo axisInfo; 4990 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo); 4991 if (!explicitlyMapped) { 4992 // Axis is not explicitly mapped, will choose a generic axis later. 4993 axisInfo.mode = AxisInfo::MODE_NORMAL; 4994 axisInfo.axis = -1; 4995 } 4996 4997 // Apply flat override. 4998 int32_t rawFlat = axisInfo.flatOverride < 0 4999 ? rawAxisInfo.flat : axisInfo.flatOverride; 5000 5001 // Calculate scaling factors and limits. 5002 Axis axis; 5003 if (axisInfo.mode == AxisInfo::MODE_SPLIT) { 5004 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue); 5005 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue); 5006 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 5007 scale, 0.0f, highScale, 0.0f, 5008 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 5009 } else if (isCenteredAxis(axisInfo.axis)) { 5010 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); 5011 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale; 5012 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 5013 scale, offset, scale, offset, 5014 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 5015 } else { 5016 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); 5017 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, 5018 scale, 0.0f, scale, 0.0f, 5019 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale); 5020 } 5021 5022 // To eliminate noise while the joystick is at rest, filter out small variations 5023 // in axis values up front. 5024 axis.filter = axis.flat * 0.25f; 5025 5026 mAxes.add(abs, axis); 5027 } 5028 } 5029 5030 // If there are too many axes, start dropping them. 5031 // Prefer to keep explicitly mapped axes. 5032 if (mAxes.size() > PointerCoords::MAX_AXES) { 5033 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.", 5034 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES); 5035 pruneAxes(true); 5036 pruneAxes(false); 5037 } 5038 5039 // Assign generic axis ids to remaining axes. 5040 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1; 5041 size_t numAxes = mAxes.size(); 5042 for (size_t i = 0; i < numAxes; i++) { 5043 Axis& axis = mAxes.editValueAt(i); 5044 if (axis.axisInfo.axis < 0) { 5045 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 5046 && haveAxis(nextGenericAxisId)) { 5047 nextGenericAxisId += 1; 5048 } 5049 5050 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) { 5051 axis.axisInfo.axis = nextGenericAxisId; 5052 nextGenericAxisId += 1; 5053 } else { 5054 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids " 5055 "have already been assigned to other axes.", 5056 getDeviceName().string(), mAxes.keyAt(i)); 5057 mAxes.removeItemsAt(i--); 5058 numAxes -= 1; 5059 } 5060 } 5061 } 5062} 5063 5064bool JoystickInputMapper::haveAxis(int32_t axisId) { 5065 size_t numAxes = mAxes.size(); 5066 for (size_t i = 0; i < numAxes; i++) { 5067 const Axis& axis = mAxes.valueAt(i); 5068 if (axis.axisInfo.axis == axisId 5069 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT 5070 && axis.axisInfo.highAxis == axisId)) { 5071 return true; 5072 } 5073 } 5074 return false; 5075} 5076 5077void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) { 5078 size_t i = mAxes.size(); 5079 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) { 5080 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) { 5081 continue; 5082 } 5083 LOGI("Discarding joystick '%s' axis %d because there are too many axes.", 5084 getDeviceName().string(), mAxes.keyAt(i)); 5085 mAxes.removeItemsAt(i); 5086 } 5087} 5088 5089bool JoystickInputMapper::isCenteredAxis(int32_t axis) { 5090 switch (axis) { 5091 case AMOTION_EVENT_AXIS_X: 5092 case AMOTION_EVENT_AXIS_Y: 5093 case AMOTION_EVENT_AXIS_Z: 5094 case AMOTION_EVENT_AXIS_RX: 5095 case AMOTION_EVENT_AXIS_RY: 5096 case AMOTION_EVENT_AXIS_RZ: 5097 case AMOTION_EVENT_AXIS_HAT_X: 5098 case AMOTION_EVENT_AXIS_HAT_Y: 5099 case AMOTION_EVENT_AXIS_ORIENTATION: 5100 case AMOTION_EVENT_AXIS_RUDDER: 5101 case AMOTION_EVENT_AXIS_WHEEL: 5102 return true; 5103 default: 5104 return false; 5105 } 5106} 5107 5108void JoystickInputMapper::reset() { 5109 // Recenter all axes. 5110 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC); 5111 5112 size_t numAxes = mAxes.size(); 5113 for (size_t i = 0; i < numAxes; i++) { 5114 Axis& axis = mAxes.editValueAt(i); 5115 axis.resetValue(); 5116 } 5117 5118 sync(when, true /*force*/); 5119 5120 InputMapper::reset(); 5121} 5122 5123void JoystickInputMapper::process(const RawEvent* rawEvent) { 5124 switch (rawEvent->type) { 5125 case EV_ABS: { 5126 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode); 5127 if (index >= 0) { 5128 Axis& axis = mAxes.editValueAt(index); 5129 float newValue, highNewValue; 5130 switch (axis.axisInfo.mode) { 5131 case AxisInfo::MODE_INVERT: 5132 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) 5133 * axis.scale + axis.offset; 5134 highNewValue = 0.0f; 5135 break; 5136 case AxisInfo::MODE_SPLIT: 5137 if (rawEvent->value < axis.axisInfo.splitValue) { 5138 newValue = (axis.axisInfo.splitValue - rawEvent->value) 5139 * axis.scale + axis.offset; 5140 highNewValue = 0.0f; 5141 } else if (rawEvent->value > axis.axisInfo.splitValue) { 5142 newValue = 0.0f; 5143 highNewValue = (rawEvent->value - axis.axisInfo.splitValue) 5144 * axis.highScale + axis.highOffset; 5145 } else { 5146 newValue = 0.0f; 5147 highNewValue = 0.0f; 5148 } 5149 break; 5150 default: 5151 newValue = rawEvent->value * axis.scale + axis.offset; 5152 highNewValue = 0.0f; 5153 break; 5154 } 5155 axis.newValue = newValue; 5156 axis.highNewValue = highNewValue; 5157 } 5158 break; 5159 } 5160 5161 case EV_SYN: 5162 switch (rawEvent->scanCode) { 5163 case SYN_REPORT: 5164 sync(rawEvent->when, false /*force*/); 5165 break; 5166 } 5167 break; 5168 } 5169} 5170 5171void JoystickInputMapper::sync(nsecs_t when, bool force) { 5172 if (!filterAxes(force)) { 5173 return; 5174 } 5175 5176 int32_t metaState = mContext->getGlobalMetaState(); 5177 5178 PointerCoords pointerCoords; 5179 pointerCoords.clear(); 5180 5181 size_t numAxes = mAxes.size(); 5182 for (size_t i = 0; i < numAxes; i++) { 5183 const Axis& axis = mAxes.valueAt(i); 5184 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue); 5185 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 5186 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue); 5187 } 5188 } 5189 5190 // Moving a joystick axis should not wake the devide because joysticks can 5191 // be fairly noisy even when not in use. On the other hand, pushing a gamepad 5192 // button will likely wake the device. 5193 // TODO: Use the input device configuration to control this behavior more finely. 5194 uint32_t policyFlags = 0; 5195 5196 int32_t pointerId = 0; 5197 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags, 5198 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE, 5199 1, &pointerId, &pointerCoords, 0, 0, 0); 5200} 5201 5202bool JoystickInputMapper::filterAxes(bool force) { 5203 bool atLeastOneSignificantChange = force; 5204 size_t numAxes = mAxes.size(); 5205 for (size_t i = 0; i < numAxes; i++) { 5206 Axis& axis = mAxes.editValueAt(i); 5207 if (force || hasValueChangedSignificantly(axis.filter, 5208 axis.newValue, axis.currentValue, axis.min, axis.max)) { 5209 axis.currentValue = axis.newValue; 5210 atLeastOneSignificantChange = true; 5211 } 5212 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { 5213 if (force || hasValueChangedSignificantly(axis.filter, 5214 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) { 5215 axis.highCurrentValue = axis.highNewValue; 5216 atLeastOneSignificantChange = true; 5217 } 5218 } 5219 } 5220 return atLeastOneSignificantChange; 5221} 5222 5223bool JoystickInputMapper::hasValueChangedSignificantly( 5224 float filter, float newValue, float currentValue, float min, float max) { 5225 if (newValue != currentValue) { 5226 // Filter out small changes in value unless the value is converging on the axis 5227 // bounds or center point. This is intended to reduce the amount of information 5228 // sent to applications by particularly noisy joysticks (such as PS3). 5229 if (fabs(newValue - currentValue) > filter 5230 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) 5231 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) 5232 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) { 5233 return true; 5234 } 5235 } 5236 return false; 5237} 5238 5239bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange( 5240 float filter, float newValue, float currentValue, float thresholdValue) { 5241 float newDistance = fabs(newValue - thresholdValue); 5242 if (newDistance < filter) { 5243 float oldDistance = fabs(currentValue - thresholdValue); 5244 if (newDistance < oldDistance) { 5245 return true; 5246 } 5247 } 5248 return false; 5249} 5250 5251} // namespace android 5252