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