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