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