2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "InputReader"
19 //#define LOG_NDEBUG 0
21 // Log debug messages for each raw event received from the EventHub.
22 #define DEBUG_RAW_EVENTS 0
24 // Log debug messages about touch screen filtering hacks.
27 // Log debug messages about virtual key processing.
28 #define DEBUG_VIRTUAL_KEYS 0
30 // Log debug messages about pointers.
31 #define DEBUG_POINTERS 0
33 // Log debug messages about pointer assignment calculations.
34 #define DEBUG_POINTER_ASSIGNMENT 0
36 // Log debug messages about gesture detection.
37 #define DEBUG_GESTURES 0
39 // Log debug messages about the vibrator.
40 #define DEBUG_VIBRATOR 0
42 #include "InputReader.h"
44 #include <cutils/log.h>
45 #include <input/Keyboard.h>
46 #include <input/VirtualKeyMap.h>
65 // Maximum number of slots supported when using the slot-based Multitouch Protocol B.
66 static const size_t MAX_SLOTS = 32;
68 // --- Static Functions ---
71 inline static T abs(const T& value) {
72 return value < 0 ? - value : value;
76 inline static T min(const T& a, const T& b) {
81 inline static void swap(T& a, T& b) {
87 inline static float avg(float x, float y) {
91 inline static float distance(float x1, float y1, float x2, float y2) {
92 return hypotf(x1 - x2, y1 - y2);
95 inline static int32_t signExtendNybble(int32_t value) {
96 return value >= 8 ? value - 16 : value;
99 static inline const char* toString(bool value) {
100 return value ? "true" : "false";
103 static 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];
115 static 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 },
123 static const size_t keyCodeRotationMapSize =
124 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
126 static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
127 return rotateValueUsingRotationMap(keyCode, orientation,
128 keyCodeRotationMap, keyCodeRotationMapSize);
131 static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
133 switch (orientation) {
134 case DISPLAY_ORIENTATION_90:
140 case DISPLAY_ORIENTATION_180:
145 case DISPLAY_ORIENTATION_270:
153 static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
154 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
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.
159 static bool isPointerDown(int32_t buttonState) {
161 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
162 | AMOTION_EVENT_BUTTON_TERTIARY);
165 static 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;
175 static 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) {
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);
192 static 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);
204 // --- InputReaderConfiguration ---
206 bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const {
207 const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay;
208 if (viewport.displayId >= 0) {
209 *outViewport = viewport;
215 void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) {
216 DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay;
221 // -- TouchAffineTransformation --
222 void TouchAffineTransformation::applyTo(float& x, float& y) const {
224 newX = x * x_scale + y * x_ymix + x_offset;
225 newY = x * y_xmix + y * y_scale + y_offset;
232 // --- InputReader ---
234 InputReader::InputReader(const sp<EventHubInterface>& eventHub,
235 const sp<InputReaderPolicyInterface>& policy,
236 const sp<InputListenerInterface>& listener) :
237 mContext(this), mEventHub(eventHub), mPolicy(policy),
238 mGlobalMetaState(0), mGeneration(1),
239 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
240 mConfigurationChangesToRefresh(0) {
241 mQueuedListener = new QueuedInputListener(listener);
246 refreshConfigurationLocked(0);
247 updateGlobalMetaStateLocked();
251 InputReader::~InputReader() {
252 for (size_t i = 0; i < mDevices.size(); i++) {
253 delete mDevices.valueAt(i);
257 void InputReader::loopOnce() {
258 int32_t oldGeneration;
259 int32_t timeoutMillis;
260 bool inputDevicesChanged = false;
261 Vector<InputDeviceInfo> inputDevices;
265 oldGeneration = mGeneration;
268 uint32_t changes = mConfigurationChangesToRefresh;
270 mConfigurationChangesToRefresh = 0;
272 refreshConfigurationLocked(changes);
273 } else if (mNextTimeout != LLONG_MAX) {
274 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
275 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
279 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
283 mReaderIsAliveCondition.broadcast();
286 processEventsLocked(mEventBuffer, count);
289 if (mNextTimeout != LLONG_MAX) {
290 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
291 if (now >= mNextTimeout) {
293 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
295 mNextTimeout = LLONG_MAX;
296 timeoutExpiredLocked(now);
300 if (oldGeneration != mGeneration) {
301 inputDevicesChanged = true;
302 getInputDevicesLocked(inputDevices);
306 // Send out a message that the describes the changed input devices.
307 if (inputDevicesChanged) {
308 mPolicy->notifyInputDevicesChanged(inputDevices);
311 // Flush queued events out to the listener.
312 // This must happen outside of the lock because the listener could potentially call
313 // back into the InputReader's methods, such as getScanCodeState, or become blocked
314 // on another thread similarly waiting to acquire the InputReader lock thereby
315 // resulting in a deadlock. This situation is actually quite plausible because the
316 // listener is actually the input dispatcher, which calls into the window manager,
317 // which occasionally calls into the input reader.
318 mQueuedListener->flush();
321 void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
322 for (const RawEvent* rawEvent = rawEvents; count;) {
323 int32_t type = rawEvent->type;
324 size_t batchSize = 1;
325 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
326 int32_t deviceId = rawEvent->deviceId;
327 while (batchSize < count) {
328 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
329 || rawEvent[batchSize].deviceId != deviceId) {
335 ALOGD("BatchSize: %d Count: %d", batchSize, count);
337 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
339 switch (rawEvent->type) {
340 case EventHubInterface::DEVICE_ADDED:
341 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
343 case EventHubInterface::DEVICE_REMOVED:
344 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
346 case EventHubInterface::FINISHED_DEVICE_SCAN:
347 handleConfigurationChangedLocked(rawEvent->when);
350 ALOG_ASSERT(false); // can't happen
355 rawEvent += batchSize;
359 void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
360 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
361 if (deviceIndex >= 0) {
362 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
366 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
367 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
368 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
370 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
371 device->configure(when, &mConfig, 0);
374 if (device->isIgnored()) {
375 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
376 identifier.name.string());
378 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
379 identifier.name.string(), device->getSources());
382 mDevices.add(deviceId, device);
383 bumpGenerationLocked();
386 void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
387 InputDevice* device = NULL;
388 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
389 if (deviceIndex < 0) {
390 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
394 device = mDevices.valueAt(deviceIndex);
395 mDevices.removeItemsAt(deviceIndex, 1);
396 bumpGenerationLocked();
398 if (device->isIgnored()) {
399 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
400 device->getId(), device->getName().string());
402 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
403 device->getId(), device->getName().string(), device->getSources());
410 InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
411 const InputDeviceIdentifier& identifier, uint32_t classes) {
412 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
413 controllerNumber, identifier, classes);
416 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
417 device->setExternal(true);
420 // Switch-like devices.
421 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
422 device->addMapper(new SwitchInputMapper(device));
425 // Vibrator-like devices.
426 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
427 device->addMapper(new VibratorInputMapper(device));
430 // Keyboard-like devices.
431 uint32_t keyboardSource = 0;
432 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
433 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
434 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
436 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
437 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
439 if (classes & INPUT_DEVICE_CLASS_DPAD) {
440 keyboardSource |= AINPUT_SOURCE_DPAD;
442 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
443 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
446 if (keyboardSource != 0) {
447 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
450 // Cursor-like devices.
451 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
452 device->addMapper(new CursorInputMapper(device));
455 // Touchscreens and touchpad devices.
456 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
457 device->addMapper(new MultiTouchInputMapper(device));
458 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
459 device->addMapper(new SingleTouchInputMapper(device));
462 // Joystick-like devices.
463 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
464 device->addMapper(new JoystickInputMapper(device));
470 void InputReader::processEventsForDeviceLocked(int32_t deviceId,
471 const RawEvent* rawEvents, size_t count) {
472 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
473 if (deviceIndex < 0) {
474 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
478 InputDevice* device = mDevices.valueAt(deviceIndex);
479 if (device->isIgnored()) {
480 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
484 device->process(rawEvents, count);
487 void InputReader::timeoutExpiredLocked(nsecs_t when) {
488 for (size_t i = 0; i < mDevices.size(); i++) {
489 InputDevice* device = mDevices.valueAt(i);
490 if (!device->isIgnored()) {
491 device->timeoutExpired(when);
496 void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
497 // Reset global meta state because it depends on the list of all configured devices.
498 updateGlobalMetaStateLocked();
500 // Enqueue configuration changed.
501 NotifyConfigurationChangedArgs args(when);
502 mQueuedListener->notifyConfigurationChanged(&args);
505 void InputReader::refreshConfigurationLocked(uint32_t changes) {
506 mPolicy->getReaderConfiguration(&mConfig);
507 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
510 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
511 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
513 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
514 mEventHub->requestReopenDevices();
516 for (size_t i = 0; i < mDevices.size(); i++) {
517 InputDevice* device = mDevices.valueAt(i);
518 device->configure(now, &mConfig, changes);
524 void InputReader::updateGlobalMetaStateLocked() {
525 mGlobalMetaState = 0;
527 for (size_t i = 0; i < mDevices.size(); i++) {
528 InputDevice* device = mDevices.valueAt(i);
529 mGlobalMetaState |= device->getMetaState();
533 int32_t InputReader::getGlobalMetaStateLocked() {
534 return mGlobalMetaState;
537 void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
538 mDisableVirtualKeysTimeout = time;
541 bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
542 InputDevice* device, int32_t keyCode, int32_t scanCode) {
543 if (now < mDisableVirtualKeysTimeout) {
544 ALOGI("Dropping virtual key from device %s because virtual keys are "
545 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
546 device->getName().string(),
547 (mDisableVirtualKeysTimeout - now) * 0.000001,
555 void InputReader::fadePointerLocked() {
556 for (size_t i = 0; i < mDevices.size(); i++) {
557 InputDevice* device = mDevices.valueAt(i);
558 device->fadePointer();
562 void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
563 if (when < mNextTimeout) {
569 int32_t InputReader::bumpGenerationLocked() {
570 return ++mGeneration;
573 void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
575 getInputDevicesLocked(outInputDevices);
578 void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
579 outInputDevices.clear();
581 size_t numDevices = mDevices.size();
582 for (size_t i = 0; i < numDevices; i++) {
583 InputDevice* device = mDevices.valueAt(i);
584 if (!device->isIgnored()) {
585 outInputDevices.push();
586 device->getDeviceInfo(&outInputDevices.editTop());
591 int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
595 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
598 int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
602 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
605 int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
608 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
611 int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
612 GetStateFunc getStateFunc) {
613 int32_t result = AKEY_STATE_UNKNOWN;
615 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
616 if (deviceIndex >= 0) {
617 InputDevice* device = mDevices.valueAt(deviceIndex);
618 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
619 result = (device->*getStateFunc)(sourceMask, code);
623 size_t numDevices = mDevices.size();
624 for (size_t i = 0; i < numDevices; i++) {
625 InputDevice* device = mDevices.valueAt(i);
626 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
627 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
628 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
629 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
630 if (currentResult >= AKEY_STATE_DOWN) {
631 return currentResult;
632 } else if (currentResult == AKEY_STATE_UP) {
633 result = currentResult;
641 bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
642 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
645 memset(outFlags, 0, numCodes);
646 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
649 bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
650 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
653 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
654 if (deviceIndex >= 0) {
655 InputDevice* device = mDevices.valueAt(deviceIndex);
656 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
657 result = device->markSupportedKeyCodes(sourceMask,
658 numCodes, keyCodes, outFlags);
662 size_t numDevices = mDevices.size();
663 for (size_t i = 0; i < numDevices; i++) {
664 InputDevice* device = mDevices.valueAt(i);
665 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
666 result |= device->markSupportedKeyCodes(sourceMask,
667 numCodes, keyCodes, outFlags);
674 void InputReader::requestRefreshConfiguration(uint32_t changes) {
678 bool needWake = !mConfigurationChangesToRefresh;
679 mConfigurationChangesToRefresh |= changes;
687 void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
688 ssize_t repeat, int32_t token) {
691 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
692 if (deviceIndex >= 0) {
693 InputDevice* device = mDevices.valueAt(deviceIndex);
694 device->vibrate(pattern, patternSize, repeat, token);
698 void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
701 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
702 if (deviceIndex >= 0) {
703 InputDevice* device = mDevices.valueAt(deviceIndex);
704 device->cancelVibrate(token);
708 void InputReader::dump(String8& dump) {
711 mEventHub->dump(dump);
714 dump.append("Input Reader State:\n");
716 for (size_t i = 0; i < mDevices.size(); i++) {
717 mDevices.valueAt(i)->dump(dump);
720 dump.append(INDENT "Configuration:\n");
721 dump.append(INDENT2 "ExcludedDeviceNames: [");
722 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
726 dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
729 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
730 mConfig.virtualKeyQuietTime * 0.000001f);
732 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
733 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
734 mConfig.pointerVelocityControlParameters.scale,
735 mConfig.pointerVelocityControlParameters.lowThreshold,
736 mConfig.pointerVelocityControlParameters.highThreshold,
737 mConfig.pointerVelocityControlParameters.acceleration);
739 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
740 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
741 mConfig.wheelVelocityControlParameters.scale,
742 mConfig.wheelVelocityControlParameters.lowThreshold,
743 mConfig.wheelVelocityControlParameters.highThreshold,
744 mConfig.wheelVelocityControlParameters.acceleration);
746 dump.appendFormat(INDENT2 "PointerGesture:\n");
747 dump.appendFormat(INDENT3 "Enabled: %s\n",
748 toString(mConfig.pointerGesturesEnabled));
749 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
750 mConfig.pointerGestureQuietInterval * 0.000001f);
751 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
752 mConfig.pointerGestureDragMinSwitchSpeed);
753 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
754 mConfig.pointerGestureTapInterval * 0.000001f);
755 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
756 mConfig.pointerGestureTapDragInterval * 0.000001f);
757 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
758 mConfig.pointerGestureTapSlop);
759 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
760 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
761 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
762 mConfig.pointerGestureMultitouchMinDistance);
763 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
764 mConfig.pointerGestureSwipeTransitionAngleCosine);
765 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
766 mConfig.pointerGestureSwipeMaxWidthRatio);
767 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
768 mConfig.pointerGestureMovementSpeedRatio);
769 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
770 mConfig.pointerGestureZoomSpeedRatio);
773 void InputReader::monitor() {
774 // Acquire and release the lock to ensure that the reader has not deadlocked.
777 mReaderIsAliveCondition.wait(mLock);
780 // Check the EventHub
781 mEventHub->monitor();
785 // --- InputReader::ContextImpl ---
787 InputReader::ContextImpl::ContextImpl(InputReader* reader) :
791 void InputReader::ContextImpl::updateGlobalMetaState() {
792 // lock is already held by the input loop
793 mReader->updateGlobalMetaStateLocked();
796 int32_t InputReader::ContextImpl::getGlobalMetaState() {
797 // lock is already held by the input loop
798 return mReader->getGlobalMetaStateLocked();
801 void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
802 // lock is already held by the input loop
803 mReader->disableVirtualKeysUntilLocked(time);
806 bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
807 InputDevice* device, int32_t keyCode, int32_t scanCode) {
808 // lock is already held by the input loop
809 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
812 void InputReader::ContextImpl::fadePointer() {
813 // lock is already held by the input loop
814 mReader->fadePointerLocked();
817 void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
818 // lock is already held by the input loop
819 mReader->requestTimeoutAtTimeLocked(when);
822 int32_t InputReader::ContextImpl::bumpGeneration() {
823 // lock is already held by the input loop
824 return mReader->bumpGenerationLocked();
827 InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
828 return mReader->mPolicy.get();
831 InputListenerInterface* InputReader::ContextImpl::getListener() {
832 return mReader->mQueuedListener.get();
835 EventHubInterface* InputReader::ContextImpl::getEventHub() {
836 return mReader->mEventHub.get();
840 // --- InputReaderThread ---
842 InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
843 Thread(/*canCallJava*/ true), mReader(reader) {
846 InputReaderThread::~InputReaderThread() {
849 bool InputReaderThread::threadLoop() {
855 // --- InputDevice ---
857 InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
858 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
859 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
860 mIdentifier(identifier), mClasses(classes),
861 mSources(0), mIsExternal(false), mDropUntilNextSync(false) {
864 InputDevice::~InputDevice() {
865 size_t numMappers = mMappers.size();
866 for (size_t i = 0; i < numMappers; i++) {
872 void InputDevice::dump(String8& dump) {
873 InputDeviceInfo deviceInfo;
874 getDeviceInfo(& deviceInfo);
876 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
877 deviceInfo.getDisplayName().string());
878 dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
879 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
880 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
881 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
883 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
884 if (!ranges.isEmpty()) {
885 dump.append(INDENT2 "Motion Ranges:\n");
886 for (size_t i = 0; i < ranges.size(); i++) {
887 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
888 const char* label = getAxisLabel(range.axis);
891 strncpy(name, label, sizeof(name));
892 name[sizeof(name) - 1] = '\0';
894 snprintf(name, sizeof(name), "%d", range.axis);
896 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
897 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
898 name, range.source, range.min, range.max, range.flat, range.fuzz,
903 size_t numMappers = mMappers.size();
904 for (size_t i = 0; i < numMappers; i++) {
905 InputMapper* mapper = mMappers[i];
910 void InputDevice::addMapper(InputMapper* mapper) {
911 mMappers.add(mapper);
914 void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
918 if (!changes) { // first time only
919 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
922 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
923 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
924 sp<KeyCharacterMap> keyboardLayout =
925 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
926 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
932 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
933 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
934 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
935 if (mAlias != alias) {
942 size_t numMappers = mMappers.size();
943 for (size_t i = 0; i < numMappers; i++) {
944 InputMapper* mapper = mMappers[i];
945 mapper->configure(when, config, changes);
946 mSources |= mapper->getSources();
951 void InputDevice::reset(nsecs_t when) {
952 size_t numMappers = mMappers.size();
953 for (size_t i = 0; i < numMappers; i++) {
954 InputMapper* mapper = mMappers[i];
958 mContext->updateGlobalMetaState();
963 void InputDevice::process(const RawEvent* rawEvents, size_t count) {
964 // Process all of the events in order for each mapper.
965 // We cannot simply ask each mapper to process them in bulk because mappers may
966 // have side-effects that must be interleaved. For example, joystick movement events and
967 // gamepad button presses are handled by different mappers but they should be dispatched
968 // in the order received.
969 size_t numMappers = mMappers.size();
970 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
972 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
973 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
977 if (mDropUntilNextSync) {
978 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
979 mDropUntilNextSync = false;
981 ALOGD("Recovered from input event buffer overrun.");
985 ALOGD("Dropped input event while waiting for next input sync.");
988 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
989 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
990 mDropUntilNextSync = true;
991 reset(rawEvent->when);
993 for (size_t i = 0; i < numMappers; i++) {
994 InputMapper* mapper = mMappers[i];
995 mapper->process(rawEvent);
1001 void InputDevice::timeoutExpired(nsecs_t when) {
1002 size_t numMappers = mMappers.size();
1003 for (size_t i = 0; i < numMappers; i++) {
1004 InputMapper* mapper = mMappers[i];
1005 mapper->timeoutExpired(when);
1009 void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1010 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
1013 size_t numMappers = mMappers.size();
1014 for (size_t i = 0; i < numMappers; i++) {
1015 InputMapper* mapper = mMappers[i];
1016 mapper->populateDeviceInfo(outDeviceInfo);
1020 int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1021 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1024 int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1025 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1028 int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1029 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1032 int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1033 int32_t result = AKEY_STATE_UNKNOWN;
1034 size_t numMappers = mMappers.size();
1035 for (size_t i = 0; i < numMappers; i++) {
1036 InputMapper* mapper = mMappers[i];
1037 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1038 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1039 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1040 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1041 if (currentResult >= AKEY_STATE_DOWN) {
1042 return currentResult;
1043 } else if (currentResult == AKEY_STATE_UP) {
1044 result = currentResult;
1051 bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1052 const int32_t* keyCodes, uint8_t* outFlags) {
1053 bool result = false;
1054 size_t numMappers = mMappers.size();
1055 for (size_t i = 0; i < numMappers; i++) {
1056 InputMapper* mapper = mMappers[i];
1057 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1058 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1064 void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1066 size_t numMappers = mMappers.size();
1067 for (size_t i = 0; i < numMappers; i++) {
1068 InputMapper* mapper = mMappers[i];
1069 mapper->vibrate(pattern, patternSize, repeat, token);
1073 void InputDevice::cancelVibrate(int32_t token) {
1074 size_t numMappers = mMappers.size();
1075 for (size_t i = 0; i < numMappers; i++) {
1076 InputMapper* mapper = mMappers[i];
1077 mapper->cancelVibrate(token);
1081 int32_t InputDevice::getMetaState() {
1083 size_t numMappers = mMappers.size();
1084 for (size_t i = 0; i < numMappers; i++) {
1085 InputMapper* mapper = mMappers[i];
1086 result |= mapper->getMetaState();
1091 void InputDevice::fadePointer() {
1092 size_t numMappers = mMappers.size();
1093 for (size_t i = 0; i < numMappers; i++) {
1094 InputMapper* mapper = mMappers[i];
1095 mapper->fadePointer();
1099 void InputDevice::bumpGeneration() {
1100 mGeneration = mContext->bumpGeneration();
1103 void InputDevice::notifyReset(nsecs_t when) {
1104 NotifyDeviceResetArgs args(when, mId);
1105 mContext->getListener()->notifyDeviceReset(&args);
1109 // --- CursorButtonAccumulator ---
1111 CursorButtonAccumulator::CursorButtonAccumulator() {
1115 void CursorButtonAccumulator::reset(InputDevice* device) {
1116 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1117 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1118 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1119 mBtnBack = device->isKeyPressed(BTN_BACK);
1120 mBtnSide = device->isKeyPressed(BTN_SIDE);
1121 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1122 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1123 mBtnTask = device->isKeyPressed(BTN_TASK);
1126 void CursorButtonAccumulator::clearButtons() {
1137 void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1138 if (rawEvent->type == EV_KEY) {
1139 switch (rawEvent->code) {
1141 mBtnLeft = rawEvent->value;
1144 mBtnRight = rawEvent->value;
1147 mBtnMiddle = rawEvent->value;
1150 mBtnBack = rawEvent->value;
1153 mBtnSide = rawEvent->value;
1156 mBtnForward = rawEvent->value;
1159 mBtnExtra = rawEvent->value;
1162 mBtnTask = rawEvent->value;
1168 uint32_t CursorButtonAccumulator::getButtonState() const {
1169 uint32_t result = 0;
1171 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1174 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1177 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1179 if (mBtnBack || mBtnSide) {
1180 result |= AMOTION_EVENT_BUTTON_BACK;
1182 if (mBtnForward || mBtnExtra) {
1183 result |= AMOTION_EVENT_BUTTON_FORWARD;
1189 // --- CursorMotionAccumulator ---
1191 CursorMotionAccumulator::CursorMotionAccumulator() {
1192 clearRelativeAxes();
1195 void CursorMotionAccumulator::reset(InputDevice* device) {
1196 clearRelativeAxes();
1199 void CursorMotionAccumulator::clearRelativeAxes() {
1204 void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1205 if (rawEvent->type == EV_REL) {
1206 switch (rawEvent->code) {
1208 mRelX = rawEvent->value;
1211 mRelY = rawEvent->value;
1217 void CursorMotionAccumulator::finishSync() {
1218 clearRelativeAxes();
1222 // --- CursorScrollAccumulator ---
1224 CursorScrollAccumulator::CursorScrollAccumulator() :
1225 mHaveRelWheel(false), mHaveRelHWheel(false) {
1226 clearRelativeAxes();
1229 void CursorScrollAccumulator::configure(InputDevice* device) {
1230 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1231 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1234 void CursorScrollAccumulator::reset(InputDevice* device) {
1235 clearRelativeAxes();
1238 void CursorScrollAccumulator::clearRelativeAxes() {
1243 void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1244 if (rawEvent->type == EV_REL) {
1245 switch (rawEvent->code) {
1247 mRelWheel = rawEvent->value;
1250 mRelHWheel = rawEvent->value;
1256 void CursorScrollAccumulator::finishSync() {
1257 clearRelativeAxes();
1261 // --- TouchButtonAccumulator ---
1263 TouchButtonAccumulator::TouchButtonAccumulator() :
1264 mHaveBtnTouch(false), mHaveStylus(false) {
1268 void TouchButtonAccumulator::configure(InputDevice* device) {
1269 mHaveBtnTouch = device->hasKey(BTN_TOUCH) || device->hasKey(BTN_LEFT);
1270 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1271 || device->hasKey(BTN_TOOL_RUBBER)
1272 || device->hasKey(BTN_TOOL_BRUSH)
1273 || device->hasKey(BTN_TOOL_PENCIL)
1274 || device->hasKey(BTN_TOOL_AIRBRUSH);
1277 void TouchButtonAccumulator::reset(InputDevice* device) {
1278 mBtnTouch = device->isKeyPressed(BTN_TOUCH) || device->isKeyPressed(BTN_LEFT);
1279 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
1280 mBtnStylus2 = device->isKeyPressed(BTN_STYLUS);
1281 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1282 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1283 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1284 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1285 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1286 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1287 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1288 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1289 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1290 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1291 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1294 void TouchButtonAccumulator::clearButtons() {
1303 mBtnToolAirbrush = 0;
1306 mBtnToolDoubleTap = 0;
1307 mBtnToolTripleTap = 0;
1308 mBtnToolQuadTap = 0;
1311 void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1312 if (rawEvent->type == EV_KEY) {
1313 switch (rawEvent->code) {
1316 mBtnTouch = rawEvent->value;
1319 mBtnStylus = rawEvent->value;
1322 mBtnStylus2 = rawEvent->value;
1324 case BTN_TOOL_FINGER:
1325 mBtnToolFinger = rawEvent->value;
1328 mBtnToolPen = rawEvent->value;
1330 case BTN_TOOL_RUBBER:
1331 mBtnToolRubber = rawEvent->value;
1333 case BTN_TOOL_BRUSH:
1334 mBtnToolBrush = rawEvent->value;
1336 case BTN_TOOL_PENCIL:
1337 mBtnToolPencil = rawEvent->value;
1339 case BTN_TOOL_AIRBRUSH:
1340 mBtnToolAirbrush = rawEvent->value;
1342 case BTN_TOOL_MOUSE:
1343 mBtnToolMouse = rawEvent->value;
1346 mBtnToolLens = rawEvent->value;
1348 case BTN_TOOL_DOUBLETAP:
1349 mBtnToolDoubleTap = rawEvent->value;
1351 case BTN_TOOL_TRIPLETAP:
1352 mBtnToolTripleTap = rawEvent->value;
1354 case BTN_TOOL_QUADTAP:
1355 mBtnToolQuadTap = rawEvent->value;
1361 uint32_t TouchButtonAccumulator::getButtonState() const {
1362 uint32_t result = 0;
1364 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1367 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1372 int32_t TouchButtonAccumulator::getToolType() const {
1373 if (mBtnToolMouse || mBtnToolLens) {
1374 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1376 if (mBtnToolRubber) {
1377 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1379 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1380 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1382 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1383 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1385 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1388 bool TouchButtonAccumulator::isToolActive() const {
1389 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1390 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1391 || mBtnToolMouse || mBtnToolLens
1392 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1395 bool TouchButtonAccumulator::isHovering() const {
1396 return mHaveBtnTouch && !mBtnTouch;
1399 bool TouchButtonAccumulator::hasStylus() const {
1404 // --- RawPointerAxes ---
1406 RawPointerAxes::RawPointerAxes() {
1410 void RawPointerAxes::clear() {
1418 orientation.clear();
1427 // --- RawPointerData ---
1429 RawPointerData::RawPointerData() {
1433 void RawPointerData::clear() {
1438 void RawPointerData::copyFrom(const RawPointerData& other) {
1439 pointerCount = other.pointerCount;
1440 hoveringIdBits = other.hoveringIdBits;
1441 touchingIdBits = other.touchingIdBits;
1443 for (uint32_t i = 0; i < pointerCount; i++) {
1444 pointers[i] = other.pointers[i];
1446 int id = pointers[i].id;
1447 idToIndex[id] = other.idToIndex[id];
1451 void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1453 uint32_t count = touchingIdBits.count();
1455 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1456 uint32_t id = idBits.clearFirstMarkedBit();
1457 const Pointer& pointer = pointerForId(id);
1469 // --- CookedPointerData ---
1471 CookedPointerData::CookedPointerData() {
1475 void CookedPointerData::clear() {
1477 hoveringIdBits.clear();
1478 touchingIdBits.clear();
1481 void CookedPointerData::copyFrom(const CookedPointerData& other) {
1482 pointerCount = other.pointerCount;
1483 hoveringIdBits = other.hoveringIdBits;
1484 touchingIdBits = other.touchingIdBits;
1486 for (uint32_t i = 0; i < pointerCount; i++) {
1487 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1488 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1490 int id = pointerProperties[i].id;
1491 idToIndex[id] = other.idToIndex[id];
1496 // --- SingleTouchMotionAccumulator ---
1498 SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1499 clearAbsoluteAxes();
1502 void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1503 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1504 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1505 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1506 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1507 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1508 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1509 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1512 void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1522 void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1523 if (rawEvent->type == EV_ABS) {
1524 switch (rawEvent->code) {
1526 mAbsX = rawEvent->value;
1529 mAbsY = rawEvent->value;
1532 mAbsPressure = rawEvent->value;
1534 case ABS_TOOL_WIDTH:
1535 mAbsToolWidth = rawEvent->value;
1538 mAbsDistance = rawEvent->value;
1541 mAbsTiltX = rawEvent->value;
1544 mAbsTiltY = rawEvent->value;
1551 // --- MultiTouchMotionAccumulator ---
1553 MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1554 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1555 mHaveStylus(false) {
1558 MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1562 void MultiTouchMotionAccumulator::configure(InputDevice* device,
1563 size_t slotCount, bool usingSlotsProtocol) {
1564 mSlotCount = slotCount;
1565 mUsingSlotsProtocol = usingSlotsProtocol;
1566 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1569 mSlots = new Slot[slotCount];
1572 void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1573 // Unfortunately there is no way to read the initial contents of the slots.
1574 // So when we reset the accumulator, we must assume they are all zeroes.
1575 if (mUsingSlotsProtocol) {
1576 // Query the driver for the current slot index and use it as the initial slot
1577 // before we start reading events from the device. It is possible that the
1578 // current slot index will not be the same as it was when the first event was
1579 // written into the evdev buffer, which means the input mapper could start
1580 // out of sync with the initial state of the events in the evdev buffer.
1581 // In the extremely unlikely case that this happens, the data from
1582 // two slots will be confused until the next ABS_MT_SLOT event is received.
1583 // This can cause the touch point to "jump", but at least there will be
1584 // no stuck touches.
1585 int32_t initialSlot;
1586 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1587 ABS_MT_SLOT, &initialSlot);
1589 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1592 clearSlots(initialSlot);
1598 void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1600 for (size_t i = 0; i < mSlotCount; i++) {
1604 mCurrentSlot = initialSlot;
1607 void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1608 if (rawEvent->type == EV_ABS) {
1609 bool newSlot = false;
1610 if (mUsingSlotsProtocol) {
1611 if (rawEvent->code == ABS_MT_SLOT) {
1612 mCurrentSlot = rawEvent->value;
1615 } else if (mCurrentSlot < 0) {
1619 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1622 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1623 "should be between 0 and %d; ignoring this slot.",
1624 mCurrentSlot, mSlotCount - 1);
1628 Slot* slot = &mSlots[mCurrentSlot];
1630 switch (rawEvent->code) {
1631 case ABS_MT_POSITION_X:
1632 slot->mInUse = true;
1633 slot->mAbsMTPositionX = rawEvent->value;
1635 case ABS_MT_POSITION_Y:
1636 slot->mInUse = true;
1637 slot->mAbsMTPositionY = rawEvent->value;
1639 case ABS_MT_TOUCH_MAJOR:
1640 slot->mInUse = true;
1641 slot->mAbsMTTouchMajor = rawEvent->value;
1643 case ABS_MT_TOUCH_MINOR:
1644 slot->mInUse = true;
1645 slot->mAbsMTTouchMinor = rawEvent->value;
1646 slot->mHaveAbsMTTouchMinor = true;
1648 case ABS_MT_WIDTH_MAJOR:
1649 slot->mInUse = true;
1650 slot->mAbsMTWidthMajor = rawEvent->value;
1652 case ABS_MT_WIDTH_MINOR:
1653 slot->mInUse = true;
1654 slot->mAbsMTWidthMinor = rawEvent->value;
1655 slot->mHaveAbsMTWidthMinor = true;
1657 case ABS_MT_ORIENTATION:
1658 slot->mInUse = true;
1659 slot->mAbsMTOrientation = rawEvent->value;
1661 case ABS_MT_TRACKING_ID:
1662 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1663 // The slot is no longer in use but it retains its previous contents,
1664 // which may be reused for subsequent touches.
1665 slot->mInUse = false;
1667 slot->mInUse = true;
1668 slot->mAbsMTTrackingId = rawEvent->value;
1671 case ABS_MT_PRESSURE:
1672 slot->mInUse = true;
1673 slot->mAbsMTPressure = rawEvent->value;
1675 case ABS_MT_DISTANCE:
1676 slot->mInUse = true;
1677 slot->mAbsMTDistance = rawEvent->value;
1679 case ABS_MT_TOOL_TYPE:
1680 slot->mInUse = true;
1681 slot->mAbsMTToolType = rawEvent->value;
1682 slot->mHaveAbsMTToolType = true;
1686 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1687 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1692 void MultiTouchMotionAccumulator::finishSync() {
1693 if (!mUsingSlotsProtocol) {
1698 bool MultiTouchMotionAccumulator::hasStylus() const {
1703 // --- MultiTouchMotionAccumulator::Slot ---
1705 MultiTouchMotionAccumulator::Slot::Slot() {
1709 void MultiTouchMotionAccumulator::Slot::clear() {
1711 mHaveAbsMTTouchMinor = false;
1712 mHaveAbsMTWidthMinor = false;
1713 mHaveAbsMTToolType = false;
1714 mAbsMTPositionX = 0;
1715 mAbsMTPositionY = 0;
1716 mAbsMTTouchMajor = 0;
1717 mAbsMTTouchMinor = 0;
1718 mAbsMTWidthMajor = 0;
1719 mAbsMTWidthMinor = 0;
1720 mAbsMTOrientation = 0;
1721 mAbsMTTrackingId = -1;
1727 int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1728 if (mHaveAbsMTToolType) {
1729 switch (mAbsMTToolType) {
1730 case MT_TOOL_FINGER:
1731 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1733 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1736 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1740 // --- InputMapper ---
1742 InputMapper::InputMapper(InputDevice* device) :
1743 mDevice(device), mContext(device->getContext()) {
1746 InputMapper::~InputMapper() {
1749 void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1750 info->addSource(getSources());
1753 void InputMapper::dump(String8& dump) {
1756 void InputMapper::configure(nsecs_t when,
1757 const InputReaderConfiguration* config, uint32_t changes) {
1760 void InputMapper::reset(nsecs_t when) {
1763 void InputMapper::timeoutExpired(nsecs_t when) {
1766 int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1767 return AKEY_STATE_UNKNOWN;
1770 int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1771 return AKEY_STATE_UNKNOWN;
1774 int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1775 return AKEY_STATE_UNKNOWN;
1778 bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1779 const int32_t* keyCodes, uint8_t* outFlags) {
1783 void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1787 void InputMapper::cancelVibrate(int32_t token) {
1790 int32_t InputMapper::getMetaState() {
1794 void InputMapper::fadePointer() {
1797 status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1798 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1801 void InputMapper::bumpGeneration() {
1802 mDevice->bumpGeneration();
1805 void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
1806 const RawAbsoluteAxisInfo& axis, const char* name) {
1808 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
1809 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1811 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1816 // --- SwitchInputMapper ---
1818 SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
1819 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
1822 SwitchInputMapper::~SwitchInputMapper() {
1825 uint32_t SwitchInputMapper::getSources() {
1826 return AINPUT_SOURCE_SWITCH;
1829 void SwitchInputMapper::process(const RawEvent* rawEvent) {
1830 switch (rawEvent->type) {
1832 processSwitch(rawEvent->code, rawEvent->value);
1836 if (rawEvent->code == SYN_REPORT) {
1837 sync(rawEvent->when);
1842 void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
1843 if (switchCode >= 0 && switchCode < 32) {
1845 mSwitchValues |= 1 << switchCode;
1847 mSwitchValues &= ~(1 << switchCode);
1849 mUpdatedSwitchMask |= 1 << switchCode;
1853 void SwitchInputMapper::sync(nsecs_t when) {
1854 if (mUpdatedSwitchMask) {
1855 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
1856 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
1857 getListener()->notifySwitch(&args);
1859 mUpdatedSwitchMask = 0;
1863 int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1864 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1867 void SwitchInputMapper::dump(String8& dump) {
1868 dump.append(INDENT2 "Switch Input Mapper:\n");
1869 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
1872 // --- VibratorInputMapper ---
1874 VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
1875 InputMapper(device), mVibrating(false) {
1878 VibratorInputMapper::~VibratorInputMapper() {
1881 uint32_t VibratorInputMapper::getSources() {
1885 void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1886 InputMapper::populateDeviceInfo(info);
1888 info->setVibrator(true);
1891 void VibratorInputMapper::process(const RawEvent* rawEvent) {
1892 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
1895 void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1899 for (size_t i = 0; i < patternSize; i++) {
1901 patternStr.append(", ");
1903 patternStr.appendFormat("%lld", pattern[i]);
1905 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
1906 getDeviceId(), patternStr.string(), repeat, token);
1910 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
1911 mPatternSize = patternSize;
1919 void VibratorInputMapper::cancelVibrate(int32_t token) {
1921 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
1924 if (mVibrating && mToken == token) {
1929 void VibratorInputMapper::timeoutExpired(nsecs_t when) {
1931 if (when >= mNextStepTime) {
1934 getContext()->requestTimeoutAtTime(mNextStepTime);
1939 void VibratorInputMapper::nextStep() {
1941 if (size_t(mIndex) >= mPatternSize) {
1950 bool vibratorOn = mIndex & 1;
1951 nsecs_t duration = mPattern[mIndex];
1954 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
1955 getDeviceId(), duration);
1957 getEventHub()->vibrate(getDeviceId(), duration);
1960 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
1962 getEventHub()->cancelVibrate(getDeviceId());
1964 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1965 mNextStepTime = now + duration;
1966 getContext()->requestTimeoutAtTime(mNextStepTime);
1968 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
1972 void VibratorInputMapper::stopVibrating() {
1975 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
1977 getEventHub()->cancelVibrate(getDeviceId());
1980 void VibratorInputMapper::dump(String8& dump) {
1981 dump.append(INDENT2 "Vibrator Input Mapper:\n");
1982 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
1986 // --- KeyboardInputMapper ---
1988 KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
1989 uint32_t source, int32_t keyboardType) :
1990 InputMapper(device), mSource(source),
1991 mKeyboardType(keyboardType) {
1994 KeyboardInputMapper::~KeyboardInputMapper() {
1997 uint32_t KeyboardInputMapper::getSources() {
2001 void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2002 InputMapper::populateDeviceInfo(info);
2004 info->setKeyboardType(mKeyboardType);
2005 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2008 void KeyboardInputMapper::dump(String8& dump) {
2009 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2010 dumpParameters(dump);
2011 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2012 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2013 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2014 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2015 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
2019 void KeyboardInputMapper::configure(nsecs_t when,
2020 const InputReaderConfiguration* config, uint32_t changes) {
2021 InputMapper::configure(when, config, changes);
2023 if (!changes) { // first time only
2024 // Configure basic parameters.
2025 configureParameters();
2028 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2029 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2031 if (config->getDisplayInfo(false /*external*/, &v)) {
2032 mOrientation = v.orientation;
2034 mOrientation = DISPLAY_ORIENTATION_0;
2037 mOrientation = DISPLAY_ORIENTATION_0;
2042 void KeyboardInputMapper::configureParameters() {
2043 mParameters.orientationAware = false;
2044 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
2045 mParameters.orientationAware);
2047 mParameters.hasAssociatedDisplay = false;
2048 if (mParameters.orientationAware) {
2049 mParameters.hasAssociatedDisplay = true;
2052 mParameters.handlesKeyRepeat = false;
2053 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.handlesKeyRepeat"),
2054 mParameters.handlesKeyRepeat);
2057 void KeyboardInputMapper::dumpParameters(String8& dump) {
2058 dump.append(INDENT3 "Parameters:\n");
2059 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2060 toString(mParameters.hasAssociatedDisplay));
2061 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2062 toString(mParameters.orientationAware));
2063 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2064 toString(mParameters.handlesKeyRepeat));
2067 void KeyboardInputMapper::reset(nsecs_t when) {
2068 mMetaState = AMETA_NONE;
2071 mCurrentHidUsage = 0;
2075 InputMapper::reset(when);
2078 void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2079 switch (rawEvent->type) {
2081 int32_t scanCode = rawEvent->code;
2082 int32_t usageCode = mCurrentHidUsage;
2083 mCurrentHidUsage = 0;
2085 if (isKeyboardOrGamepadKey(scanCode)) {
2088 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, &keyCode, &flags)) {
2089 keyCode = AKEYCODE_UNKNOWN;
2092 processKey(rawEvent->when, rawEvent->value != 0, keyCode, scanCode, flags);
2097 if (rawEvent->code == MSC_SCAN) {
2098 mCurrentHidUsage = rawEvent->value;
2103 if (rawEvent->code == SYN_REPORT) {
2104 mCurrentHidUsage = 0;
2110 bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2111 return scanCode < BTN_MOUSE
2112 || scanCode >= KEY_OK
2113 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2114 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2117 void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
2118 int32_t scanCode, uint32_t policyFlags) {
2121 // Rotate key codes according to orientation if needed.
2122 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2123 keyCode = rotateKeyCode(keyCode, mOrientation);
2127 ssize_t keyDownIndex = findKeyDown(scanCode);
2128 if (keyDownIndex >= 0) {
2129 // key repeat, be sure to use same keycode as before in case of rotation
2130 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2133 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2134 && mContext->shouldDropVirtualKey(when,
2135 getDevice(), keyCode, scanCode)) {
2140 KeyDown& keyDown = mKeyDowns.editTop();
2141 keyDown.keyCode = keyCode;
2142 keyDown.scanCode = scanCode;
2148 ssize_t keyDownIndex = findKeyDown(scanCode);
2149 if (keyDownIndex >= 0) {
2150 // key up, be sure to use same keycode as before in case of rotation
2151 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2152 mKeyDowns.removeAt(size_t(keyDownIndex));
2154 // key was not actually down
2155 ALOGI("Dropping key up from device %s because the key was not down. "
2156 "keyCode=%d, scanCode=%d",
2157 getDeviceName().string(), keyCode, scanCode);
2162 int32_t oldMetaState = mMetaState;
2163 int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState);
2164 bool metaStateChanged = oldMetaState != newMetaState;
2165 if (metaStateChanged) {
2166 mMetaState = newMetaState;
2167 updateLedState(false);
2170 nsecs_t downTime = mDownTime;
2172 // Key down on external an keyboard should wake the device.
2173 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2174 // For internal keyboards, the key layout file should specify the policy flags for
2175 // each wake key individually.
2176 // TODO: Use the input device configuration to control this behavior more finely.
2177 if (down && getDevice()->isExternal()) {
2178 policyFlags |= POLICY_FLAG_WAKE;
2181 if (mParameters.handlesKeyRepeat) {
2182 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2185 if (metaStateChanged) {
2186 getContext()->updateGlobalMetaState();
2189 if (down && !isMetaKey(keyCode)) {
2190 getContext()->fadePointer();
2193 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2194 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
2195 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
2196 getListener()->notifyKey(&args);
2199 ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2200 size_t n = mKeyDowns.size();
2201 for (size_t i = 0; i < n; i++) {
2202 if (mKeyDowns[i].scanCode == scanCode) {
2209 int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2210 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2213 int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2214 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2217 bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2218 const int32_t* keyCodes, uint8_t* outFlags) {
2219 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2222 int32_t KeyboardInputMapper::getMetaState() {
2226 void KeyboardInputMapper::resetLedState() {
2227 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2228 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2229 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2231 updateLedState(true);
2234 void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2235 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2236 ledState.on = false;
2239 void KeyboardInputMapper::updateLedState(bool reset) {
2240 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2241 AMETA_CAPS_LOCK_ON, reset);
2242 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2243 AMETA_NUM_LOCK_ON, reset);
2244 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2245 AMETA_SCROLL_LOCK_ON, reset);
2248 void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2249 int32_t led, int32_t modifier, bool reset) {
2250 if (ledState.avail) {
2251 bool desiredState = (mMetaState & modifier) != 0;
2252 if (reset || ledState.on != desiredState) {
2253 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2254 ledState.on = desiredState;
2260 // --- CursorInputMapper ---
2262 CursorInputMapper::CursorInputMapper(InputDevice* device) :
2263 InputMapper(device) {
2266 CursorInputMapper::~CursorInputMapper() {
2269 uint32_t CursorInputMapper::getSources() {
2273 void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2274 InputMapper::populateDeviceInfo(info);
2276 if (mParameters.mode == Parameters::MODE_POINTER) {
2277 float minX, minY, maxX, maxY;
2278 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2279 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2280 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2283 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2284 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2286 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2288 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2289 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2291 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2292 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2296 void CursorInputMapper::dump(String8& dump) {
2297 dump.append(INDENT2 "Cursor Input Mapper:\n");
2298 dumpParameters(dump);
2299 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2300 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2301 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2302 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2303 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2304 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2305 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2306 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2307 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2308 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2309 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2310 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2311 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2312 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
2315 void CursorInputMapper::configure(nsecs_t when,
2316 const InputReaderConfiguration* config, uint32_t changes) {
2317 InputMapper::configure(when, config, changes);
2319 if (!changes) { // first time only
2320 mCursorScrollAccumulator.configure(getDevice());
2322 // Configure basic parameters.
2323 configureParameters();
2325 // Configure device mode.
2326 switch (mParameters.mode) {
2327 case Parameters::MODE_POINTER:
2328 mSource = AINPUT_SOURCE_MOUSE;
2333 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2335 case Parameters::MODE_NAVIGATION:
2336 mSource = AINPUT_SOURCE_TRACKBALL;
2337 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2338 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2339 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2340 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2344 mVWheelScale = 1.0f;
2345 mHWheelScale = 1.0f;
2348 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2349 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2350 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2351 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2354 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2355 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2357 if (config->getDisplayInfo(false /*external*/, &v)) {
2358 mOrientation = v.orientation;
2360 mOrientation = DISPLAY_ORIENTATION_0;
2363 mOrientation = DISPLAY_ORIENTATION_0;
2369 void CursorInputMapper::configureParameters() {
2370 mParameters.mode = Parameters::MODE_POINTER;
2371 String8 cursorModeString;
2372 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2373 if (cursorModeString == "navigation") {
2374 mParameters.mode = Parameters::MODE_NAVIGATION;
2375 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2376 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2380 mParameters.orientationAware = false;
2381 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2382 mParameters.orientationAware);
2384 mParameters.hasAssociatedDisplay = false;
2385 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2386 mParameters.hasAssociatedDisplay = true;
2390 void CursorInputMapper::dumpParameters(String8& dump) {
2391 dump.append(INDENT3 "Parameters:\n");
2392 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2393 toString(mParameters.hasAssociatedDisplay));
2395 switch (mParameters.mode) {
2396 case Parameters::MODE_POINTER:
2397 dump.append(INDENT4 "Mode: pointer\n");
2399 case Parameters::MODE_NAVIGATION:
2400 dump.append(INDENT4 "Mode: navigation\n");
2406 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2407 toString(mParameters.orientationAware));
2410 void CursorInputMapper::reset(nsecs_t when) {
2414 mPointerVelocityControl.reset();
2415 mWheelXVelocityControl.reset();
2416 mWheelYVelocityControl.reset();
2418 mCursorButtonAccumulator.reset(getDevice());
2419 mCursorMotionAccumulator.reset(getDevice());
2420 mCursorScrollAccumulator.reset(getDevice());
2422 InputMapper::reset(when);
2425 void CursorInputMapper::process(const RawEvent* rawEvent) {
2426 mCursorButtonAccumulator.process(rawEvent);
2427 mCursorMotionAccumulator.process(rawEvent);
2428 mCursorScrollAccumulator.process(rawEvent);
2430 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2431 sync(rawEvent->when);
2435 void CursorInputMapper::sync(nsecs_t when) {
2436 int32_t lastButtonState = mButtonState;
2437 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2438 mButtonState = currentButtonState;
2440 bool wasDown = isPointerDown(lastButtonState);
2441 bool down = isPointerDown(currentButtonState);
2443 if (!wasDown && down) {
2446 } else if (wasDown && !down) {
2449 downChanged = false;
2451 nsecs_t downTime = mDownTime;
2452 bool buttonsChanged = currentButtonState != lastButtonState;
2453 bool buttonsPressed = currentButtonState & ~lastButtonState;
2455 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2456 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2457 bool moved = deltaX != 0 || deltaY != 0;
2459 // Rotate delta according to orientation if needed.
2460 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2461 && (deltaX != 0.0f || deltaY != 0.0f)) {
2462 rotateDelta(mOrientation, &deltaX, &deltaY);
2465 // Move the pointer.
2466 PointerProperties pointerProperties;
2467 pointerProperties.clear();
2468 pointerProperties.id = 0;
2469 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2471 PointerCoords pointerCoords;
2472 pointerCoords.clear();
2474 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2475 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2476 bool scrolled = vscroll != 0 || hscroll != 0;
2478 mWheelYVelocityControl.move(when, NULL, &vscroll);
2479 mWheelXVelocityControl.move(when, &hscroll, NULL);
2481 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2484 if (mPointerController != NULL) {
2485 if (moved || scrolled || buttonsChanged) {
2486 mPointerController->setPresentation(
2487 PointerControllerInterface::PRESENTATION_POINTER);
2490 mPointerController->move(deltaX, deltaY);
2493 if (buttonsChanged) {
2494 mPointerController->setButtonState(currentButtonState);
2497 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2501 mPointerController->getPosition(&x, &y);
2502 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2503 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2504 displayId = ADISPLAY_ID_DEFAULT;
2506 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2507 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2508 displayId = ADISPLAY_ID_NONE;
2511 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2513 // Moving an external trackball or mouse should wake the device.
2514 // We don't do this for internal cursor devices to prevent them from waking up
2515 // the device in your pocket.
2516 // TODO: Use the input device configuration to control this behavior more finely.
2517 uint32_t policyFlags = 0;
2518 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
2519 policyFlags |= POLICY_FLAG_WAKE;
2522 // Synthesize key down from buttons if needed.
2523 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2524 policyFlags, lastButtonState, currentButtonState);
2526 // Send motion event.
2527 if (downChanged || moved || scrolled || buttonsChanged) {
2528 int32_t metaState = mContext->getGlobalMetaState();
2529 int32_t motionEventAction;
2531 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2532 } else if (down || mPointerController == NULL) {
2533 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2535 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2538 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
2539 motionEventAction, 0, metaState, currentButtonState, 0,
2540 displayId, 1, &pointerProperties, &pointerCoords,
2541 mXPrecision, mYPrecision, downTime);
2542 getListener()->notifyMotion(&args);
2544 // Send hover move after UP to tell the application that the mouse is hovering now.
2545 if (motionEventAction == AMOTION_EVENT_ACTION_UP
2546 && mPointerController != NULL) {
2547 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
2548 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2549 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2550 displayId, 1, &pointerProperties, &pointerCoords,
2551 mXPrecision, mYPrecision, downTime);
2552 getListener()->notifyMotion(&hoverArgs);
2555 // Send scroll events.
2557 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2558 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2560 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2561 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, currentButtonState,
2562 AMOTION_EVENT_EDGE_FLAG_NONE,
2563 displayId, 1, &pointerProperties, &pointerCoords,
2564 mXPrecision, mYPrecision, downTime);
2565 getListener()->notifyMotion(&scrollArgs);
2569 // Synthesize key up from buttons if needed.
2570 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2571 policyFlags, lastButtonState, currentButtonState);
2573 mCursorMotionAccumulator.finishSync();
2574 mCursorScrollAccumulator.finishSync();
2577 int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2578 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2579 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2581 return AKEY_STATE_UNKNOWN;
2585 void CursorInputMapper::fadePointer() {
2586 if (mPointerController != NULL) {
2587 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2592 // --- TouchInputMapper ---
2594 TouchInputMapper::TouchInputMapper(InputDevice* device) :
2595 InputMapper(device),
2596 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2597 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2598 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2601 TouchInputMapper::~TouchInputMapper() {
2604 uint32_t TouchInputMapper::getSources() {
2608 void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2609 InputMapper::populateDeviceInfo(info);
2611 if (mDeviceMode != DEVICE_MODE_DISABLED) {
2612 info->addMotionRange(mOrientedRanges.x);
2613 info->addMotionRange(mOrientedRanges.y);
2614 info->addMotionRange(mOrientedRanges.pressure);
2616 if (mOrientedRanges.haveSize) {
2617 info->addMotionRange(mOrientedRanges.size);
2620 if (mOrientedRanges.haveTouchSize) {
2621 info->addMotionRange(mOrientedRanges.touchMajor);
2622 info->addMotionRange(mOrientedRanges.touchMinor);
2625 if (mOrientedRanges.haveToolSize) {
2626 info->addMotionRange(mOrientedRanges.toolMajor);
2627 info->addMotionRange(mOrientedRanges.toolMinor);
2630 if (mOrientedRanges.haveOrientation) {
2631 info->addMotionRange(mOrientedRanges.orientation);
2634 if (mOrientedRanges.haveDistance) {
2635 info->addMotionRange(mOrientedRanges.distance);
2638 if (mOrientedRanges.haveTilt) {
2639 info->addMotionRange(mOrientedRanges.tilt);
2642 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2643 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2646 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2647 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2650 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2651 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2652 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2653 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2654 x.fuzz, x.resolution);
2655 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2656 y.fuzz, y.resolution);
2657 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2658 x.fuzz, x.resolution);
2659 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2660 y.fuzz, y.resolution);
2662 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2666 void TouchInputMapper::dump(String8& dump) {
2667 dump.append(INDENT2 "Touch Input Mapper:\n");
2668 dumpParameters(dump);
2669 dumpVirtualKeys(dump);
2670 dumpRawPointerAxes(dump);
2671 dumpCalibration(dump);
2672 dumpAffineTransformation(dump);
2675 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2676 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2677 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2678 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2679 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2680 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
2681 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
2682 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
2683 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
2684 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
2685 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
2686 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
2687 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
2688 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
2689 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
2690 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
2691 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
2693 dump.appendFormat(INDENT3 "Last Button State: 0x%08x\n", mLastButtonState);
2695 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
2696 mLastRawPointerData.pointerCount);
2697 for (uint32_t i = 0; i < mLastRawPointerData.pointerCount; i++) {
2698 const RawPointerData::Pointer& pointer = mLastRawPointerData.pointers[i];
2699 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
2700 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
2701 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
2702 "toolType=%d, isHovering=%s\n", i,
2703 pointer.id, pointer.x, pointer.y, pointer.pressure,
2704 pointer.touchMajor, pointer.touchMinor,
2705 pointer.toolMajor, pointer.toolMinor,
2706 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
2707 pointer.toolType, toString(pointer.isHovering));
2710 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
2711 mLastCookedPointerData.pointerCount);
2712 for (uint32_t i = 0; i < mLastCookedPointerData.pointerCount; i++) {
2713 const PointerProperties& pointerProperties = mLastCookedPointerData.pointerProperties[i];
2714 const PointerCoords& pointerCoords = mLastCookedPointerData.pointerCoords[i];
2715 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
2716 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
2717 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
2718 "toolType=%d, isHovering=%s\n", i,
2719 pointerProperties.id,
2720 pointerCoords.getX(),
2721 pointerCoords.getY(),
2722 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2723 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2724 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2725 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2726 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2727 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
2728 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
2729 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
2730 pointerProperties.toolType,
2731 toString(mLastCookedPointerData.isHovering(i)));
2734 if (mDeviceMode == DEVICE_MODE_POINTER) {
2735 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
2736 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
2737 mPointerXMovementScale);
2738 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
2739 mPointerYMovementScale);
2740 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
2741 mPointerXZoomScale);
2742 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
2743 mPointerYZoomScale);
2744 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
2745 mPointerGestureMaxSwipeWidth);
2749 void TouchInputMapper::configure(nsecs_t when,
2750 const InputReaderConfiguration* config, uint32_t changes) {
2751 InputMapper::configure(when, config, changes);
2755 if (!changes) { // first time only
2756 // Configure basic parameters.
2757 configureParameters();
2759 // Configure common accumulators.
2760 mCursorScrollAccumulator.configure(getDevice());
2761 mTouchButtonAccumulator.configure(getDevice());
2763 // Configure absolute axis information.
2764 configureRawPointerAxes();
2766 // Prepare input device calibration.
2768 resolveCalibration();
2771 if (!changes || (changes & InputReaderConfiguration::TOUCH_AFFINE_TRANSFORMATION)) {
2772 // Update location calibration to reflect current settings
2773 updateAffineTransformation();
2776 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2777 // Update pointer speed.
2778 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
2779 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
2780 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
2783 bool resetNeeded = false;
2784 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
2785 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
2786 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES))) {
2787 // Configure device sources, surface dimensions, orientation and
2789 configureSurface(when, &resetNeeded);
2792 if (changes && resetNeeded) {
2793 // Send reset, unless this is the first time the device has been configured,
2794 // in which case the reader will call reset itself after all mappers are ready.
2795 getDevice()->notifyReset(when);
2799 void TouchInputMapper::configureParameters() {
2800 // Use the pointer presentation mode for devices that do not support distinct
2801 // multitouch. The spot-based presentation relies on being able to accurately
2802 // locate two or more fingers on the touch pad.
2803 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
2804 ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
2806 String8 gestureModeString;
2807 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
2808 gestureModeString)) {
2809 if (gestureModeString == "pointer") {
2810 mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
2811 } else if (gestureModeString == "spots") {
2812 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
2813 } else if (gestureModeString != "default") {
2814 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
2818 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
2819 // The device is a touch screen.
2820 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2821 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
2822 // The device is a pointing device like a track pad.
2823 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2824 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
2825 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
2826 // The device is a cursor device with a touch pad attached.
2827 // By default don't use the touch pad to move the pointer.
2828 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
2830 // The device is a touch pad of unknown purpose.
2831 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2834 mParameters.hasButtonUnderPad=
2835 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
2837 String8 deviceTypeString;
2838 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
2839 deviceTypeString)) {
2840 if (deviceTypeString == "touchScreen") {
2841 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2842 } else if (deviceTypeString == "touchPad") {
2843 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
2844 } else if (deviceTypeString == "touchNavigation") {
2845 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
2846 } else if (deviceTypeString == "pointer") {
2847 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2848 } else if (deviceTypeString != "default") {
2849 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
2853 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2854 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
2855 mParameters.orientationAware);
2857 mParameters.hasAssociatedDisplay = false;
2858 mParameters.associatedDisplayIsExternal = false;
2859 if (mParameters.orientationAware
2860 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2861 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2862 mParameters.hasAssociatedDisplay = true;
2863 mParameters.associatedDisplayIsExternal =
2864 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2865 && getDevice()->isExternal();
2868 // Initial downs on external touch devices should wake the device.
2869 // Normally we don't do this for internal touch screens to prevent them from waking
2870 // up in your pocket but you can enable it using the input device configuration.
2871 mParameters.wake = getDevice()->isExternal();
2872 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
2876 void TouchInputMapper::dumpParameters(String8& dump) {
2877 dump.append(INDENT3 "Parameters:\n");
2879 switch (mParameters.gestureMode) {
2880 case Parameters::GESTURE_MODE_POINTER:
2881 dump.append(INDENT4 "GestureMode: pointer\n");
2883 case Parameters::GESTURE_MODE_SPOTS:
2884 dump.append(INDENT4 "GestureMode: spots\n");
2890 switch (mParameters.deviceType) {
2891 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
2892 dump.append(INDENT4 "DeviceType: touchScreen\n");
2894 case Parameters::DEVICE_TYPE_TOUCH_PAD:
2895 dump.append(INDENT4 "DeviceType: touchPad\n");
2897 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
2898 dump.append(INDENT4 "DeviceType: touchNavigation\n");
2900 case Parameters::DEVICE_TYPE_POINTER:
2901 dump.append(INDENT4 "DeviceType: pointer\n");
2907 dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
2908 toString(mParameters.hasAssociatedDisplay),
2909 toString(mParameters.associatedDisplayIsExternal));
2910 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2911 toString(mParameters.orientationAware));
2914 void TouchInputMapper::configureRawPointerAxes() {
2915 mRawPointerAxes.clear();
2918 void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
2919 dump.append(INDENT3 "Raw Touch Axes:\n");
2920 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
2921 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
2922 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
2923 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
2924 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
2925 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
2926 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
2927 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
2928 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
2929 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
2930 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
2931 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
2932 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
2935 void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
2936 int32_t oldDeviceMode = mDeviceMode;
2938 // Determine device mode.
2939 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2940 && mConfig.pointerGesturesEnabled) {
2941 mSource = AINPUT_SOURCE_MOUSE;
2942 mDeviceMode = DEVICE_MODE_POINTER;
2944 mSource |= AINPUT_SOURCE_STYLUS;
2946 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2947 && mParameters.hasAssociatedDisplay) {
2948 mSource = AINPUT_SOURCE_TOUCHSCREEN;
2949 mDeviceMode = DEVICE_MODE_DIRECT;
2951 mSource |= AINPUT_SOURCE_STYLUS;
2953 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
2954 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
2955 mDeviceMode = DEVICE_MODE_NAVIGATION;
2957 mSource = AINPUT_SOURCE_TOUCHPAD;
2958 mDeviceMode = DEVICE_MODE_UNSCALED;
2961 // Ensure we have valid X and Y axes.
2962 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
2963 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
2964 "The device will be inoperable.", getDeviceName().string());
2965 mDeviceMode = DEVICE_MODE_DISABLED;
2969 // Raw width and height in the natural orientation.
2970 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
2971 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
2973 // Get associated display dimensions.
2974 DisplayViewport newViewport;
2975 if (mParameters.hasAssociatedDisplay) {
2976 if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
2977 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
2978 "display. The device will be inoperable until the display size "
2979 "becomes available.",
2980 getDeviceName().string());
2981 mDeviceMode = DEVICE_MODE_DISABLED;
2985 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
2987 bool viewportChanged = mViewport != newViewport;
2988 if (viewportChanged) {
2989 mViewport = newViewport;
2991 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
2992 // Convert rotated viewport to natural surface coordinates.
2993 int32_t naturalLogicalWidth, naturalLogicalHeight;
2994 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
2995 int32_t naturalPhysicalLeft, naturalPhysicalTop;
2996 int32_t naturalDeviceWidth, naturalDeviceHeight;
2997 switch (mViewport.orientation) {
2998 case DISPLAY_ORIENTATION_90:
2999 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3000 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3001 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3002 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3003 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3004 naturalPhysicalTop = mViewport.physicalLeft;
3005 naturalDeviceWidth = mViewport.deviceHeight;
3006 naturalDeviceHeight = mViewport.deviceWidth;
3008 case DISPLAY_ORIENTATION_180:
3009 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3010 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3011 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3012 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3013 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3014 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3015 naturalDeviceWidth = mViewport.deviceWidth;
3016 naturalDeviceHeight = mViewport.deviceHeight;
3018 case DISPLAY_ORIENTATION_270:
3019 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3020 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3021 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3022 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3023 naturalPhysicalLeft = mViewport.physicalTop;
3024 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3025 naturalDeviceWidth = mViewport.deviceHeight;
3026 naturalDeviceHeight = mViewport.deviceWidth;
3028 case DISPLAY_ORIENTATION_0:
3030 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3031 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3032 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3033 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3034 naturalPhysicalLeft = mViewport.physicalLeft;
3035 naturalPhysicalTop = mViewport.physicalTop;
3036 naturalDeviceWidth = mViewport.deviceWidth;
3037 naturalDeviceHeight = mViewport.deviceHeight;
3041 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3042 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3043 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3044 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3046 mSurfaceOrientation = mParameters.orientationAware ?
3047 mViewport.orientation : DISPLAY_ORIENTATION_0;
3049 mSurfaceWidth = rawWidth;
3050 mSurfaceHeight = rawHeight;
3053 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3057 // If moving between pointer modes, need to reset some state.
3058 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3059 if (deviceModeChanged) {
3060 mOrientedRanges.clear();
3063 // Create pointer controller if needed.
3064 if (mDeviceMode == DEVICE_MODE_POINTER ||
3065 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3066 if (mPointerController == NULL) {
3067 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3070 mPointerController.clear();
3073 if (viewportChanged || deviceModeChanged) {
3074 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3076 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3077 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3079 // Configure X and Y factors.
3080 mXScale = float(mSurfaceWidth) / rawWidth;
3081 mYScale = float(mSurfaceHeight) / rawHeight;
3082 mXTranslate = -mSurfaceLeft;
3083 mYTranslate = -mSurfaceTop;
3084 mXPrecision = 1.0f / mXScale;
3085 mYPrecision = 1.0f / mYScale;
3087 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3088 mOrientedRanges.x.source = mSource;
3089 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3090 mOrientedRanges.y.source = mSource;
3092 configureVirtualKeys();
3094 // Scale factor for terms that are not oriented in a particular axis.
3095 // If the pixels are square then xScale == yScale otherwise we fake it
3096 // by choosing an average.
3097 mGeometricScale = avg(mXScale, mYScale);
3099 // Size of diagonal axis.
3100 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3103 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3104 if (mRawPointerAxes.touchMajor.valid
3105 && mRawPointerAxes.touchMajor.maxValue != 0) {
3106 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3107 } else if (mRawPointerAxes.toolMajor.valid
3108 && mRawPointerAxes.toolMajor.maxValue != 0) {
3109 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3114 mOrientedRanges.haveTouchSize = true;
3115 mOrientedRanges.haveToolSize = true;
3116 mOrientedRanges.haveSize = true;
3118 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3119 mOrientedRanges.touchMajor.source = mSource;
3120 mOrientedRanges.touchMajor.min = 0;
3121 mOrientedRanges.touchMajor.max = diagonalSize;
3122 mOrientedRanges.touchMajor.flat = 0;
3123 mOrientedRanges.touchMajor.fuzz = 0;
3124 mOrientedRanges.touchMajor.resolution = 0;
3126 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3127 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3129 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3130 mOrientedRanges.toolMajor.source = mSource;
3131 mOrientedRanges.toolMajor.min = 0;
3132 mOrientedRanges.toolMajor.max = diagonalSize;
3133 mOrientedRanges.toolMajor.flat = 0;
3134 mOrientedRanges.toolMajor.fuzz = 0;
3135 mOrientedRanges.toolMajor.resolution = 0;
3137 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3138 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3140 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3141 mOrientedRanges.size.source = mSource;
3142 mOrientedRanges.size.min = 0;
3143 mOrientedRanges.size.max = 1.0;
3144 mOrientedRanges.size.flat = 0;
3145 mOrientedRanges.size.fuzz = 0;
3146 mOrientedRanges.size.resolution = 0;
3151 // Pressure factors.
3153 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3154 || mCalibration.pressureCalibration
3155 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3156 if (mCalibration.havePressureScale) {
3157 mPressureScale = mCalibration.pressureScale;
3158 } else if (mRawPointerAxes.pressure.valid
3159 && mRawPointerAxes.pressure.maxValue != 0) {
3160 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3164 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3165 mOrientedRanges.pressure.source = mSource;
3166 mOrientedRanges.pressure.min = 0;
3167 mOrientedRanges.pressure.max = 1.0;
3168 mOrientedRanges.pressure.flat = 0;
3169 mOrientedRanges.pressure.fuzz = 0;
3170 mOrientedRanges.pressure.resolution = 0;
3177 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3179 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3180 mRawPointerAxes.tiltX.maxValue);
3181 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3182 mRawPointerAxes.tiltY.maxValue);
3183 mTiltXScale = M_PI / 180;
3184 mTiltYScale = M_PI / 180;
3186 mOrientedRanges.haveTilt = true;
3188 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3189 mOrientedRanges.tilt.source = mSource;
3190 mOrientedRanges.tilt.min = 0;
3191 mOrientedRanges.tilt.max = M_PI_2;
3192 mOrientedRanges.tilt.flat = 0;
3193 mOrientedRanges.tilt.fuzz = 0;
3194 mOrientedRanges.tilt.resolution = 0;
3198 mOrientationScale = 0;
3200 mOrientedRanges.haveOrientation = true;
3202 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3203 mOrientedRanges.orientation.source = mSource;
3204 mOrientedRanges.orientation.min = -M_PI;
3205 mOrientedRanges.orientation.max = M_PI;
3206 mOrientedRanges.orientation.flat = 0;
3207 mOrientedRanges.orientation.fuzz = 0;
3208 mOrientedRanges.orientation.resolution = 0;
3209 } else if (mCalibration.orientationCalibration !=
3210 Calibration::ORIENTATION_CALIBRATION_NONE) {
3211 if (mCalibration.orientationCalibration
3212 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3213 if (mRawPointerAxes.orientation.valid) {
3214 if (mRawPointerAxes.orientation.maxValue > 0) {
3215 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3216 } else if (mRawPointerAxes.orientation.minValue < 0) {
3217 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3219 mOrientationScale = 0;
3224 mOrientedRanges.haveOrientation = true;
3226 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3227 mOrientedRanges.orientation.source = mSource;
3228 mOrientedRanges.orientation.min = -M_PI_2;
3229 mOrientedRanges.orientation.max = M_PI_2;
3230 mOrientedRanges.orientation.flat = 0;
3231 mOrientedRanges.orientation.fuzz = 0;
3232 mOrientedRanges.orientation.resolution = 0;
3237 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3238 if (mCalibration.distanceCalibration
3239 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3240 if (mCalibration.haveDistanceScale) {
3241 mDistanceScale = mCalibration.distanceScale;
3243 mDistanceScale = 1.0f;
3247 mOrientedRanges.haveDistance = true;
3249 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3250 mOrientedRanges.distance.source = mSource;
3251 mOrientedRanges.distance.min =
3252 mRawPointerAxes.distance.minValue * mDistanceScale;
3253 mOrientedRanges.distance.max =
3254 mRawPointerAxes.distance.maxValue * mDistanceScale;
3255 mOrientedRanges.distance.flat = 0;
3256 mOrientedRanges.distance.fuzz =
3257 mRawPointerAxes.distance.fuzz * mDistanceScale;
3258 mOrientedRanges.distance.resolution = 0;
3261 // Compute oriented precision, scales and ranges.
3262 // Note that the maximum value reported is an inclusive maximum value so it is one
3263 // unit less than the total width or height of surface.
3264 switch (mSurfaceOrientation) {
3265 case DISPLAY_ORIENTATION_90:
3266 case DISPLAY_ORIENTATION_270:
3267 mOrientedXPrecision = mYPrecision;
3268 mOrientedYPrecision = mXPrecision;
3270 mOrientedRanges.x.min = mYTranslate;
3271 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3272 mOrientedRanges.x.flat = 0;
3273 mOrientedRanges.x.fuzz = 0;
3274 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3276 mOrientedRanges.y.min = mXTranslate;
3277 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3278 mOrientedRanges.y.flat = 0;
3279 mOrientedRanges.y.fuzz = 0;
3280 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3284 mOrientedXPrecision = mXPrecision;
3285 mOrientedYPrecision = mYPrecision;
3287 mOrientedRanges.x.min = mXTranslate;
3288 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3289 mOrientedRanges.x.flat = 0;
3290 mOrientedRanges.x.fuzz = 0;
3291 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3293 mOrientedRanges.y.min = mYTranslate;
3294 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3295 mOrientedRanges.y.flat = 0;
3296 mOrientedRanges.y.fuzz = 0;
3297 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3302 updateAffineTransformation();
3304 if (mDeviceMode == DEVICE_MODE_POINTER) {
3305 // Compute pointer gesture detection parameters.
3306 float rawDiagonal = hypotf(rawWidth, rawHeight);
3307 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3309 // Scale movements such that one whole swipe of the touch pad covers a
3310 // given area relative to the diagonal size of the display when no acceleration
3312 // Assume that the touch pad has a square aspect ratio such that movements in
3313 // X and Y of the same number of raw units cover the same physical distance.
3314 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3315 * displayDiagonal / rawDiagonal;
3316 mPointerYMovementScale = mPointerXMovementScale;
3318 // Scale zooms to cover a smaller range of the display than movements do.
3319 // This value determines the area around the pointer that is affected by freeform
3320 // pointer gestures.
3321 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3322 * displayDiagonal / rawDiagonal;
3323 mPointerYZoomScale = mPointerXZoomScale;
3325 // Max width between pointers to detect a swipe gesture is more than some fraction
3326 // of the diagonal axis of the touch pad. Touches that are wider than this are
3327 // translated into freeform gestures.
3328 mPointerGestureMaxSwipeWidth =
3329 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3331 // Abort current pointer usages because the state has changed.
3332 abortPointerUsage(when, 0 /*policyFlags*/);
3335 // Inform the dispatcher about the changes.
3336 *outResetNeeded = true;
3341 void TouchInputMapper::dumpSurface(String8& dump) {
3342 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3343 "logicalFrame=[%d, %d, %d, %d], "
3344 "physicalFrame=[%d, %d, %d, %d], "
3345 "deviceSize=[%d, %d]\n",
3346 mViewport.displayId, mViewport.orientation,
3347 mViewport.logicalLeft, mViewport.logicalTop,
3348 mViewport.logicalRight, mViewport.logicalBottom,
3349 mViewport.physicalLeft, mViewport.physicalTop,
3350 mViewport.physicalRight, mViewport.physicalBottom,
3351 mViewport.deviceWidth, mViewport.deviceHeight);
3353 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3354 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3355 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3356 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3357 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3360 void TouchInputMapper::configureVirtualKeys() {
3361 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3362 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3364 mVirtualKeys.clear();
3366 if (virtualKeyDefinitions.size() == 0) {
3370 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3372 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3373 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3374 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3375 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3377 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3378 const VirtualKeyDefinition& virtualKeyDefinition =
3379 virtualKeyDefinitions[i];
3382 VirtualKey& virtualKey = mVirtualKeys.editTop();
3384 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3387 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, &keyCode, &flags)) {
3388 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3389 virtualKey.scanCode);
3390 mVirtualKeys.pop(); // drop the key
3394 virtualKey.keyCode = keyCode;
3395 virtualKey.flags = flags;
3397 // convert the key definition's display coordinates into touch coordinates for a hit box
3398 int32_t halfWidth = virtualKeyDefinition.width / 2;
3399 int32_t halfHeight = virtualKeyDefinition.height / 2;
3401 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3402 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3403 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3404 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3405 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3406 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3407 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3408 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3412 void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3413 if (!mVirtualKeys.isEmpty()) {
3414 dump.append(INDENT3 "Virtual Keys:\n");
3416 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3417 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
3418 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
3419 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3420 i, virtualKey.scanCode, virtualKey.keyCode,
3421 virtualKey.hitLeft, virtualKey.hitRight,
3422 virtualKey.hitTop, virtualKey.hitBottom);
3427 void TouchInputMapper::parseCalibration() {
3428 const PropertyMap& in = getDevice()->getConfiguration();
3429 Calibration& out = mCalibration;
3432 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3433 String8 sizeCalibrationString;
3434 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3435 if (sizeCalibrationString == "none") {
3436 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3437 } else if (sizeCalibrationString == "geometric") {
3438 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3439 } else if (sizeCalibrationString == "diameter") {
3440 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3441 } else if (sizeCalibrationString == "box") {
3442 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3443 } else if (sizeCalibrationString == "area") {
3444 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3445 } else if (sizeCalibrationString != "default") {
3446 ALOGW("Invalid value for touch.size.calibration: '%s'",
3447 sizeCalibrationString.string());
3451 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3453 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3455 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3459 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3460 String8 pressureCalibrationString;
3461 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3462 if (pressureCalibrationString == "none") {
3463 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3464 } else if (pressureCalibrationString == "physical") {
3465 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3466 } else if (pressureCalibrationString == "amplitude") {
3467 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3468 } else if (pressureCalibrationString != "default") {
3469 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3470 pressureCalibrationString.string());
3474 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3478 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3479 String8 orientationCalibrationString;
3480 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3481 if (orientationCalibrationString == "none") {
3482 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3483 } else if (orientationCalibrationString == "interpolated") {
3484 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3485 } else if (orientationCalibrationString == "vector") {
3486 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3487 } else if (orientationCalibrationString != "default") {
3488 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3489 orientationCalibrationString.string());
3494 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3495 String8 distanceCalibrationString;
3496 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3497 if (distanceCalibrationString == "none") {
3498 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3499 } else if (distanceCalibrationString == "scaled") {
3500 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3501 } else if (distanceCalibrationString != "default") {
3502 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3503 distanceCalibrationString.string());
3507 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3510 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3511 String8 coverageCalibrationString;
3512 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3513 if (coverageCalibrationString == "none") {
3514 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3515 } else if (coverageCalibrationString == "box") {
3516 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3517 } else if (coverageCalibrationString != "default") {
3518 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3519 coverageCalibrationString.string());
3524 void TouchInputMapper::resolveCalibration() {
3526 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3527 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3528 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3531 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3535 if (mRawPointerAxes.pressure.valid) {
3536 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3537 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3540 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3544 if (mRawPointerAxes.orientation.valid) {
3545 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3546 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3549 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3553 if (mRawPointerAxes.distance.valid) {
3554 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3555 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3558 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3562 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3563 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3567 void TouchInputMapper::dumpCalibration(String8& dump) {
3568 dump.append(INDENT3 "Calibration:\n");
3571 switch (mCalibration.sizeCalibration) {
3572 case Calibration::SIZE_CALIBRATION_NONE:
3573 dump.append(INDENT4 "touch.size.calibration: none\n");
3575 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3576 dump.append(INDENT4 "touch.size.calibration: geometric\n");
3578 case Calibration::SIZE_CALIBRATION_DIAMETER:
3579 dump.append(INDENT4 "touch.size.calibration: diameter\n");
3581 case Calibration::SIZE_CALIBRATION_BOX:
3582 dump.append(INDENT4 "touch.size.calibration: box\n");
3584 case Calibration::SIZE_CALIBRATION_AREA:
3585 dump.append(INDENT4 "touch.size.calibration: area\n");
3591 if (mCalibration.haveSizeScale) {
3592 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3593 mCalibration.sizeScale);
3596 if (mCalibration.haveSizeBias) {
3597 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3598 mCalibration.sizeBias);
3601 if (mCalibration.haveSizeIsSummed) {
3602 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3603 toString(mCalibration.sizeIsSummed));
3607 switch (mCalibration.pressureCalibration) {
3608 case Calibration::PRESSURE_CALIBRATION_NONE:
3609 dump.append(INDENT4 "touch.pressure.calibration: none\n");
3611 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3612 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3614 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3615 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3621 if (mCalibration.havePressureScale) {
3622 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3623 mCalibration.pressureScale);
3627 switch (mCalibration.orientationCalibration) {
3628 case Calibration::ORIENTATION_CALIBRATION_NONE:
3629 dump.append(INDENT4 "touch.orientation.calibration: none\n");
3631 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3632 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3634 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3635 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3642 switch (mCalibration.distanceCalibration) {
3643 case Calibration::DISTANCE_CALIBRATION_NONE:
3644 dump.append(INDENT4 "touch.distance.calibration: none\n");
3646 case Calibration::DISTANCE_CALIBRATION_SCALED:
3647 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3653 if (mCalibration.haveDistanceScale) {
3654 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
3655 mCalibration.distanceScale);
3658 switch (mCalibration.coverageCalibration) {
3659 case Calibration::COVERAGE_CALIBRATION_NONE:
3660 dump.append(INDENT4 "touch.coverage.calibration: none\n");
3662 case Calibration::COVERAGE_CALIBRATION_BOX:
3663 dump.append(INDENT4 "touch.coverage.calibration: box\n");
3670 void TouchInputMapper::dumpAffineTransformation(String8& dump) {
3671 dump.append(INDENT3 "Affine Transformation:\n");
3673 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
3674 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
3675 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
3676 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
3677 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
3678 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
3681 void TouchInputMapper::updateAffineTransformation() {
3682 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
3683 mSurfaceOrientation);
3686 void TouchInputMapper::reset(nsecs_t when) {
3687 mCursorButtonAccumulator.reset(getDevice());
3688 mCursorScrollAccumulator.reset(getDevice());
3689 mTouchButtonAccumulator.reset(getDevice());
3691 mPointerVelocityControl.reset();
3692 mWheelXVelocityControl.reset();
3693 mWheelYVelocityControl.reset();
3695 mCurrentRawPointerData.clear();
3696 mLastRawPointerData.clear();
3697 mCurrentCookedPointerData.clear();
3698 mLastCookedPointerData.clear();
3699 mCurrentButtonState = 0;
3700 mLastButtonState = 0;
3701 mCurrentRawVScroll = 0;
3702 mCurrentRawHScroll = 0;
3703 mCurrentFingerIdBits.clear();
3704 mLastFingerIdBits.clear();
3705 mCurrentStylusIdBits.clear();
3706 mLastStylusIdBits.clear();
3707 mCurrentMouseIdBits.clear();
3708 mLastMouseIdBits.clear();
3709 mPointerUsage = POINTER_USAGE_NONE;
3710 mSentHoverEnter = false;
3713 mCurrentVirtualKey.down = false;
3715 mPointerGesture.reset();
3716 mPointerSimple.reset();
3718 if (mPointerController != NULL) {
3719 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3720 mPointerController->clearSpots();
3723 InputMapper::reset(when);
3726 void TouchInputMapper::process(const RawEvent* rawEvent) {
3727 mCursorButtonAccumulator.process(rawEvent);
3728 mCursorScrollAccumulator.process(rawEvent);
3729 mTouchButtonAccumulator.process(rawEvent);
3731 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3732 sync(rawEvent->when);
3736 void TouchInputMapper::sync(nsecs_t when) {
3737 // Sync button state.
3738 mCurrentButtonState = mTouchButtonAccumulator.getButtonState()
3739 | mCursorButtonAccumulator.getButtonState();
3741 // Sync scroll state.
3742 mCurrentRawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
3743 mCurrentRawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
3744 mCursorScrollAccumulator.finishSync();
3746 // Sync touch state.
3747 bool havePointerIds = true;
3748 mCurrentRawPointerData.clear();
3749 syncTouch(when, &havePointerIds);
3751 #if DEBUG_RAW_EVENTS
3752 if (!havePointerIds) {
3753 ALOGD("syncTouch: pointerCount %d -> %d, no pointer ids",
3754 mLastRawPointerData.pointerCount,
3755 mCurrentRawPointerData.pointerCount);
3757 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
3758 "hovering ids 0x%08x -> 0x%08x",
3759 mLastRawPointerData.pointerCount,
3760 mCurrentRawPointerData.pointerCount,
3761 mLastRawPointerData.touchingIdBits.value,
3762 mCurrentRawPointerData.touchingIdBits.value,
3763 mLastRawPointerData.hoveringIdBits.value,
3764 mCurrentRawPointerData.hoveringIdBits.value);
3768 // Reset state that we will compute below.
3769 mCurrentFingerIdBits.clear();
3770 mCurrentStylusIdBits.clear();
3771 mCurrentMouseIdBits.clear();
3772 mCurrentCookedPointerData.clear();
3774 if (mDeviceMode == DEVICE_MODE_DISABLED) {
3775 // Drop all input if the device is disabled.
3776 mCurrentRawPointerData.clear();
3777 mCurrentButtonState = 0;
3779 // Preprocess pointer data.
3780 if (!havePointerIds) {
3784 // Handle policy on initial down or hover events.
3785 uint32_t policyFlags = 0;
3786 bool initialDown = mLastRawPointerData.pointerCount == 0
3787 && mCurrentRawPointerData.pointerCount != 0;
3788 bool buttonsPressed = mCurrentButtonState & ~mLastButtonState;
3789 if (initialDown || buttonsPressed) {
3790 // If this is a touch screen, hide the pointer on an initial down.
3791 if (mDeviceMode == DEVICE_MODE_DIRECT) {
3792 getContext()->fadePointer();
3795 if (mParameters.wake) {
3796 policyFlags |= POLICY_FLAG_WAKE;
3800 // Synthesize key down from raw buttons if needed.
3801 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
3802 policyFlags, mLastButtonState, mCurrentButtonState);
3804 // Consume raw off-screen touches before cooking pointer data.
3805 // If touches are consumed, subsequent code will not receive any pointer data.
3806 if (consumeRawTouches(when, policyFlags)) {
3807 mCurrentRawPointerData.clear();
3810 // Cook pointer data. This call populates the mCurrentCookedPointerData structure
3811 // with cooked pointer data that has the same ids and indices as the raw data.
3812 // The following code can use either the raw or cooked data, as needed.
3815 // Dispatch the touches either directly or by translation through a pointer on screen.
3816 if (mDeviceMode == DEVICE_MODE_POINTER) {
3817 for (BitSet32 idBits(mCurrentRawPointerData.touchingIdBits); !idBits.isEmpty(); ) {
3818 uint32_t id = idBits.clearFirstMarkedBit();
3819 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3820 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
3821 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
3822 mCurrentStylusIdBits.markBit(id);
3823 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
3824 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
3825 mCurrentFingerIdBits.markBit(id);
3826 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
3827 mCurrentMouseIdBits.markBit(id);
3830 for (BitSet32 idBits(mCurrentRawPointerData.hoveringIdBits); !idBits.isEmpty(); ) {
3831 uint32_t id = idBits.clearFirstMarkedBit();
3832 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3833 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
3834 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
3835 mCurrentStylusIdBits.markBit(id);
3839 // Stylus takes precedence over all tools, then mouse, then finger.
3840 PointerUsage pointerUsage = mPointerUsage;
3841 if (!mCurrentStylusIdBits.isEmpty()) {
3842 mCurrentMouseIdBits.clear();
3843 mCurrentFingerIdBits.clear();
3844 pointerUsage = POINTER_USAGE_STYLUS;
3845 } else if (!mCurrentMouseIdBits.isEmpty()) {
3846 mCurrentFingerIdBits.clear();
3847 pointerUsage = POINTER_USAGE_MOUSE;
3848 } else if (!mCurrentFingerIdBits.isEmpty() || isPointerDown(mCurrentButtonState)) {
3849 pointerUsage = POINTER_USAGE_GESTURES;
3852 dispatchPointerUsage(when, policyFlags, pointerUsage);
3854 if (mDeviceMode == DEVICE_MODE_DIRECT
3855 && mConfig.showTouches && mPointerController != NULL) {
3856 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
3857 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3859 mPointerController->setButtonState(mCurrentButtonState);
3860 mPointerController->setSpots(mCurrentCookedPointerData.pointerCoords,
3861 mCurrentCookedPointerData.idToIndex,
3862 mCurrentCookedPointerData.touchingIdBits);
3865 dispatchHoverExit(when, policyFlags);
3866 dispatchTouches(when, policyFlags);
3867 dispatchHoverEnterAndMove(when, policyFlags);
3870 // Synthesize key up from raw buttons if needed.
3871 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
3872 policyFlags, mLastButtonState, mCurrentButtonState);
3875 // Copy current touch to last touch in preparation for the next cycle.
3876 mLastRawPointerData.copyFrom(mCurrentRawPointerData);
3877 mLastCookedPointerData.copyFrom(mCurrentCookedPointerData);
3878 mLastButtonState = mCurrentButtonState;
3879 mLastFingerIdBits = mCurrentFingerIdBits;
3880 mLastStylusIdBits = mCurrentStylusIdBits;
3881 mLastMouseIdBits = mCurrentMouseIdBits;
3883 // Clear some transient state.
3884 mCurrentRawVScroll = 0;
3885 mCurrentRawHScroll = 0;
3888 void TouchInputMapper::timeoutExpired(nsecs_t when) {
3889 if (mDeviceMode == DEVICE_MODE_POINTER) {
3890 if (mPointerUsage == POINTER_USAGE_GESTURES) {
3891 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
3896 bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
3897 // Check for release of a virtual key.
3898 if (mCurrentVirtualKey.down) {
3899 if (mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3900 // Pointer went up while virtual key was down.
3901 mCurrentVirtualKey.down = false;
3902 if (!mCurrentVirtualKey.ignored) {
3903 #if DEBUG_VIRTUAL_KEYS
3904 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
3905 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
3907 dispatchVirtualKey(when, policyFlags,
3908 AKEY_EVENT_ACTION_UP,
3909 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
3914 if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
3915 uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
3916 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3917 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
3918 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
3919 // Pointer is still within the space of the virtual key.
3924 // Pointer left virtual key area or another pointer also went down.
3925 // Send key cancellation but do not consume the touch yet.
3926 // This is useful when the user swipes through from the virtual key area
3927 // into the main display surface.
3928 mCurrentVirtualKey.down = false;
3929 if (!mCurrentVirtualKey.ignored) {
3930 #if DEBUG_VIRTUAL_KEYS
3931 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
3932 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
3934 dispatchVirtualKey(when, policyFlags,
3935 AKEY_EVENT_ACTION_UP,
3936 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
3937 | AKEY_EVENT_FLAG_CANCELED);
3941 if (mLastRawPointerData.touchingIdBits.isEmpty()
3942 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3943 // Pointer just went down. Check for virtual key press or off-screen touches.
3944 uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
3945 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3946 if (!isPointInsideSurface(pointer.x, pointer.y)) {
3947 // If exactly one pointer went down, check for virtual key hit.
3948 // Otherwise we will drop the entire stroke.
3949 if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
3950 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
3952 mCurrentVirtualKey.down = true;
3953 mCurrentVirtualKey.downTime = when;
3954 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
3955 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
3956 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
3957 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
3959 if (!mCurrentVirtualKey.ignored) {
3960 #if DEBUG_VIRTUAL_KEYS
3961 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
3962 mCurrentVirtualKey.keyCode,
3963 mCurrentVirtualKey.scanCode);
3965 dispatchVirtualKey(when, policyFlags,
3966 AKEY_EVENT_ACTION_DOWN,
3967 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
3975 // Disable all virtual key touches that happen within a short time interval of the
3976 // most recent touch within the screen area. The idea is to filter out stray
3977 // virtual key presses when interacting with the touch screen.
3979 // Problems we're trying to solve:
3981 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
3982 // virtual key area that is implemented by a separate touch panel and accidentally
3983 // triggers a virtual key.
3985 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
3986 // area and accidentally triggers a virtual key. This often happens when virtual keys
3987 // are layed out below the screen near to where the on screen keyboard's space bar
3989 if (mConfig.virtualKeyQuietTime > 0 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3990 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
3995 void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
3996 int32_t keyEventAction, int32_t keyEventFlags) {
3997 int32_t keyCode = mCurrentVirtualKey.keyCode;
3998 int32_t scanCode = mCurrentVirtualKey.scanCode;
3999 nsecs_t downTime = mCurrentVirtualKey.downTime;
4000 int32_t metaState = mContext->getGlobalMetaState();
4001 policyFlags |= POLICY_FLAG_VIRTUAL;
4003 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4004 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4005 getListener()->notifyKey(&args);
4008 void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
4009 BitSet32 currentIdBits = mCurrentCookedPointerData.touchingIdBits;
4010 BitSet32 lastIdBits = mLastCookedPointerData.touchingIdBits;
4011 int32_t metaState = getContext()->getGlobalMetaState();
4012 int32_t buttonState = mCurrentButtonState;
4014 if (currentIdBits == lastIdBits) {
4015 if (!currentIdBits.isEmpty()) {
4016 // No pointer id changes so this is a move event.
4017 // The listener takes care of batching moves so we don't have to deal with that here.
4018 dispatchMotion(when, policyFlags, mSource,
4019 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState,
4020 AMOTION_EVENT_EDGE_FLAG_NONE,
4021 mCurrentCookedPointerData.pointerProperties,
4022 mCurrentCookedPointerData.pointerCoords,
4023 mCurrentCookedPointerData.idToIndex,
4025 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4028 // There may be pointers going up and pointers going down and pointers moving
4029 // all at the same time.
4030 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4031 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4032 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4033 BitSet32 dispatchedIdBits(lastIdBits.value);
4035 // Update last coordinates of pointers that have moved so that we observe the new
4036 // pointer positions at the same time as other pointers that have just gone up.
4037 bool moveNeeded = updateMovedPointers(
4038 mCurrentCookedPointerData.pointerProperties,
4039 mCurrentCookedPointerData.pointerCoords,
4040 mCurrentCookedPointerData.idToIndex,
4041 mLastCookedPointerData.pointerProperties,
4042 mLastCookedPointerData.pointerCoords,
4043 mLastCookedPointerData.idToIndex,
4045 if (buttonState != mLastButtonState) {
4049 // Dispatch pointer up events.
4050 while (!upIdBits.isEmpty()) {
4051 uint32_t upId = upIdBits.clearFirstMarkedBit();
4053 dispatchMotion(when, policyFlags, mSource,
4054 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0,
4055 mLastCookedPointerData.pointerProperties,
4056 mLastCookedPointerData.pointerCoords,
4057 mLastCookedPointerData.idToIndex,
4058 dispatchedIdBits, upId,
4059 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4060 dispatchedIdBits.clearBit(upId);
4063 // Dispatch move events if any of the remaining pointers moved from their old locations.
4064 // Although applications receive new locations as part of individual pointer up
4065 // events, they do not generally handle them except when presented in a move event.
4067 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4068 dispatchMotion(when, policyFlags, mSource,
4069 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0,
4070 mCurrentCookedPointerData.pointerProperties,
4071 mCurrentCookedPointerData.pointerCoords,
4072 mCurrentCookedPointerData.idToIndex,
4073 dispatchedIdBits, -1,
4074 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4077 // Dispatch pointer down events using the new pointer locations.
4078 while (!downIdBits.isEmpty()) {
4079 uint32_t downId = downIdBits.clearFirstMarkedBit();
4080 dispatchedIdBits.markBit(downId);
4082 if (dispatchedIdBits.count() == 1) {
4083 // First pointer is going down. Set down time.
4087 dispatchMotion(when, policyFlags, mSource,
4088 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
4089 mCurrentCookedPointerData.pointerProperties,
4090 mCurrentCookedPointerData.pointerCoords,
4091 mCurrentCookedPointerData.idToIndex,
4092 dispatchedIdBits, downId,
4093 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4098 void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4099 if (mSentHoverEnter &&
4100 (mCurrentCookedPointerData.hoveringIdBits.isEmpty()
4101 || !mCurrentCookedPointerData.touchingIdBits.isEmpty())) {
4102 int32_t metaState = getContext()->getGlobalMetaState();
4103 dispatchMotion(when, policyFlags, mSource,
4104 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
4105 mLastCookedPointerData.pointerProperties,
4106 mLastCookedPointerData.pointerCoords,
4107 mLastCookedPointerData.idToIndex,
4108 mLastCookedPointerData.hoveringIdBits, -1,
4109 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4110 mSentHoverEnter = false;
4114 void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
4115 if (mCurrentCookedPointerData.touchingIdBits.isEmpty()
4116 && !mCurrentCookedPointerData.hoveringIdBits.isEmpty()) {
4117 int32_t metaState = getContext()->getGlobalMetaState();
4118 if (!mSentHoverEnter) {
4119 dispatchMotion(when, policyFlags, mSource,
4120 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
4121 mCurrentCookedPointerData.pointerProperties,
4122 mCurrentCookedPointerData.pointerCoords,
4123 mCurrentCookedPointerData.idToIndex,
4124 mCurrentCookedPointerData.hoveringIdBits, -1,
4125 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4126 mSentHoverEnter = true;
4129 dispatchMotion(when, policyFlags, mSource,
4130 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
4131 mCurrentCookedPointerData.pointerProperties,
4132 mCurrentCookedPointerData.pointerCoords,
4133 mCurrentCookedPointerData.idToIndex,
4134 mCurrentCookedPointerData.hoveringIdBits, -1,
4135 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4139 void TouchInputMapper::cookPointerData() {
4140 uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
4142 mCurrentCookedPointerData.clear();
4143 mCurrentCookedPointerData.pointerCount = currentPointerCount;
4144 mCurrentCookedPointerData.hoveringIdBits = mCurrentRawPointerData.hoveringIdBits;
4145 mCurrentCookedPointerData.touchingIdBits = mCurrentRawPointerData.touchingIdBits;
4147 // Walk through the the active pointers and map device coordinates onto
4148 // surface coordinates and adjust for display orientation.
4149 for (uint32_t i = 0; i < currentPointerCount; i++) {
4150 const RawPointerData::Pointer& in = mCurrentRawPointerData.pointers[i];
4153 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4154 switch (mCalibration.sizeCalibration) {
4155 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4156 case Calibration::SIZE_CALIBRATION_DIAMETER:
4157 case Calibration::SIZE_CALIBRATION_BOX:
4158 case Calibration::SIZE_CALIBRATION_AREA:
4159 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4160 touchMajor = in.touchMajor;
4161 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4162 toolMajor = in.toolMajor;
4163 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4164 size = mRawPointerAxes.touchMinor.valid
4165 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4166 } else if (mRawPointerAxes.touchMajor.valid) {
4167 toolMajor = touchMajor = in.touchMajor;
4168 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4169 ? in.touchMinor : in.touchMajor;
4170 size = mRawPointerAxes.touchMinor.valid
4171 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4172 } else if (mRawPointerAxes.toolMajor.valid) {
4173 touchMajor = toolMajor = in.toolMajor;
4174 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4175 ? in.toolMinor : in.toolMajor;
4176 size = mRawPointerAxes.toolMinor.valid
4177 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4179 ALOG_ASSERT(false, "No touch or tool axes. "
4180 "Size calibration should have been resolved to NONE.");
4188 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
4189 uint32_t touchingCount = mCurrentRawPointerData.touchingIdBits.count();
4190 if (touchingCount > 1) {
4191 touchMajor /= touchingCount;
4192 touchMinor /= touchingCount;
4193 toolMajor /= touchingCount;
4194 toolMinor /= touchingCount;
4195 size /= touchingCount;
4199 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4200 touchMajor *= mGeometricScale;
4201 touchMinor *= mGeometricScale;
4202 toolMajor *= mGeometricScale;
4203 toolMinor *= mGeometricScale;
4204 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4205 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4206 touchMinor = touchMajor;
4207 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4208 toolMinor = toolMajor;
4209 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4210 touchMinor = touchMajor;
4211 toolMinor = toolMajor;
4214 mCalibration.applySizeScaleAndBias(&touchMajor);
4215 mCalibration.applySizeScaleAndBias(&touchMinor);
4216 mCalibration.applySizeScaleAndBias(&toolMajor);
4217 mCalibration.applySizeScaleAndBias(&toolMinor);
4231 switch (mCalibration.pressureCalibration) {
4232 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4233 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4234 pressure = in.pressure * mPressureScale;
4237 pressure = in.isHovering ? 0 : 1;
4241 // Tilt and Orientation
4245 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4246 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4247 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4248 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4252 switch (mCalibration.orientationCalibration) {
4253 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4254 orientation = in.orientation * mOrientationScale;
4256 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4257 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4258 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4259 if (c1 != 0 || c2 != 0) {
4260 orientation = atan2f(c1, c2) * 0.5f;
4261 float confidence = hypotf(c1, c2);
4262 float scale = 1.0f + confidence / 16.0f;
4263 touchMajor *= scale;
4264 touchMinor /= scale;
4279 switch (mCalibration.distanceCalibration) {
4280 case Calibration::DISTANCE_CALIBRATION_SCALED:
4281 distance = in.distance * mDistanceScale;
4288 int32_t rawLeft, rawTop, rawRight, rawBottom;
4289 switch (mCalibration.coverageCalibration) {
4290 case Calibration::COVERAGE_CALIBRATION_BOX:
4291 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4292 rawRight = in.toolMinor & 0x0000ffff;
4293 rawBottom = in.toolMajor & 0x0000ffff;
4294 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4297 rawLeft = rawTop = rawRight = rawBottom = 0;
4301 // Adjust X,Y coords for device calibration
4302 // TODO: Adjust coverage coords?
4303 float xTransformed = in.x, yTransformed = in.y;
4304 mAffineTransform.applyTo(xTransformed, yTransformed);
4306 // Adjust X, Y, and coverage coords for surface orientation.
4308 float left, top, right, bottom;
4310 switch (mSurfaceOrientation) {
4311 case DISPLAY_ORIENTATION_90:
4312 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4313 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4314 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4315 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4316 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4317 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4318 orientation -= M_PI_2;
4319 if (orientation < mOrientedRanges.orientation.min) {
4320 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4323 case DISPLAY_ORIENTATION_180:
4324 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4325 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4326 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4327 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4328 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4329 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4330 orientation -= M_PI;
4331 if (orientation < mOrientedRanges.orientation.min) {
4332 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4335 case DISPLAY_ORIENTATION_270:
4336 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4337 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4338 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4339 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4340 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4341 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4342 orientation += M_PI_2;
4343 if (orientation > mOrientedRanges.orientation.max) {
4344 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4348 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4349 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4350 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4351 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4352 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4353 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4357 // Write output coords.
4358 PointerCoords& out = mCurrentCookedPointerData.pointerCoords[i];
4360 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4361 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4362 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4363 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4364 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4365 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4366 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4367 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4368 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4369 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4370 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4371 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4372 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4373 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4375 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4376 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4379 // Write output properties.
4380 PointerProperties& properties = mCurrentCookedPointerData.pointerProperties[i];
4381 uint32_t id = in.id;
4384 properties.toolType = in.toolType;
4387 mCurrentCookedPointerData.idToIndex[id] = i;
4391 void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4392 PointerUsage pointerUsage) {
4393 if (pointerUsage != mPointerUsage) {
4394 abortPointerUsage(when, policyFlags);
4395 mPointerUsage = pointerUsage;
4398 switch (mPointerUsage) {
4399 case POINTER_USAGE_GESTURES:
4400 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4402 case POINTER_USAGE_STYLUS:
4403 dispatchPointerStylus(when, policyFlags);
4405 case POINTER_USAGE_MOUSE:
4406 dispatchPointerMouse(when, policyFlags);
4413 void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4414 switch (mPointerUsage) {
4415 case POINTER_USAGE_GESTURES:
4416 abortPointerGestures(when, policyFlags);
4418 case POINTER_USAGE_STYLUS:
4419 abortPointerStylus(when, policyFlags);
4421 case POINTER_USAGE_MOUSE:
4422 abortPointerMouse(when, policyFlags);
4428 mPointerUsage = POINTER_USAGE_NONE;
4431 void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
4433 // Update current gesture coordinates.
4434 bool cancelPreviousGesture, finishPreviousGesture;
4435 bool sendEvents = preparePointerGestures(when,
4436 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
4440 if (finishPreviousGesture) {
4441 cancelPreviousGesture = false;
4444 // Update the pointer presentation and spots.
4445 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4446 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4447 if (finishPreviousGesture || cancelPreviousGesture) {
4448 mPointerController->clearSpots();
4450 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
4451 mPointerGesture.currentGestureIdToIndex,
4452 mPointerGesture.currentGestureIdBits);
4454 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4457 // Show or hide the pointer if needed.
4458 switch (mPointerGesture.currentGestureMode) {
4459 case PointerGesture::NEUTRAL:
4460 case PointerGesture::QUIET:
4461 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
4462 && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4463 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
4464 // Remind the user of where the pointer is after finishing a gesture with spots.
4465 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
4468 case PointerGesture::TAP:
4469 case PointerGesture::TAP_DRAG:
4470 case PointerGesture::BUTTON_CLICK_OR_DRAG:
4471 case PointerGesture::HOVER:
4472 case PointerGesture::PRESS:
4473 // Unfade the pointer when the current gesture manipulates the
4474 // area directly under the pointer.
4475 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4477 case PointerGesture::SWIPE:
4478 case PointerGesture::FREEFORM:
4479 // Fade the pointer when the current gesture manipulates a different
4480 // area and there are spots to guide the user experience.
4481 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4482 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4484 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4490 int32_t metaState = getContext()->getGlobalMetaState();
4491 int32_t buttonState = mCurrentButtonState;
4493 // Update last coordinates of pointers that have moved so that we observe the new
4494 // pointer positions at the same time as other pointers that have just gone up.
4495 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
4496 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
4497 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4498 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
4499 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
4500 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
4501 bool moveNeeded = false;
4502 if (down && !cancelPreviousGesture && !finishPreviousGesture
4503 && !mPointerGesture.lastGestureIdBits.isEmpty()
4504 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
4505 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
4506 & mPointerGesture.lastGestureIdBits.value);
4507 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
4508 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4509 mPointerGesture.lastGestureProperties,
4510 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4511 movedGestureIdBits);
4512 if (buttonState != mLastButtonState) {
4517 // Send motion events for all pointers that went up or were canceled.
4518 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
4519 if (!dispatchedGestureIdBits.isEmpty()) {
4520 if (cancelPreviousGesture) {
4521 dispatchMotion(when, policyFlags, mSource,
4522 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
4523 AMOTION_EVENT_EDGE_FLAG_NONE,
4524 mPointerGesture.lastGestureProperties,
4525 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4526 dispatchedGestureIdBits, -1,
4527 0, 0, mPointerGesture.downTime);
4529 dispatchedGestureIdBits.clear();
4531 BitSet32 upGestureIdBits;
4532 if (finishPreviousGesture) {
4533 upGestureIdBits = dispatchedGestureIdBits;
4535 upGestureIdBits.value = dispatchedGestureIdBits.value
4536 & ~mPointerGesture.currentGestureIdBits.value;
4538 while (!upGestureIdBits.isEmpty()) {
4539 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
4541 dispatchMotion(when, policyFlags, mSource,
4542 AMOTION_EVENT_ACTION_POINTER_UP, 0,
4543 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4544 mPointerGesture.lastGestureProperties,
4545 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4546 dispatchedGestureIdBits, id,
4547 0, 0, mPointerGesture.downTime);
4549 dispatchedGestureIdBits.clearBit(id);
4554 // Send motion events for all pointers that moved.
4556 dispatchMotion(when, policyFlags, mSource,
4557 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4558 mPointerGesture.currentGestureProperties,
4559 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4560 dispatchedGestureIdBits, -1,
4561 0, 0, mPointerGesture.downTime);
4564 // Send motion events for all pointers that went down.
4566 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
4567 & ~dispatchedGestureIdBits.value);
4568 while (!downGestureIdBits.isEmpty()) {
4569 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
4570 dispatchedGestureIdBits.markBit(id);
4572 if (dispatchedGestureIdBits.count() == 1) {
4573 mPointerGesture.downTime = when;
4576 dispatchMotion(when, policyFlags, mSource,
4577 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
4578 mPointerGesture.currentGestureProperties,
4579 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4580 dispatchedGestureIdBits, id,
4581 0, 0, mPointerGesture.downTime);
4585 // Send motion events for hover.
4586 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
4587 dispatchMotion(when, policyFlags, mSource,
4588 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
4589 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4590 mPointerGesture.currentGestureProperties,
4591 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4592 mPointerGesture.currentGestureIdBits, -1,
4593 0, 0, mPointerGesture.downTime);
4594 } else if (dispatchedGestureIdBits.isEmpty()
4595 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
4596 // Synthesize a hover move event after all pointers go up to indicate that
4597 // the pointer is hovering again even if the user is not currently touching
4598 // the touch pad. This ensures that a view will receive a fresh hover enter
4599 // event after a tap.
4601 mPointerController->getPosition(&x, &y);
4603 PointerProperties pointerProperties;
4604 pointerProperties.clear();
4605 pointerProperties.id = 0;
4606 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
4608 PointerCoords pointerCoords;
4609 pointerCoords.clear();
4610 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4611 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4613 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
4614 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
4615 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4616 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
4617 0, 0, mPointerGesture.downTime);
4618 getListener()->notifyMotion(&args);
4622 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
4624 mPointerGesture.lastGestureIdBits.clear();
4626 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
4627 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
4628 uint32_t id = idBits.clearFirstMarkedBit();
4629 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4630 mPointerGesture.lastGestureProperties[index].copyFrom(
4631 mPointerGesture.currentGestureProperties[index]);
4632 mPointerGesture.lastGestureCoords[index].copyFrom(
4633 mPointerGesture.currentGestureCoords[index]);
4634 mPointerGesture.lastGestureIdToIndex[id] = index;
4639 void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
4640 // Cancel previously dispatches pointers.
4641 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
4642 int32_t metaState = getContext()->getGlobalMetaState();
4643 int32_t buttonState = mCurrentButtonState;
4644 dispatchMotion(when, policyFlags, mSource,
4645 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
4646 AMOTION_EVENT_EDGE_FLAG_NONE,
4647 mPointerGesture.lastGestureProperties,
4648 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4649 mPointerGesture.lastGestureIdBits, -1,
4650 0, 0, mPointerGesture.downTime);
4653 // Reset the current pointer gesture.
4654 mPointerGesture.reset();
4655 mPointerVelocityControl.reset();
4657 // Remove any current spots.
4658 if (mPointerController != NULL) {
4659 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4660 mPointerController->clearSpots();
4664 bool TouchInputMapper::preparePointerGestures(nsecs_t when,
4665 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
4666 *outCancelPreviousGesture = false;
4667 *outFinishPreviousGesture = false;
4669 // Handle TAP timeout.
4672 ALOGD("Gestures: Processing timeout");
4675 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
4676 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
4677 // The tap/drag timeout has not yet expired.
4678 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
4679 + mConfig.pointerGestureTapDragInterval);
4681 // The tap is finished.
4683 ALOGD("Gestures: TAP finished");
4685 *outFinishPreviousGesture = true;
4687 mPointerGesture.activeGestureId = -1;
4688 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
4689 mPointerGesture.currentGestureIdBits.clear();
4691 mPointerVelocityControl.reset();
4696 // We did not handle this timeout.
4700 const uint32_t currentFingerCount = mCurrentFingerIdBits.count();
4701 const uint32_t lastFingerCount = mLastFingerIdBits.count();
4703 // Update the velocity tracker.
4705 VelocityTracker::Position positions[MAX_POINTERS];
4707 for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); count++) {
4708 uint32_t id = idBits.clearFirstMarkedBit();
4709 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
4710 positions[count].x = pointer.x * mPointerXMovementScale;
4711 positions[count].y = pointer.y * mPointerYMovementScale;
4713 mPointerGesture.velocityTracker.addMovement(when,
4714 mCurrentFingerIdBits, positions);
4717 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
4718 // to NEUTRAL, then we should not generate tap event.
4719 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
4720 && mPointerGesture.lastGestureMode != PointerGesture::TAP
4721 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
4722 mPointerGesture.resetTap();
4725 // Pick a new active touch id if needed.
4726 // Choose an arbitrary pointer that just went down, if there is one.
4727 // Otherwise choose an arbitrary remaining pointer.
4728 // This guarantees we always have an active touch id when there is at least one pointer.
4729 // We keep the same active touch id for as long as possible.
4730 bool activeTouchChanged = false;
4731 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
4732 int32_t activeTouchId = lastActiveTouchId;
4733 if (activeTouchId < 0) {
4734 if (!mCurrentFingerIdBits.isEmpty()) {
4735 activeTouchChanged = true;
4736 activeTouchId = mPointerGesture.activeTouchId =
4737 mCurrentFingerIdBits.firstMarkedBit();
4738 mPointerGesture.firstTouchTime = when;
4740 } else if (!mCurrentFingerIdBits.hasBit(activeTouchId)) {
4741 activeTouchChanged = true;
4742 if (!mCurrentFingerIdBits.isEmpty()) {
4743 activeTouchId = mPointerGesture.activeTouchId =
4744 mCurrentFingerIdBits.firstMarkedBit();
4746 activeTouchId = mPointerGesture.activeTouchId = -1;
4750 // Determine whether we are in quiet time.
4751 bool isQuietTime = false;
4752 if (activeTouchId < 0) {
4753 mPointerGesture.resetQuietTime();
4755 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
4757 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
4758 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4759 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
4760 && currentFingerCount < 2) {
4761 // Enter quiet time when exiting swipe or freeform state.
4762 // This is to prevent accidentally entering the hover state and flinging the
4763 // pointer when finishing a swipe and there is still one pointer left onscreen.
4765 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4766 && currentFingerCount >= 2
4767 && !isPointerDown(mCurrentButtonState)) {
4768 // Enter quiet time when releasing the button and there are still two or more
4769 // fingers down. This may indicate that one finger was used to press the button
4770 // but it has not gone up yet.
4774 mPointerGesture.quietTime = when;
4779 // Switch states based on button and pointer state.
4781 // Case 1: Quiet time. (QUIET)
4783 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
4784 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
4786 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
4787 *outFinishPreviousGesture = true;
4790 mPointerGesture.activeGestureId = -1;
4791 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
4792 mPointerGesture.currentGestureIdBits.clear();
4794 mPointerVelocityControl.reset();
4795 } else if (isPointerDown(mCurrentButtonState)) {
4796 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
4797 // The pointer follows the active touch point.
4798 // Emit DOWN, MOVE, UP events at the pointer location.
4800 // Only the active touch matters; other fingers are ignored. This policy helps
4801 // to handle the case where the user places a second finger on the touch pad
4802 // to apply the necessary force to depress an integrated button below the surface.
4803 // We don't want the second finger to be delivered to applications.
4805 // For this to work well, we need to make sure to track the pointer that is really
4806 // active. If the user first puts one finger down to click then adds another
4807 // finger to drag then the active pointer should switch to the finger that is
4810 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
4811 "currentFingerCount=%d", activeTouchId, currentFingerCount);
4813 // Reset state when just starting.
4814 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
4815 *outFinishPreviousGesture = true;
4816 mPointerGesture.activeGestureId = 0;
4819 // Switch pointers if needed.
4820 // Find the fastest pointer and follow it.
4821 if (activeTouchId >= 0 && currentFingerCount > 1) {
4822 int32_t bestId = -1;
4823 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
4824 for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); ) {
4825 uint32_t id = idBits.clearFirstMarkedBit();
4827 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
4828 float speed = hypotf(vx, vy);
4829 if (speed > bestSpeed) {
4835 if (bestId >= 0 && bestId != activeTouchId) {
4836 mPointerGesture.activeTouchId = activeTouchId = bestId;
4837 activeTouchChanged = true;
4839 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
4840 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
4845 if (activeTouchId >= 0 && mLastFingerIdBits.hasBit(activeTouchId)) {
4846 const RawPointerData::Pointer& currentPointer =
4847 mCurrentRawPointerData.pointerForId(activeTouchId);
4848 const RawPointerData::Pointer& lastPointer =
4849 mLastRawPointerData.pointerForId(activeTouchId);
4850 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
4851 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
4853 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
4854 mPointerVelocityControl.move(when, &deltaX, &deltaY);
4856 // Move the pointer using a relative motion.
4857 // When using spots, the click will occur at the position of the anchor
4858 // spot and all other spots will move there.
4859 mPointerController->move(deltaX, deltaY);
4861 mPointerVelocityControl.reset();
4865 mPointerController->getPosition(&x, &y);
4867 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
4868 mPointerGesture.currentGestureIdBits.clear();
4869 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4870 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4871 mPointerGesture.currentGestureProperties[0].clear();
4872 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4873 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
4874 mPointerGesture.currentGestureCoords[0].clear();
4875 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4876 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4877 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4878 } else if (currentFingerCount == 0) {
4879 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
4880 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
4881 *outFinishPreviousGesture = true;
4884 // Watch for taps coming out of HOVER or TAP_DRAG mode.
4885 // Checking for taps after TAP_DRAG allows us to detect double-taps.
4886 bool tapped = false;
4887 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
4888 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
4889 && lastFingerCount == 1) {
4890 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
4892 mPointerController->getPosition(&x, &y);
4893 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
4894 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
4896 ALOGD("Gestures: TAP");
4899 mPointerGesture.tapUpTime = when;
4900 getContext()->requestTimeoutAtTime(when
4901 + mConfig.pointerGestureTapDragInterval);
4903 mPointerGesture.activeGestureId = 0;
4904 mPointerGesture.currentGestureMode = PointerGesture::TAP;
4905 mPointerGesture.currentGestureIdBits.clear();
4906 mPointerGesture.currentGestureIdBits.markBit(
4907 mPointerGesture.activeGestureId);
4908 mPointerGesture.currentGestureIdToIndex[
4909 mPointerGesture.activeGestureId] = 0;
4910 mPointerGesture.currentGestureProperties[0].clear();
4911 mPointerGesture.currentGestureProperties[0].id =
4912 mPointerGesture.activeGestureId;
4913 mPointerGesture.currentGestureProperties[0].toolType =
4914 AMOTION_EVENT_TOOL_TYPE_FINGER;
4915 mPointerGesture.currentGestureCoords[0].clear();
4916 mPointerGesture.currentGestureCoords[0].setAxisValue(
4917 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
4918 mPointerGesture.currentGestureCoords[0].setAxisValue(
4919 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
4920 mPointerGesture.currentGestureCoords[0].setAxisValue(
4921 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4926 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
4927 x - mPointerGesture.tapX,
4928 y - mPointerGesture.tapY);
4933 if (mPointerGesture.tapDownTime != LLONG_MIN) {
4934 ALOGD("Gestures: Not a TAP, %0.3fms since down",
4935 (when - mPointerGesture.tapDownTime) * 0.000001f);
4937 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
4943 mPointerVelocityControl.reset();
4947 ALOGD("Gestures: NEUTRAL");
4949 mPointerGesture.activeGestureId = -1;
4950 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
4951 mPointerGesture.currentGestureIdBits.clear();
4953 } else if (currentFingerCount == 1) {
4954 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
4955 // The pointer follows the active touch point.
4956 // When in HOVER, emit HOVER_MOVE events at the pointer location.
4957 // When in TAP_DRAG, emit MOVE events at the pointer location.
4958 ALOG_ASSERT(activeTouchId >= 0);
4960 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
4961 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
4962 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
4964 mPointerController->getPosition(&x, &y);
4965 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
4966 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
4967 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4970 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
4971 x - mPointerGesture.tapX,
4972 y - mPointerGesture.tapY);
4977 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
4978 (when - mPointerGesture.tapUpTime) * 0.000001f);
4981 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
4982 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4985 if (mLastFingerIdBits.hasBit(activeTouchId)) {
4986 const RawPointerData::Pointer& currentPointer =
4987 mCurrentRawPointerData.pointerForId(activeTouchId);
4988 const RawPointerData::Pointer& lastPointer =
4989 mLastRawPointerData.pointerForId(activeTouchId);
4990 float deltaX = (currentPointer.x - lastPointer.x)
4991 * mPointerXMovementScale;
4992 float deltaY = (currentPointer.y - lastPointer.y)
4993 * mPointerYMovementScale;
4995 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
4996 mPointerVelocityControl.move(when, &deltaX, &deltaY);
4998 // Move the pointer using a relative motion.
4999 // When using spots, the hover or drag will occur at the position of the anchor spot.
5000 mPointerController->move(deltaX, deltaY);
5002 mPointerVelocityControl.reset();
5006 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5008 ALOGD("Gestures: TAP_DRAG");
5013 ALOGD("Gestures: HOVER");
5015 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5016 *outFinishPreviousGesture = true;
5018 mPointerGesture.activeGestureId = 0;
5023 mPointerController->getPosition(&x, &y);
5025 mPointerGesture.currentGestureIdBits.clear();
5026 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5027 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5028 mPointerGesture.currentGestureProperties[0].clear();
5029 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5030 mPointerGesture.currentGestureProperties[0].toolType =
5031 AMOTION_EVENT_TOOL_TYPE_FINGER;
5032 mPointerGesture.currentGestureCoords[0].clear();
5033 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5034 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5035 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5036 down ? 1.0f : 0.0f);
5038 if (lastFingerCount == 0 && currentFingerCount != 0) {
5039 mPointerGesture.resetTap();
5040 mPointerGesture.tapDownTime = when;
5041 mPointerGesture.tapX = x;
5042 mPointerGesture.tapY = y;
5045 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5046 // We need to provide feedback for each finger that goes down so we cannot wait
5047 // for the fingers to move before deciding what to do.
5049 // The ambiguous case is deciding what to do when there are two fingers down but they
5050 // have not moved enough to determine whether they are part of a drag or part of a
5051 // freeform gesture, or just a press or long-press at the pointer location.
5053 // When there are two fingers we start with the PRESS hypothesis and we generate a
5054 // down at the pointer location.
5056 // When the two fingers move enough or when additional fingers are added, we make
5057 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5058 ALOG_ASSERT(activeTouchId >= 0);
5060 bool settled = when >= mPointerGesture.firstTouchTime
5061 + mConfig.pointerGestureMultitouchSettleInterval;
5062 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5063 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5064 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5065 *outFinishPreviousGesture = true;
5066 } else if (!settled && currentFingerCount > lastFingerCount) {
5067 // Additional pointers have gone down but not yet settled.
5068 // Reset the gesture.
5070 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5071 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5072 + mConfig.pointerGestureMultitouchSettleInterval - when)
5075 *outCancelPreviousGesture = true;
5077 // Continue previous gesture.
5078 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5081 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5082 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5083 mPointerGesture.activeGestureId = 0;
5084 mPointerGesture.referenceIdBits.clear();
5085 mPointerVelocityControl.reset();
5087 // Use the centroid and pointer location as the reference points for the gesture.
5089 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5090 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5091 + mConfig.pointerGestureMultitouchSettleInterval - when)
5094 mCurrentRawPointerData.getCentroidOfTouchingPointers(
5095 &mPointerGesture.referenceTouchX,
5096 &mPointerGesture.referenceTouchY);
5097 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5098 &mPointerGesture.referenceGestureY);
5101 // Clear the reference deltas for fingers not yet included in the reference calculation.
5102 for (BitSet32 idBits(mCurrentFingerIdBits.value
5103 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5104 uint32_t id = idBits.clearFirstMarkedBit();
5105 mPointerGesture.referenceDeltas[id].dx = 0;
5106 mPointerGesture.referenceDeltas[id].dy = 0;
5108 mPointerGesture.referenceIdBits = mCurrentFingerIdBits;
5110 // Add delta for all fingers and calculate a common movement delta.
5111 float commonDeltaX = 0, commonDeltaY = 0;
5112 BitSet32 commonIdBits(mLastFingerIdBits.value
5113 & mCurrentFingerIdBits.value);
5114 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5115 bool first = (idBits == commonIdBits);
5116 uint32_t id = idBits.clearFirstMarkedBit();
5117 const RawPointerData::Pointer& cpd = mCurrentRawPointerData.pointerForId(id);
5118 const RawPointerData::Pointer& lpd = mLastRawPointerData.pointerForId(id);
5119 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5120 delta.dx += cpd.x - lpd.x;
5121 delta.dy += cpd.y - lpd.y;
5124 commonDeltaX = delta.dx;
5125 commonDeltaY = delta.dy;
5127 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5128 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5132 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5133 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5134 float dist[MAX_POINTER_ID + 1];
5135 int32_t distOverThreshold = 0;
5136 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5137 uint32_t id = idBits.clearFirstMarkedBit();
5138 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5139 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5140 delta.dy * mPointerYZoomScale);
5141 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5142 distOverThreshold += 1;
5146 // Only transition when at least two pointers have moved further than
5147 // the minimum distance threshold.
5148 if (distOverThreshold >= 2) {
5149 if (currentFingerCount > 2) {
5150 // There are more than two pointers, switch to FREEFORM.
5152 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5153 currentFingerCount);
5155 *outCancelPreviousGesture = true;
5156 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5158 // There are exactly two pointers.
5159 BitSet32 idBits(mCurrentFingerIdBits);
5160 uint32_t id1 = idBits.clearFirstMarkedBit();
5161 uint32_t id2 = idBits.firstMarkedBit();
5162 const RawPointerData::Pointer& p1 = mCurrentRawPointerData.pointerForId(id1);
5163 const RawPointerData::Pointer& p2 = mCurrentRawPointerData.pointerForId(id2);
5164 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5165 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5166 // There are two pointers but they are too far apart for a SWIPE,
5167 // switch to FREEFORM.
5169 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5170 mutualDistance, mPointerGestureMaxSwipeWidth);
5172 *outCancelPreviousGesture = true;
5173 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5175 // There are two pointers. Wait for both pointers to start moving
5176 // before deciding whether this is a SWIPE or FREEFORM gesture.
5177 float dist1 = dist[id1];
5178 float dist2 = dist[id2];
5179 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5180 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5181 // Calculate the dot product of the displacement vectors.
5182 // When the vectors are oriented in approximately the same direction,
5183 // the angle betweeen them is near zero and the cosine of the angle
5184 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5185 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5186 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5187 float dx1 = delta1.dx * mPointerXZoomScale;
5188 float dy1 = delta1.dy * mPointerYZoomScale;
5189 float dx2 = delta2.dx * mPointerXZoomScale;
5190 float dy2 = delta2.dy * mPointerYZoomScale;
5191 float dot = dx1 * dx2 + dy1 * dy2;
5192 float cosine = dot / (dist1 * dist2); // denominator always > 0
5193 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5194 // Pointers are moving in the same direction. Switch to SWIPE.
5196 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5197 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5198 "cosine %0.3f >= %0.3f",
5199 dist1, mConfig.pointerGestureMultitouchMinDistance,
5200 dist2, mConfig.pointerGestureMultitouchMinDistance,
5201 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5203 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5205 // Pointers are moving in different directions. Switch to FREEFORM.
5207 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5208 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5209 "cosine %0.3f < %0.3f",
5210 dist1, mConfig.pointerGestureMultitouchMinDistance,
5211 dist2, mConfig.pointerGestureMultitouchMinDistance,
5212 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5214 *outCancelPreviousGesture = true;
5215 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5221 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5222 // Switch from SWIPE to FREEFORM if additional pointers go down.
5223 // Cancel previous gesture.
5224 if (currentFingerCount > 2) {
5226 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5227 currentFingerCount);
5229 *outCancelPreviousGesture = true;
5230 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5234 // Move the reference points based on the overall group motion of the fingers
5235 // except in PRESS mode while waiting for a transition to occur.
5236 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5237 && (commonDeltaX || commonDeltaY)) {
5238 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5239 uint32_t id = idBits.clearFirstMarkedBit();
5240 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5245 mPointerGesture.referenceTouchX += commonDeltaX;
5246 mPointerGesture.referenceTouchY += commonDeltaY;
5248 commonDeltaX *= mPointerXMovementScale;
5249 commonDeltaY *= mPointerYMovementScale;
5251 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5252 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5254 mPointerGesture.referenceGestureX += commonDeltaX;
5255 mPointerGesture.referenceGestureY += commonDeltaY;
5259 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5260 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5261 // PRESS or SWIPE mode.
5263 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5264 "activeGestureId=%d, currentTouchPointerCount=%d",
5265 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5267 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5269 mPointerGesture.currentGestureIdBits.clear();
5270 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5271 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5272 mPointerGesture.currentGestureProperties[0].clear();
5273 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5274 mPointerGesture.currentGestureProperties[0].toolType =
5275 AMOTION_EVENT_TOOL_TYPE_FINGER;
5276 mPointerGesture.currentGestureCoords[0].clear();
5277 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5278 mPointerGesture.referenceGestureX);
5279 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5280 mPointerGesture.referenceGestureY);
5281 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5282 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5285 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5286 "activeGestureId=%d, currentTouchPointerCount=%d",
5287 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5289 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5291 mPointerGesture.currentGestureIdBits.clear();
5293 BitSet32 mappedTouchIdBits;
5294 BitSet32 usedGestureIdBits;
5295 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5296 // Initially, assign the active gesture id to the active touch point
5297 // if there is one. No other touch id bits are mapped yet.
5298 if (!*outCancelPreviousGesture) {
5299 mappedTouchIdBits.markBit(activeTouchId);
5300 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5301 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5302 mPointerGesture.activeGestureId;
5304 mPointerGesture.activeGestureId = -1;
5307 // Otherwise, assume we mapped all touches from the previous frame.
5308 // Reuse all mappings that are still applicable.
5309 mappedTouchIdBits.value = mLastFingerIdBits.value
5310 & mCurrentFingerIdBits.value;
5311 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5313 // Check whether we need to choose a new active gesture id because the
5314 // current went went up.
5315 for (BitSet32 upTouchIdBits(mLastFingerIdBits.value
5316 & ~mCurrentFingerIdBits.value);
5317 !upTouchIdBits.isEmpty(); ) {
5318 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5319 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5320 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5321 mPointerGesture.activeGestureId = -1;
5328 ALOGD("Gestures: FREEFORM follow up "
5329 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5330 "activeGestureId=%d",
5331 mappedTouchIdBits.value, usedGestureIdBits.value,
5332 mPointerGesture.activeGestureId);
5335 BitSet32 idBits(mCurrentFingerIdBits);
5336 for (uint32_t i = 0; i < currentFingerCount; i++) {
5337 uint32_t touchId = idBits.clearFirstMarkedBit();
5339 if (!mappedTouchIdBits.hasBit(touchId)) {
5340 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5341 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5343 ALOGD("Gestures: FREEFORM "
5344 "new mapping for touch id %d -> gesture id %d",
5345 touchId, gestureId);
5348 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5350 ALOGD("Gestures: FREEFORM "
5351 "existing mapping for touch id %d -> gesture id %d",
5352 touchId, gestureId);
5355 mPointerGesture.currentGestureIdBits.markBit(gestureId);
5356 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5358 const RawPointerData::Pointer& pointer =
5359 mCurrentRawPointerData.pointerForId(touchId);
5360 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5361 * mPointerXZoomScale;
5362 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5363 * mPointerYZoomScale;
5364 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5366 mPointerGesture.currentGestureProperties[i].clear();
5367 mPointerGesture.currentGestureProperties[i].id = gestureId;
5368 mPointerGesture.currentGestureProperties[i].toolType =
5369 AMOTION_EVENT_TOOL_TYPE_FINGER;
5370 mPointerGesture.currentGestureCoords[i].clear();
5371 mPointerGesture.currentGestureCoords[i].setAxisValue(
5372 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5373 mPointerGesture.currentGestureCoords[i].setAxisValue(
5374 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5375 mPointerGesture.currentGestureCoords[i].setAxisValue(
5376 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5379 if (mPointerGesture.activeGestureId < 0) {
5380 mPointerGesture.activeGestureId =
5381 mPointerGesture.currentGestureIdBits.firstMarkedBit();
5383 ALOGD("Gestures: FREEFORM new "
5384 "activeGestureId=%d", mPointerGesture.activeGestureId);
5390 mPointerController->setButtonState(mCurrentButtonState);
5393 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5394 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5395 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5396 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5397 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5398 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5399 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5400 uint32_t id = idBits.clearFirstMarkedBit();
5401 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5402 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5403 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5404 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
5405 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5406 id, index, properties.toolType,
5407 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5408 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5409 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5411 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5412 uint32_t id = idBits.clearFirstMarkedBit();
5413 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5414 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5415 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5416 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
5417 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5418 id, index, properties.toolType,
5419 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5420 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5421 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5427 void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
5428 mPointerSimple.currentCoords.clear();
5429 mPointerSimple.currentProperties.clear();
5431 bool down, hovering;
5432 if (!mCurrentStylusIdBits.isEmpty()) {
5433 uint32_t id = mCurrentStylusIdBits.firstMarkedBit();
5434 uint32_t index = mCurrentCookedPointerData.idToIndex[id];
5435 float x = mCurrentCookedPointerData.pointerCoords[index].getX();
5436 float y = mCurrentCookedPointerData.pointerCoords[index].getY();
5437 mPointerController->setPosition(x, y);
5439 hovering = mCurrentCookedPointerData.hoveringIdBits.hasBit(id);
5442 mPointerController->getPosition(&x, &y);
5443 mPointerSimple.currentCoords.copyFrom(mCurrentCookedPointerData.pointerCoords[index]);
5444 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5445 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5446 mPointerSimple.currentProperties.id = 0;
5447 mPointerSimple.currentProperties.toolType =
5448 mCurrentCookedPointerData.pointerProperties[index].toolType;
5454 dispatchPointerSimple(when, policyFlags, down, hovering);
5457 void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
5458 abortPointerSimple(when, policyFlags);
5461 void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
5462 mPointerSimple.currentCoords.clear();
5463 mPointerSimple.currentProperties.clear();
5465 bool down, hovering;
5466 if (!mCurrentMouseIdBits.isEmpty()) {
5467 uint32_t id = mCurrentMouseIdBits.firstMarkedBit();
5468 uint32_t currentIndex = mCurrentRawPointerData.idToIndex[id];
5469 if (mLastMouseIdBits.hasBit(id)) {
5470 uint32_t lastIndex = mCurrentRawPointerData.idToIndex[id];
5471 float deltaX = (mCurrentRawPointerData.pointers[currentIndex].x
5472 - mLastRawPointerData.pointers[lastIndex].x)
5473 * mPointerXMovementScale;
5474 float deltaY = (mCurrentRawPointerData.pointers[currentIndex].y
5475 - mLastRawPointerData.pointers[lastIndex].y)
5476 * mPointerYMovementScale;
5478 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5479 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5481 mPointerController->move(deltaX, deltaY);
5483 mPointerVelocityControl.reset();
5486 down = isPointerDown(mCurrentButtonState);
5490 mPointerController->getPosition(&x, &y);
5491 mPointerSimple.currentCoords.copyFrom(
5492 mCurrentCookedPointerData.pointerCoords[currentIndex]);
5493 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5494 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5495 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5496 hovering ? 0.0f : 1.0f);
5497 mPointerSimple.currentProperties.id = 0;
5498 mPointerSimple.currentProperties.toolType =
5499 mCurrentCookedPointerData.pointerProperties[currentIndex].toolType;
5501 mPointerVelocityControl.reset();
5507 dispatchPointerSimple(when, policyFlags, down, hovering);
5510 void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
5511 abortPointerSimple(when, policyFlags);
5513 mPointerVelocityControl.reset();
5516 void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
5517 bool down, bool hovering) {
5518 int32_t metaState = getContext()->getGlobalMetaState();
5520 if (mPointerController != NULL) {
5521 if (down || hovering) {
5522 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5523 mPointerController->clearSpots();
5524 mPointerController->setButtonState(mCurrentButtonState);
5525 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5526 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
5527 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5531 if (mPointerSimple.down && !down) {
5532 mPointerSimple.down = false;
5535 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5536 AMOTION_EVENT_ACTION_UP, 0, metaState, mLastButtonState, 0,
5537 mViewport.displayId,
5538 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
5539 mOrientedXPrecision, mOrientedYPrecision,
5540 mPointerSimple.downTime);
5541 getListener()->notifyMotion(&args);
5544 if (mPointerSimple.hovering && !hovering) {
5545 mPointerSimple.hovering = false;
5548 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5549 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
5550 mViewport.displayId,
5551 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
5552 mOrientedXPrecision, mOrientedYPrecision,
5553 mPointerSimple.downTime);
5554 getListener()->notifyMotion(&args);
5558 if (!mPointerSimple.down) {
5559 mPointerSimple.down = true;
5560 mPointerSimple.downTime = when;
5563 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5564 AMOTION_EVENT_ACTION_DOWN, 0, metaState, mCurrentButtonState, 0,
5565 mViewport.displayId,
5566 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5567 mOrientedXPrecision, mOrientedYPrecision,
5568 mPointerSimple.downTime);
5569 getListener()->notifyMotion(&args);
5573 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5574 AMOTION_EVENT_ACTION_MOVE, 0, metaState, mCurrentButtonState, 0,
5575 mViewport.displayId,
5576 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5577 mOrientedXPrecision, mOrientedYPrecision,
5578 mPointerSimple.downTime);
5579 getListener()->notifyMotion(&args);
5583 if (!mPointerSimple.hovering) {
5584 mPointerSimple.hovering = true;
5586 // Send hover enter.
5587 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5588 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
5589 mViewport.displayId,
5590 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5591 mOrientedXPrecision, mOrientedYPrecision,
5592 mPointerSimple.downTime);
5593 getListener()->notifyMotion(&args);
5597 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5598 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
5599 mViewport.displayId,
5600 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5601 mOrientedXPrecision, mOrientedYPrecision,
5602 mPointerSimple.downTime);
5603 getListener()->notifyMotion(&args);
5606 if (mCurrentRawVScroll || mCurrentRawHScroll) {
5607 float vscroll = mCurrentRawVScroll;
5608 float hscroll = mCurrentRawHScroll;
5609 mWheelYVelocityControl.move(when, NULL, &vscroll);
5610 mWheelXVelocityControl.move(when, &hscroll, NULL);
5613 PointerCoords pointerCoords;
5614 pointerCoords.copyFrom(mPointerSimple.currentCoords);
5615 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
5616 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
5618 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5619 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, mCurrentButtonState, 0,
5620 mViewport.displayId,
5621 1, &mPointerSimple.currentProperties, &pointerCoords,
5622 mOrientedXPrecision, mOrientedYPrecision,
5623 mPointerSimple.downTime);
5624 getListener()->notifyMotion(&args);
5628 if (down || hovering) {
5629 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
5630 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
5632 mPointerSimple.reset();
5636 void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
5637 mPointerSimple.currentCoords.clear();
5638 mPointerSimple.currentProperties.clear();
5640 dispatchPointerSimple(when, policyFlags, false, false);
5643 void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
5644 int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
5645 const PointerProperties* properties, const PointerCoords* coords,
5646 const uint32_t* idToIndex, BitSet32 idBits,
5647 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
5648 PointerCoords pointerCoords[MAX_POINTERS];
5649 PointerProperties pointerProperties[MAX_POINTERS];
5650 uint32_t pointerCount = 0;
5651 while (!idBits.isEmpty()) {
5652 uint32_t id = idBits.clearFirstMarkedBit();
5653 uint32_t index = idToIndex[id];
5654 pointerProperties[pointerCount].copyFrom(properties[index]);
5655 pointerCoords[pointerCount].copyFrom(coords[index]);
5657 if (changedId >= 0 && id == uint32_t(changedId)) {
5658 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
5664 ALOG_ASSERT(pointerCount != 0);
5666 if (changedId >= 0 && pointerCount == 1) {
5667 // Replace initial down and final up action.
5668 // We can compare the action without masking off the changed pointer index
5669 // because we know the index is 0.
5670 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
5671 action = AMOTION_EVENT_ACTION_DOWN;
5672 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
5673 action = AMOTION_EVENT_ACTION_UP;
5680 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
5681 action, flags, metaState, buttonState, edgeFlags,
5682 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
5683 xPrecision, yPrecision, downTime);
5684 getListener()->notifyMotion(&args);
5687 bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
5688 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
5689 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
5690 BitSet32 idBits) const {
5691 bool changed = false;
5692 while (!idBits.isEmpty()) {
5693 uint32_t id = idBits.clearFirstMarkedBit();
5694 uint32_t inIndex = inIdToIndex[id];
5695 uint32_t outIndex = outIdToIndex[id];
5697 const PointerProperties& curInProperties = inProperties[inIndex];
5698 const PointerCoords& curInCoords = inCoords[inIndex];
5699 PointerProperties& curOutProperties = outProperties[outIndex];
5700 PointerCoords& curOutCoords = outCoords[outIndex];
5702 if (curInProperties != curOutProperties) {
5703 curOutProperties.copyFrom(curInProperties);
5707 if (curInCoords != curOutCoords) {
5708 curOutCoords.copyFrom(curInCoords);
5715 void TouchInputMapper::fadePointer() {
5716 if (mPointerController != NULL) {
5717 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5721 bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
5722 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
5723 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
5726 const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
5727 int32_t x, int32_t y) {
5728 size_t numVirtualKeys = mVirtualKeys.size();
5729 for (size_t i = 0; i < numVirtualKeys; i++) {
5730 const VirtualKey& virtualKey = mVirtualKeys[i];
5732 #if DEBUG_VIRTUAL_KEYS
5733 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
5734 "left=%d, top=%d, right=%d, bottom=%d",
5736 virtualKey.keyCode, virtualKey.scanCode,
5737 virtualKey.hitLeft, virtualKey.hitTop,
5738 virtualKey.hitRight, virtualKey.hitBottom);
5741 if (virtualKey.isHit(x, y)) {
5742 return & virtualKey;
5749 void TouchInputMapper::assignPointerIds() {
5750 uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
5751 uint32_t lastPointerCount = mLastRawPointerData.pointerCount;
5753 mCurrentRawPointerData.clearIdBits();
5755 if (currentPointerCount == 0) {
5756 // No pointers to assign.
5760 if (lastPointerCount == 0) {
5761 // All pointers are new.
5762 for (uint32_t i = 0; i < currentPointerCount; i++) {
5764 mCurrentRawPointerData.pointers[i].id = id;
5765 mCurrentRawPointerData.idToIndex[id] = i;
5766 mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(i));
5771 if (currentPointerCount == 1 && lastPointerCount == 1
5772 && mCurrentRawPointerData.pointers[0].toolType
5773 == mLastRawPointerData.pointers[0].toolType) {
5774 // Only one pointer and no change in count so it must have the same id as before.
5775 uint32_t id = mLastRawPointerData.pointers[0].id;
5776 mCurrentRawPointerData.pointers[0].id = id;
5777 mCurrentRawPointerData.idToIndex[id] = 0;
5778 mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(0));
5783 // We build a heap of squared euclidean distances between current and last pointers
5784 // associated with the current and last pointer indices. Then, we find the best
5785 // match (by distance) for each current pointer.
5786 // The pointers must have the same tool type but it is possible for them to
5787 // transition from hovering to touching or vice-versa while retaining the same id.
5788 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
5790 uint32_t heapSize = 0;
5791 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
5792 currentPointerIndex++) {
5793 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
5794 lastPointerIndex++) {
5795 const RawPointerData::Pointer& currentPointer =
5796 mCurrentRawPointerData.pointers[currentPointerIndex];
5797 const RawPointerData::Pointer& lastPointer =
5798 mLastRawPointerData.pointers[lastPointerIndex];
5799 if (currentPointer.toolType == lastPointer.toolType) {
5800 int64_t deltaX = currentPointer.x - lastPointer.x;
5801 int64_t deltaY = currentPointer.y - lastPointer.y;
5803 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
5805 // Insert new element into the heap (sift up).
5806 heap[heapSize].currentPointerIndex = currentPointerIndex;
5807 heap[heapSize].lastPointerIndex = lastPointerIndex;
5808 heap[heapSize].distance = distance;
5815 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
5817 for (uint32_t parentIndex = startIndex; ;) {
5818 uint32_t childIndex = parentIndex * 2 + 1;
5819 if (childIndex >= heapSize) {
5823 if (childIndex + 1 < heapSize
5824 && heap[childIndex + 1].distance < heap[childIndex].distance) {
5828 if (heap[parentIndex].distance <= heap[childIndex].distance) {
5832 swap(heap[parentIndex], heap[childIndex]);
5833 parentIndex = childIndex;
5837 #if DEBUG_POINTER_ASSIGNMENT
5838 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
5839 for (size_t i = 0; i < heapSize; i++) {
5840 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
5841 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
5846 // Pull matches out by increasing order of distance.
5847 // To avoid reassigning pointers that have already been matched, the loop keeps track
5848 // of which last and current pointers have been matched using the matchedXXXBits variables.
5849 // It also tracks the used pointer id bits.
5850 BitSet32 matchedLastBits(0);
5851 BitSet32 matchedCurrentBits(0);
5852 BitSet32 usedIdBits(0);
5854 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
5855 while (heapSize > 0) {
5857 // The first time through the loop, we just consume the root element of
5858 // the heap (the one with smallest distance).
5861 // Previous iterations consumed the root element of the heap.
5862 // Pop root element off of the heap (sift down).
5863 heap[0] = heap[heapSize];
5864 for (uint32_t parentIndex = 0; ;) {
5865 uint32_t childIndex = parentIndex * 2 + 1;
5866 if (childIndex >= heapSize) {
5870 if (childIndex + 1 < heapSize
5871 && heap[childIndex + 1].distance < heap[childIndex].distance) {
5875 if (heap[parentIndex].distance <= heap[childIndex].distance) {
5879 swap(heap[parentIndex], heap[childIndex]);
5880 parentIndex = childIndex;
5883 #if DEBUG_POINTER_ASSIGNMENT
5884 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
5885 for (size_t i = 0; i < heapSize; i++) {
5886 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
5887 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
5895 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
5896 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
5898 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
5899 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
5901 matchedCurrentBits.markBit(currentPointerIndex);
5902 matchedLastBits.markBit(lastPointerIndex);
5904 uint32_t id = mLastRawPointerData.pointers[lastPointerIndex].id;
5905 mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
5906 mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
5907 mCurrentRawPointerData.markIdBit(id,
5908 mCurrentRawPointerData.isHovering(currentPointerIndex));
5909 usedIdBits.markBit(id);
5911 #if DEBUG_POINTER_ASSIGNMENT
5912 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
5913 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
5919 // Assign fresh ids to pointers that were not matched in the process.
5920 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
5921 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
5922 uint32_t id = usedIdBits.markFirstUnmarkedBit();
5924 mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
5925 mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
5926 mCurrentRawPointerData.markIdBit(id,
5927 mCurrentRawPointerData.isHovering(currentPointerIndex));
5929 #if DEBUG_POINTER_ASSIGNMENT
5930 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
5931 currentPointerIndex, id);
5936 int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
5937 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
5938 return AKEY_STATE_VIRTUAL;
5941 size_t numVirtualKeys = mVirtualKeys.size();
5942 for (size_t i = 0; i < numVirtualKeys; i++) {
5943 const VirtualKey& virtualKey = mVirtualKeys[i];
5944 if (virtualKey.keyCode == keyCode) {
5945 return AKEY_STATE_UP;
5949 return AKEY_STATE_UNKNOWN;
5952 int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
5953 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
5954 return AKEY_STATE_VIRTUAL;
5957 size_t numVirtualKeys = mVirtualKeys.size();
5958 for (size_t i = 0; i < numVirtualKeys; i++) {
5959 const VirtualKey& virtualKey = mVirtualKeys[i];
5960 if (virtualKey.scanCode == scanCode) {
5961 return AKEY_STATE_UP;
5965 return AKEY_STATE_UNKNOWN;
5968 bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
5969 const int32_t* keyCodes, uint8_t* outFlags) {
5970 size_t numVirtualKeys = mVirtualKeys.size();
5971 for (size_t i = 0; i < numVirtualKeys; i++) {
5972 const VirtualKey& virtualKey = mVirtualKeys[i];
5974 for (size_t i = 0; i < numCodes; i++) {
5975 if (virtualKey.keyCode == keyCodes[i]) {
5985 // --- SingleTouchInputMapper ---
5987 SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
5988 TouchInputMapper(device) {
5991 SingleTouchInputMapper::~SingleTouchInputMapper() {
5994 void SingleTouchInputMapper::reset(nsecs_t when) {
5995 mSingleTouchMotionAccumulator.reset(getDevice());
5997 TouchInputMapper::reset(when);
6000 void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6001 TouchInputMapper::process(rawEvent);
6003 mSingleTouchMotionAccumulator.process(rawEvent);
6006 void SingleTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
6007 if (mTouchButtonAccumulator.isToolActive()) {
6008 mCurrentRawPointerData.pointerCount = 1;
6009 mCurrentRawPointerData.idToIndex[0] = 0;
6011 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6012 && (mTouchButtonAccumulator.isHovering()
6013 || (mRawPointerAxes.pressure.valid
6014 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
6015 mCurrentRawPointerData.markIdBit(0, isHovering);
6017 RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[0];
6019 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6020 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6021 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6022 outPointer.touchMajor = 0;
6023 outPointer.touchMinor = 0;
6024 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6025 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6026 outPointer.orientation = 0;
6027 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6028 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6029 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6030 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6031 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6032 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6034 outPointer.isHovering = isHovering;
6038 void SingleTouchInputMapper::configureRawPointerAxes() {
6039 TouchInputMapper::configureRawPointerAxes();
6041 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6042 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6043 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6044 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6045 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6046 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6047 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6050 bool SingleTouchInputMapper::hasStylus() const {
6051 return mTouchButtonAccumulator.hasStylus();
6055 // --- MultiTouchInputMapper ---
6057 MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6058 TouchInputMapper(device) {
6061 MultiTouchInputMapper::~MultiTouchInputMapper() {
6064 void MultiTouchInputMapper::reset(nsecs_t when) {
6065 mMultiTouchMotionAccumulator.reset(getDevice());
6067 mPointerIdBits.clear();
6069 TouchInputMapper::reset(when);
6072 void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6073 TouchInputMapper::process(rawEvent);
6075 mMultiTouchMotionAccumulator.process(rawEvent);
6078 void MultiTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
6079 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6080 size_t outCount = 0;
6081 BitSet32 newPointerIdBits;
6083 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6084 const MultiTouchMotionAccumulator::Slot* inSlot =
6085 mMultiTouchMotionAccumulator.getSlot(inIndex);
6086 if (!inSlot->isInUse()) {
6090 if (outCount >= MAX_POINTERS) {
6092 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6093 "ignoring the rest.",
6094 getDeviceName().string(), MAX_POINTERS);
6096 break; // too many fingers!
6099 RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[outCount];
6100 outPointer.x = inSlot->getX();
6101 outPointer.y = inSlot->getY();
6102 outPointer.pressure = inSlot->getPressure();
6103 outPointer.touchMajor = inSlot->getTouchMajor();
6104 outPointer.touchMinor = inSlot->getTouchMinor();
6105 outPointer.toolMajor = inSlot->getToolMajor();
6106 outPointer.toolMinor = inSlot->getToolMinor();
6107 outPointer.orientation = inSlot->getOrientation();
6108 outPointer.distance = inSlot->getDistance();
6109 outPointer.tiltX = 0;
6110 outPointer.tiltY = 0;
6112 outPointer.toolType = inSlot->getToolType();
6113 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6114 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6115 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6116 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6120 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6121 && (mTouchButtonAccumulator.isHovering()
6122 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6123 outPointer.isHovering = isHovering;
6125 // Assign pointer id using tracking id if available.
6126 if (*outHavePointerIds) {
6127 int32_t trackingId = inSlot->getTrackingId();
6129 if (trackingId >= 0) {
6130 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6131 uint32_t n = idBits.clearFirstMarkedBit();
6132 if (mPointerTrackingIdMap[n] == trackingId) {
6137 if (id < 0 && !mPointerIdBits.isFull()) {
6138 id = mPointerIdBits.markFirstUnmarkedBit();
6139 mPointerTrackingIdMap[id] = trackingId;
6143 *outHavePointerIds = false;
6144 mCurrentRawPointerData.clearIdBits();
6145 newPointerIdBits.clear();
6148 mCurrentRawPointerData.idToIndex[id] = outCount;
6149 mCurrentRawPointerData.markIdBit(id, isHovering);
6150 newPointerIdBits.markBit(id);
6157 mCurrentRawPointerData.pointerCount = outCount;
6158 mPointerIdBits = newPointerIdBits;
6160 mMultiTouchMotionAccumulator.finishSync();
6163 void MultiTouchInputMapper::configureRawPointerAxes() {
6164 TouchInputMapper::configureRawPointerAxes();
6166 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6167 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6168 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6169 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6170 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6171 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6172 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6173 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6174 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6175 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6176 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6178 if (mRawPointerAxes.trackingId.valid
6179 && mRawPointerAxes.slot.valid
6180 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6181 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6182 if (slotCount > MAX_SLOTS) {
6183 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6184 "only supports a maximum of %zu slots at this time.",
6185 getDeviceName().string(), slotCount, MAX_SLOTS);
6186 slotCount = MAX_SLOTS;
6188 mMultiTouchMotionAccumulator.configure(getDevice(),
6189 slotCount, true /*usingSlotsProtocol*/);
6191 mMultiTouchMotionAccumulator.configure(getDevice(),
6192 MAX_POINTERS, false /*usingSlotsProtocol*/);
6196 bool MultiTouchInputMapper::hasStylus() const {
6197 return mMultiTouchMotionAccumulator.hasStylus()
6198 || mTouchButtonAccumulator.hasStylus();
6202 // --- JoystickInputMapper ---
6204 JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6205 InputMapper(device) {
6208 JoystickInputMapper::~JoystickInputMapper() {
6211 uint32_t JoystickInputMapper::getSources() {
6212 return AINPUT_SOURCE_JOYSTICK;
6215 void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6216 InputMapper::populateDeviceInfo(info);
6218 for (size_t i = 0; i < mAxes.size(); i++) {
6219 const Axis& axis = mAxes.valueAt(i);
6220 addMotionRange(axis.axisInfo.axis, axis, info);
6222 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6223 addMotionRange(axis.axisInfo.highAxis, axis, info);
6229 void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6230 InputDeviceInfo* info) {
6231 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6232 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6233 /* In order to ease the transition for developers from using the old axes
6234 * to the newer, more semantically correct axes, we'll continue to register
6235 * the old axes as duplicates of their corresponding new ones. */
6236 int32_t compatAxis = getCompatAxis(axisId);
6237 if (compatAxis >= 0) {
6238 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6239 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6243 /* A mapping from axes the joystick actually has to the axes that should be
6244 * artificially created for compatibility purposes.
6245 * Returns -1 if no compatibility axis is needed. */
6246 int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6248 case AMOTION_EVENT_AXIS_LTRIGGER:
6249 return AMOTION_EVENT_AXIS_BRAKE;
6250 case AMOTION_EVENT_AXIS_RTRIGGER:
6251 return AMOTION_EVENT_AXIS_GAS;
6256 void JoystickInputMapper::dump(String8& dump) {
6257 dump.append(INDENT2 "Joystick Input Mapper:\n");
6259 dump.append(INDENT3 "Axes:\n");
6260 size_t numAxes = mAxes.size();
6261 for (size_t i = 0; i < numAxes; i++) {
6262 const Axis& axis = mAxes.valueAt(i);
6263 const char* label = getAxisLabel(axis.axisInfo.axis);
6265 dump.appendFormat(INDENT4 "%s", label);
6267 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6269 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6270 label = getAxisLabel(axis.axisInfo.highAxis);
6272 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6274 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6275 axis.axisInfo.splitValue);
6277 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6278 dump.append(" (invert)");
6281 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6282 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6283 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
6284 "highScale=%0.5f, highOffset=%0.5f\n",
6285 axis.scale, axis.offset, axis.highScale, axis.highOffset);
6286 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
6287 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6288 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6289 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6293 void JoystickInputMapper::configure(nsecs_t when,
6294 const InputReaderConfiguration* config, uint32_t changes) {
6295 InputMapper::configure(when, config, changes);
6297 if (!changes) { // first time only
6298 // Collect all axes.
6299 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6300 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6301 & INPUT_DEVICE_CLASS_JOYSTICK)) {
6302 continue; // axis must be claimed by a different device
6305 RawAbsoluteAxisInfo rawAxisInfo;
6306 getAbsoluteAxisInfo(abs, &rawAxisInfo);
6307 if (rawAxisInfo.valid) {
6310 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6311 if (!explicitlyMapped) {
6312 // Axis is not explicitly mapped, will choose a generic axis later.
6313 axisInfo.mode = AxisInfo::MODE_NORMAL;
6317 // Apply flat override.
6318 int32_t rawFlat = axisInfo.flatOverride < 0
6319 ? rawAxisInfo.flat : axisInfo.flatOverride;
6321 // Calculate scaling factors and limits.
6323 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6324 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6325 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6326 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6327 scale, 0.0f, highScale, 0.0f,
6328 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6329 rawAxisInfo.resolution * scale);
6330 } else if (isCenteredAxis(axisInfo.axis)) {
6331 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6332 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6333 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6334 scale, offset, scale, offset,
6335 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6336 rawAxisInfo.resolution * scale);
6338 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6339 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6340 scale, 0.0f, scale, 0.0f,
6341 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6342 rawAxisInfo.resolution * scale);
6345 // To eliminate noise while the joystick is at rest, filter out small variations
6346 // in axis values up front.
6347 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
6349 mAxes.add(abs, axis);
6353 // If there are too many axes, start dropping them.
6354 // Prefer to keep explicitly mapped axes.
6355 if (mAxes.size() > PointerCoords::MAX_AXES) {
6356 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
6357 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
6362 // Assign generic axis ids to remaining axes.
6363 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
6364 size_t numAxes = mAxes.size();
6365 for (size_t i = 0; i < numAxes; i++) {
6366 Axis& axis = mAxes.editValueAt(i);
6367 if (axis.axisInfo.axis < 0) {
6368 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
6369 && haveAxis(nextGenericAxisId)) {
6370 nextGenericAxisId += 1;
6373 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
6374 axis.axisInfo.axis = nextGenericAxisId;
6375 nextGenericAxisId += 1;
6377 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
6378 "have already been assigned to other axes.",
6379 getDeviceName().string(), mAxes.keyAt(i));
6380 mAxes.removeItemsAt(i--);
6388 bool JoystickInputMapper::haveAxis(int32_t axisId) {
6389 size_t numAxes = mAxes.size();
6390 for (size_t i = 0; i < numAxes; i++) {
6391 const Axis& axis = mAxes.valueAt(i);
6392 if (axis.axisInfo.axis == axisId
6393 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
6394 && axis.axisInfo.highAxis == axisId)) {
6401 void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
6402 size_t i = mAxes.size();
6403 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
6404 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
6407 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
6408 getDeviceName().string(), mAxes.keyAt(i));
6409 mAxes.removeItemsAt(i);
6413 bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
6415 case AMOTION_EVENT_AXIS_X:
6416 case AMOTION_EVENT_AXIS_Y:
6417 case AMOTION_EVENT_AXIS_Z:
6418 case AMOTION_EVENT_AXIS_RX:
6419 case AMOTION_EVENT_AXIS_RY:
6420 case AMOTION_EVENT_AXIS_RZ:
6421 case AMOTION_EVENT_AXIS_HAT_X:
6422 case AMOTION_EVENT_AXIS_HAT_Y:
6423 case AMOTION_EVENT_AXIS_ORIENTATION:
6424 case AMOTION_EVENT_AXIS_RUDDER:
6425 case AMOTION_EVENT_AXIS_WHEEL:
6432 void JoystickInputMapper::reset(nsecs_t when) {
6433 // Recenter all axes.
6434 size_t numAxes = mAxes.size();
6435 for (size_t i = 0; i < numAxes; i++) {
6436 Axis& axis = mAxes.editValueAt(i);
6440 InputMapper::reset(when);
6443 void JoystickInputMapper::process(const RawEvent* rawEvent) {
6444 switch (rawEvent->type) {
6446 ssize_t index = mAxes.indexOfKey(rawEvent->code);
6448 Axis& axis = mAxes.editValueAt(index);
6449 float newValue, highNewValue;
6450 switch (axis.axisInfo.mode) {
6451 case AxisInfo::MODE_INVERT:
6452 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
6453 * axis.scale + axis.offset;
6454 highNewValue = 0.0f;
6456 case AxisInfo::MODE_SPLIT:
6457 if (rawEvent->value < axis.axisInfo.splitValue) {
6458 newValue = (axis.axisInfo.splitValue - rawEvent->value)
6459 * axis.scale + axis.offset;
6460 highNewValue = 0.0f;
6461 } else if (rawEvent->value > axis.axisInfo.splitValue) {
6463 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
6464 * axis.highScale + axis.highOffset;
6467 highNewValue = 0.0f;
6471 newValue = rawEvent->value * axis.scale + axis.offset;
6472 highNewValue = 0.0f;
6475 axis.newValue = newValue;
6476 axis.highNewValue = highNewValue;
6482 switch (rawEvent->code) {
6484 sync(rawEvent->when, false /*force*/);
6491 void JoystickInputMapper::sync(nsecs_t when, bool force) {
6492 if (!filterAxes(force)) {
6496 int32_t metaState = mContext->getGlobalMetaState();
6497 int32_t buttonState = 0;
6499 PointerProperties pointerProperties;
6500 pointerProperties.clear();
6501 pointerProperties.id = 0;
6502 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
6504 PointerCoords pointerCoords;
6505 pointerCoords.clear();
6507 size_t numAxes = mAxes.size();
6508 for (size_t i = 0; i < numAxes; i++) {
6509 const Axis& axis = mAxes.valueAt(i);
6510 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
6511 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6512 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
6513 axis.highCurrentValue);
6517 // Moving a joystick axis should not wake the device because joysticks can
6518 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
6519 // button will likely wake the device.
6520 // TODO: Use the input device configuration to control this behavior more finely.
6521 uint32_t policyFlags = 0;
6523 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
6524 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
6525 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
6526 getListener()->notifyMotion(&args);
6529 void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
6530 int32_t axis, float value) {
6531 pointerCoords->setAxisValue(axis, value);
6532 /* In order to ease the transition for developers from using the old axes
6533 * to the newer, more semantically correct axes, we'll continue to produce
6534 * values for the old axes as mirrors of the value of their corresponding
6536 int32_t compatAxis = getCompatAxis(axis);
6537 if (compatAxis >= 0) {
6538 pointerCoords->setAxisValue(compatAxis, value);
6542 bool JoystickInputMapper::filterAxes(bool force) {
6543 bool atLeastOneSignificantChange = force;
6544 size_t numAxes = mAxes.size();
6545 for (size_t i = 0; i < numAxes; i++) {
6546 Axis& axis = mAxes.editValueAt(i);
6547 if (force || hasValueChangedSignificantly(axis.filter,
6548 axis.newValue, axis.currentValue, axis.min, axis.max)) {
6549 axis.currentValue = axis.newValue;
6550 atLeastOneSignificantChange = true;
6552 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6553 if (force || hasValueChangedSignificantly(axis.filter,
6554 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
6555 axis.highCurrentValue = axis.highNewValue;
6556 atLeastOneSignificantChange = true;
6560 return atLeastOneSignificantChange;
6563 bool JoystickInputMapper::hasValueChangedSignificantly(
6564 float filter, float newValue, float currentValue, float min, float max) {
6565 if (newValue != currentValue) {
6566 // Filter out small changes in value unless the value is converging on the axis
6567 // bounds or center point. This is intended to reduce the amount of information
6568 // sent to applications by particularly noisy joysticks (such as PS3).
6569 if (fabs(newValue - currentValue) > filter
6570 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
6571 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
6572 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
6579 bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
6580 float filter, float newValue, float currentValue, float thresholdValue) {
6581 float newDistance = fabs(newValue - thresholdValue);
6582 if (newDistance < filter) {
6583 float oldDistance = fabs(currentValue - thresholdValue);
6584 if (newDistance < oldDistance) {
6591 } // namespace android