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