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