blob: 8556c238ad852fbb1965d022f3d805c5dfac5b06 [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
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
47#include <cutils/log.h>
48#include <input/Keyboard.h>
49#include <input/VirtualKeyMap.h>
50
Michael Wright842500e2015-03-13 17:32:02 -070051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <stddef.h>
53#include <stdlib.h>
54#include <unistd.h>
55#include <errno.h>
56#include <limits.h>
57#include <math.h>
58
59#define INDENT " "
60#define INDENT2 " "
61#define INDENT3 " "
62#define INDENT4 " "
63#define INDENT5 " "
64
65namespace android {
66
67// --- Constants ---
68
69// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
70static const size_t MAX_SLOTS = 32;
71
Michael Wright842500e2015-03-13 17:32:02 -070072// Maximum amount of latency to add to touch events while waiting for data from an
73// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010074static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070075
Michael Wright43fd19f2015-04-21 19:02:58 +010076// Maximum amount of time to wait on touch data before pushing out new pressure data.
77static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
78
79// Artificial latency on synthetic events created from stylus data without corresponding touch
80// data.
81static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
82
Michael Wrightd02c5b62014-02-10 15:10:22 -080083// --- Static Functions ---
84
85template<typename T>
86inline static T abs(const T& value) {
87 return value < 0 ? - value : value;
88}
89
90template<typename T>
91inline static T min(const T& a, const T& b) {
92 return a < b ? a : b;
93}
94
95template<typename T>
96inline static void swap(T& a, T& b) {
97 T temp = a;
98 a = b;
99 b = temp;
100}
101
102inline static float avg(float x, float y) {
103 return (x + y) / 2;
104}
105
106inline static float distance(float x1, float y1, float x2, float y2) {
107 return hypotf(x1 - x2, y1 - y2);
108}
109
110inline static int32_t signExtendNybble(int32_t value) {
111 return value >= 8 ? value - 16 : value;
112}
113
114static inline const char* toString(bool value) {
115 return value ? "true" : "false";
116}
117
118static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
119 const int32_t map[][4], size_t mapSize) {
120 if (orientation != DISPLAY_ORIENTATION_0) {
121 for (size_t i = 0; i < mapSize; i++) {
122 if (value == map[i][0]) {
123 return map[i][orientation];
124 }
125 }
126 }
127 return value;
128}
129
130static const int32_t keyCodeRotationMap[][4] = {
131 // key codes enumerated counter-clockwise with the original (unrotated) key first
132 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
133 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
134 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
135 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
136 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
137};
138static const size_t keyCodeRotationMapSize =
139 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
140
141static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
142 return rotateValueUsingRotationMap(keyCode, orientation,
143 keyCodeRotationMap, keyCodeRotationMapSize);
144}
145
146static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
147 float temp;
148 switch (orientation) {
149 case DISPLAY_ORIENTATION_90:
150 temp = *deltaX;
151 *deltaX = *deltaY;
152 *deltaY = -temp;
153 break;
154
155 case DISPLAY_ORIENTATION_180:
156 *deltaX = -*deltaX;
157 *deltaY = -*deltaY;
158 break;
159
160 case DISPLAY_ORIENTATION_270:
161 temp = *deltaX;
162 *deltaX = -*deltaY;
163 *deltaY = temp;
164 break;
165 }
166}
167
168static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
169 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
170}
171
172// Returns true if the pointer should be reported as being down given the specified
173// button states. This determines whether the event is reported as a touch event.
174static bool isPointerDown(int32_t buttonState) {
175 return buttonState &
176 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
177 | AMOTION_EVENT_BUTTON_TERTIARY);
178}
179
180static float calculateCommonVector(float a, float b) {
181 if (a > 0 && b > 0) {
182 return a < b ? a : b;
183 } else if (a < 0 && b < 0) {
184 return a > b ? a : b;
185 } else {
186 return 0;
187 }
188}
189
190static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
191 nsecs_t when, int32_t deviceId, uint32_t source,
192 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
193 int32_t buttonState, int32_t keyCode) {
194 if (
195 (action == AKEY_EVENT_ACTION_DOWN
196 && !(lastButtonState & buttonState)
197 && (currentButtonState & buttonState))
198 || (action == AKEY_EVENT_ACTION_UP
199 && (lastButtonState & buttonState)
200 && !(currentButtonState & buttonState))) {
201 NotifyKeyArgs args(when, deviceId, source, policyFlags,
202 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
203 context->getListener()->notifyKey(&args);
204 }
205}
206
207static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
208 nsecs_t when, int32_t deviceId, uint32_t source,
209 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
210 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
211 lastButtonState, currentButtonState,
212 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
213 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
214 lastButtonState, currentButtonState,
215 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
216}
217
218
219// --- InputReaderConfiguration ---
220
221bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const {
222 const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay;
223 if (viewport.displayId >= 0) {
224 *outViewport = viewport;
225 return true;
226 }
227 return false;
228}
229
230void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) {
231 DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay;
232 v = viewport;
233}
234
235
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700236// -- TouchAffineTransformation --
237void TouchAffineTransformation::applyTo(float& x, float& y) const {
238 float newX, newY;
239 newX = x * x_scale + y * x_ymix + x_offset;
240 newY = x * y_xmix + y * y_scale + y_offset;
241
242 x = newX;
243 y = newY;
244}
245
246
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247// --- InputReader ---
248
249InputReader::InputReader(const sp<EventHubInterface>& eventHub,
250 const sp<InputReaderPolicyInterface>& policy,
251 const sp<InputListenerInterface>& listener) :
252 mContext(this), mEventHub(eventHub), mPolicy(policy),
253 mGlobalMetaState(0), mGeneration(1),
254 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
255 mConfigurationChangesToRefresh(0) {
256 mQueuedListener = new QueuedInputListener(listener);
257
258 { // acquire lock
259 AutoMutex _l(mLock);
260
261 refreshConfigurationLocked(0);
262 updateGlobalMetaStateLocked();
263 } // release lock
264}
265
266InputReader::~InputReader() {
267 for (size_t i = 0; i < mDevices.size(); i++) {
268 delete mDevices.valueAt(i);
269 }
270}
271
272void InputReader::loopOnce() {
273 int32_t oldGeneration;
274 int32_t timeoutMillis;
275 bool inputDevicesChanged = false;
276 Vector<InputDeviceInfo> inputDevices;
277 { // acquire lock
278 AutoMutex _l(mLock);
279
280 oldGeneration = mGeneration;
281 timeoutMillis = -1;
282
283 uint32_t changes = mConfigurationChangesToRefresh;
284 if (changes) {
285 mConfigurationChangesToRefresh = 0;
286 timeoutMillis = 0;
287 refreshConfigurationLocked(changes);
288 } else if (mNextTimeout != LLONG_MAX) {
289 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
290 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
291 }
292 } // release lock
293
294 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
295
296 { // acquire lock
297 AutoMutex _l(mLock);
298 mReaderIsAliveCondition.broadcast();
299
300 if (count) {
301 processEventsLocked(mEventBuffer, count);
302 }
303
304 if (mNextTimeout != LLONG_MAX) {
305 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
306 if (now >= mNextTimeout) {
307#if DEBUG_RAW_EVENTS
308 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
309#endif
310 mNextTimeout = LLONG_MAX;
311 timeoutExpiredLocked(now);
312 }
313 }
314
315 if (oldGeneration != mGeneration) {
316 inputDevicesChanged = true;
317 getInputDevicesLocked(inputDevices);
318 }
319 } // release lock
320
321 // Send out a message that the describes the changed input devices.
322 if (inputDevicesChanged) {
323 mPolicy->notifyInputDevicesChanged(inputDevices);
324 }
325
326 // Flush queued events out to the listener.
327 // This must happen outside of the lock because the listener could potentially call
328 // back into the InputReader's methods, such as getScanCodeState, or become blocked
329 // on another thread similarly waiting to acquire the InputReader lock thereby
330 // resulting in a deadlock. This situation is actually quite plausible because the
331 // listener is actually the input dispatcher, which calls into the window manager,
332 // which occasionally calls into the input reader.
333 mQueuedListener->flush();
334}
335
336void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
337 for (const RawEvent* rawEvent = rawEvents; count;) {
338 int32_t type = rawEvent->type;
339 size_t batchSize = 1;
340 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
341 int32_t deviceId = rawEvent->deviceId;
342 while (batchSize < count) {
343 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
344 || rawEvent[batchSize].deviceId != deviceId) {
345 break;
346 }
347 batchSize += 1;
348 }
349#if DEBUG_RAW_EVENTS
350 ALOGD("BatchSize: %d Count: %d", batchSize, count);
351#endif
352 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
353 } else {
354 switch (rawEvent->type) {
355 case EventHubInterface::DEVICE_ADDED:
356 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
357 break;
358 case EventHubInterface::DEVICE_REMOVED:
359 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
360 break;
361 case EventHubInterface::FINISHED_DEVICE_SCAN:
362 handleConfigurationChangedLocked(rawEvent->when);
363 break;
364 default:
365 ALOG_ASSERT(false); // can't happen
366 break;
367 }
368 }
369 count -= batchSize;
370 rawEvent += batchSize;
371 }
372}
373
374void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
375 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
376 if (deviceIndex >= 0) {
377 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
378 return;
379 }
380
381 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
382 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
383 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
384
385 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
386 device->configure(when, &mConfig, 0);
387 device->reset(when);
388
389 if (device->isIgnored()) {
390 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
391 identifier.name.string());
392 } else {
393 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
394 identifier.name.string(), device->getSources());
395 }
396
397 mDevices.add(deviceId, device);
398 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700399
400 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
401 notifyExternalStylusPresenceChanged();
402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403}
404
405void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
406 InputDevice* device = NULL;
407 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
408 if (deviceIndex < 0) {
409 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
410 return;
411 }
412
413 device = mDevices.valueAt(deviceIndex);
414 mDevices.removeItemsAt(deviceIndex, 1);
415 bumpGenerationLocked();
416
417 if (device->isIgnored()) {
418 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
419 device->getId(), device->getName().string());
420 } else {
421 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
422 device->getId(), device->getName().string(), device->getSources());
423 }
424
Michael Wright842500e2015-03-13 17:32:02 -0700425 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
426 notifyExternalStylusPresenceChanged();
427 }
428
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 device->reset(when);
430 delete device;
431}
432
433InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
434 const InputDeviceIdentifier& identifier, uint32_t classes) {
435 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
436 controllerNumber, identifier, classes);
437
438 // External devices.
439 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
440 device->setExternal(true);
441 }
442
Tim Kilbourn063ff532015-04-08 10:26:18 -0700443 // Devices with mics.
444 if (classes & INPUT_DEVICE_CLASS_MIC) {
445 device->setMic(true);
446 }
447
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 // Switch-like devices.
449 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
450 device->addMapper(new SwitchInputMapper(device));
451 }
452
Prashant Malani1941ff52015-08-11 18:29:28 -0700453 // Scroll wheel-like devices.
454 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
455 device->addMapper(new RotaryEncoderInputMapper(device));
456 }
457
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 // Vibrator-like devices.
459 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
460 device->addMapper(new VibratorInputMapper(device));
461 }
462
463 // Keyboard-like devices.
464 uint32_t keyboardSource = 0;
465 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
466 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
467 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
468 }
469 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
470 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
471 }
472 if (classes & INPUT_DEVICE_CLASS_DPAD) {
473 keyboardSource |= AINPUT_SOURCE_DPAD;
474 }
475 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
476 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
477 }
478
479 if (keyboardSource != 0) {
480 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
481 }
482
483 // Cursor-like devices.
484 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
485 device->addMapper(new CursorInputMapper(device));
486 }
487
488 // Touchscreens and touchpad devices.
489 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
490 device->addMapper(new MultiTouchInputMapper(device));
491 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
492 device->addMapper(new SingleTouchInputMapper(device));
493 }
494
495 // Joystick-like devices.
496 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
497 device->addMapper(new JoystickInputMapper(device));
498 }
499
Michael Wright842500e2015-03-13 17:32:02 -0700500 // External stylus-like devices.
501 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
502 device->addMapper(new ExternalStylusInputMapper(device));
503 }
504
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 return device;
506}
507
508void InputReader::processEventsForDeviceLocked(int32_t deviceId,
509 const RawEvent* rawEvents, size_t count) {
510 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
511 if (deviceIndex < 0) {
512 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
513 return;
514 }
515
516 InputDevice* device = mDevices.valueAt(deviceIndex);
517 if (device->isIgnored()) {
518 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
519 return;
520 }
521
522 device->process(rawEvents, count);
523}
524
525void InputReader::timeoutExpiredLocked(nsecs_t when) {
526 for (size_t i = 0; i < mDevices.size(); i++) {
527 InputDevice* device = mDevices.valueAt(i);
528 if (!device->isIgnored()) {
529 device->timeoutExpired(when);
530 }
531 }
532}
533
534void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
535 // Reset global meta state because it depends on the list of all configured devices.
536 updateGlobalMetaStateLocked();
537
538 // Enqueue configuration changed.
539 NotifyConfigurationChangedArgs args(when);
540 mQueuedListener->notifyConfigurationChanged(&args);
541}
542
543void InputReader::refreshConfigurationLocked(uint32_t changes) {
544 mPolicy->getReaderConfiguration(&mConfig);
545 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
546
547 if (changes) {
548 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
549 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
550
551 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
552 mEventHub->requestReopenDevices();
553 } else {
554 for (size_t i = 0; i < mDevices.size(); i++) {
555 InputDevice* device = mDevices.valueAt(i);
556 device->configure(now, &mConfig, changes);
557 }
558 }
559 }
560}
561
562void InputReader::updateGlobalMetaStateLocked() {
563 mGlobalMetaState = 0;
564
565 for (size_t i = 0; i < mDevices.size(); i++) {
566 InputDevice* device = mDevices.valueAt(i);
567 mGlobalMetaState |= device->getMetaState();
568 }
569}
570
571int32_t InputReader::getGlobalMetaStateLocked() {
572 return mGlobalMetaState;
573}
574
Michael Wright842500e2015-03-13 17:32:02 -0700575void InputReader::notifyExternalStylusPresenceChanged() {
576 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
577}
578
579void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
580 for (size_t i = 0; i < mDevices.size(); i++) {
581 InputDevice* device = mDevices.valueAt(i);
582 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
583 outDevices.push();
584 device->getDeviceInfo(&outDevices.editTop());
585 }
586 }
587}
588
589void InputReader::dispatchExternalStylusState(const StylusState& state) {
590 for (size_t i = 0; i < mDevices.size(); i++) {
591 InputDevice* device = mDevices.valueAt(i);
592 device->updateExternalStylusState(state);
593 }
594}
595
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
597 mDisableVirtualKeysTimeout = time;
598}
599
600bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
601 InputDevice* device, int32_t keyCode, int32_t scanCode) {
602 if (now < mDisableVirtualKeysTimeout) {
603 ALOGI("Dropping virtual key from device %s because virtual keys are "
604 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
605 device->getName().string(),
606 (mDisableVirtualKeysTimeout - now) * 0.000001,
607 keyCode, scanCode);
608 return true;
609 } else {
610 return false;
611 }
612}
613
614void InputReader::fadePointerLocked() {
615 for (size_t i = 0; i < mDevices.size(); i++) {
616 InputDevice* device = mDevices.valueAt(i);
617 device->fadePointer();
618 }
619}
620
621void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
622 if (when < mNextTimeout) {
623 mNextTimeout = when;
624 mEventHub->wake();
625 }
626}
627
628int32_t InputReader::bumpGenerationLocked() {
629 return ++mGeneration;
630}
631
632void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
633 AutoMutex _l(mLock);
634 getInputDevicesLocked(outInputDevices);
635}
636
637void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
638 outInputDevices.clear();
639
640 size_t numDevices = mDevices.size();
641 for (size_t i = 0; i < numDevices; i++) {
642 InputDevice* device = mDevices.valueAt(i);
643 if (!device->isIgnored()) {
644 outInputDevices.push();
645 device->getDeviceInfo(&outInputDevices.editTop());
646 }
647 }
648}
649
650int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
651 int32_t keyCode) {
652 AutoMutex _l(mLock);
653
654 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
655}
656
657int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
658 int32_t scanCode) {
659 AutoMutex _l(mLock);
660
661 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
662}
663
664int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
665 AutoMutex _l(mLock);
666
667 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
668}
669
670int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
671 GetStateFunc getStateFunc) {
672 int32_t result = AKEY_STATE_UNKNOWN;
673 if (deviceId >= 0) {
674 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
675 if (deviceIndex >= 0) {
676 InputDevice* device = mDevices.valueAt(deviceIndex);
677 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
678 result = (device->*getStateFunc)(sourceMask, code);
679 }
680 }
681 } else {
682 size_t numDevices = mDevices.size();
683 for (size_t i = 0; i < numDevices; i++) {
684 InputDevice* device = mDevices.valueAt(i);
685 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
686 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
687 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
688 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
689 if (currentResult >= AKEY_STATE_DOWN) {
690 return currentResult;
691 } else if (currentResult == AKEY_STATE_UP) {
692 result = currentResult;
693 }
694 }
695 }
696 }
697 return result;
698}
699
700bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
701 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
702 AutoMutex _l(mLock);
703
704 memset(outFlags, 0, numCodes);
705 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
706}
707
708bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
709 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
710 bool result = false;
711 if (deviceId >= 0) {
712 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
713 if (deviceIndex >= 0) {
714 InputDevice* device = mDevices.valueAt(deviceIndex);
715 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
716 result = device->markSupportedKeyCodes(sourceMask,
717 numCodes, keyCodes, outFlags);
718 }
719 }
720 } else {
721 size_t numDevices = mDevices.size();
722 for (size_t i = 0; i < numDevices; i++) {
723 InputDevice* device = mDevices.valueAt(i);
724 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
725 result |= device->markSupportedKeyCodes(sourceMask,
726 numCodes, keyCodes, outFlags);
727 }
728 }
729 }
730 return result;
731}
732
733void InputReader::requestRefreshConfiguration(uint32_t changes) {
734 AutoMutex _l(mLock);
735
736 if (changes) {
737 bool needWake = !mConfigurationChangesToRefresh;
738 mConfigurationChangesToRefresh |= changes;
739
740 if (needWake) {
741 mEventHub->wake();
742 }
743 }
744}
745
746void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
747 ssize_t repeat, int32_t token) {
748 AutoMutex _l(mLock);
749
750 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
751 if (deviceIndex >= 0) {
752 InputDevice* device = mDevices.valueAt(deviceIndex);
753 device->vibrate(pattern, patternSize, repeat, token);
754 }
755}
756
757void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
758 AutoMutex _l(mLock);
759
760 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
761 if (deviceIndex >= 0) {
762 InputDevice* device = mDevices.valueAt(deviceIndex);
763 device->cancelVibrate(token);
764 }
765}
766
767void InputReader::dump(String8& dump) {
768 AutoMutex _l(mLock);
769
770 mEventHub->dump(dump);
771 dump.append("\n");
772
773 dump.append("Input Reader State:\n");
774
775 for (size_t i = 0; i < mDevices.size(); i++) {
776 mDevices.valueAt(i)->dump(dump);
777 }
778
779 dump.append(INDENT "Configuration:\n");
780 dump.append(INDENT2 "ExcludedDeviceNames: [");
781 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
782 if (i != 0) {
783 dump.append(", ");
784 }
785 dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
786 }
787 dump.append("]\n");
788 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
789 mConfig.virtualKeyQuietTime * 0.000001f);
790
791 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
792 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
793 mConfig.pointerVelocityControlParameters.scale,
794 mConfig.pointerVelocityControlParameters.lowThreshold,
795 mConfig.pointerVelocityControlParameters.highThreshold,
796 mConfig.pointerVelocityControlParameters.acceleration);
797
798 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
799 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
800 mConfig.wheelVelocityControlParameters.scale,
801 mConfig.wheelVelocityControlParameters.lowThreshold,
802 mConfig.wheelVelocityControlParameters.highThreshold,
803 mConfig.wheelVelocityControlParameters.acceleration);
804
805 dump.appendFormat(INDENT2 "PointerGesture:\n");
806 dump.appendFormat(INDENT3 "Enabled: %s\n",
807 toString(mConfig.pointerGesturesEnabled));
808 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
809 mConfig.pointerGestureQuietInterval * 0.000001f);
810 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
811 mConfig.pointerGestureDragMinSwitchSpeed);
812 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
813 mConfig.pointerGestureTapInterval * 0.000001f);
814 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
815 mConfig.pointerGestureTapDragInterval * 0.000001f);
816 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
817 mConfig.pointerGestureTapSlop);
818 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
819 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
820 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
821 mConfig.pointerGestureMultitouchMinDistance);
822 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
823 mConfig.pointerGestureSwipeTransitionAngleCosine);
824 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
825 mConfig.pointerGestureSwipeMaxWidthRatio);
826 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
827 mConfig.pointerGestureMovementSpeedRatio);
828 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
829 mConfig.pointerGestureZoomSpeedRatio);
830}
831
832void InputReader::monitor() {
833 // Acquire and release the lock to ensure that the reader has not deadlocked.
834 mLock.lock();
835 mEventHub->wake();
836 mReaderIsAliveCondition.wait(mLock);
837 mLock.unlock();
838
839 // Check the EventHub
840 mEventHub->monitor();
841}
842
843
844// --- InputReader::ContextImpl ---
845
846InputReader::ContextImpl::ContextImpl(InputReader* reader) :
847 mReader(reader) {
848}
849
850void InputReader::ContextImpl::updateGlobalMetaState() {
851 // lock is already held by the input loop
852 mReader->updateGlobalMetaStateLocked();
853}
854
855int32_t InputReader::ContextImpl::getGlobalMetaState() {
856 // lock is already held by the input loop
857 return mReader->getGlobalMetaStateLocked();
858}
859
860void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
861 // lock is already held by the input loop
862 mReader->disableVirtualKeysUntilLocked(time);
863}
864
865bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
866 InputDevice* device, int32_t keyCode, int32_t scanCode) {
867 // lock is already held by the input loop
868 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
869}
870
871void InputReader::ContextImpl::fadePointer() {
872 // lock is already held by the input loop
873 mReader->fadePointerLocked();
874}
875
876void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
877 // lock is already held by the input loop
878 mReader->requestTimeoutAtTimeLocked(when);
879}
880
881int32_t InputReader::ContextImpl::bumpGeneration() {
882 // lock is already held by the input loop
883 return mReader->bumpGenerationLocked();
884}
885
Michael Wright842500e2015-03-13 17:32:02 -0700886void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
887 // lock is already held by whatever called refreshConfigurationLocked
888 mReader->getExternalStylusDevicesLocked(outDevices);
889}
890
891void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
892 mReader->dispatchExternalStylusState(state);
893}
894
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
896 return mReader->mPolicy.get();
897}
898
899InputListenerInterface* InputReader::ContextImpl::getListener() {
900 return mReader->mQueuedListener.get();
901}
902
903EventHubInterface* InputReader::ContextImpl::getEventHub() {
904 return mReader->mEventHub.get();
905}
906
907
908// --- InputReaderThread ---
909
910InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
911 Thread(/*canCallJava*/ true), mReader(reader) {
912}
913
914InputReaderThread::~InputReaderThread() {
915}
916
917bool InputReaderThread::threadLoop() {
918 mReader->loopOnce();
919 return true;
920}
921
922
923// --- InputDevice ---
924
925InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
926 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
927 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
928 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700929 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930}
931
932InputDevice::~InputDevice() {
933 size_t numMappers = mMappers.size();
934 for (size_t i = 0; i < numMappers; i++) {
935 delete mMappers[i];
936 }
937 mMappers.clear();
938}
939
940void InputDevice::dump(String8& dump) {
941 InputDeviceInfo deviceInfo;
942 getDeviceInfo(& deviceInfo);
943
944 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
945 deviceInfo.getDisplayName().string());
946 dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
947 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Tim Kilbourn063ff532015-04-08 10:26:18 -0700948 dump.appendFormat(INDENT2 "HasMic: %s\n", toString(mHasMic));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
950 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
951
952 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
953 if (!ranges.isEmpty()) {
954 dump.append(INDENT2 "Motion Ranges:\n");
955 for (size_t i = 0; i < ranges.size(); i++) {
956 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
957 const char* label = getAxisLabel(range.axis);
958 char name[32];
959 if (label) {
960 strncpy(name, label, sizeof(name));
961 name[sizeof(name) - 1] = '\0';
962 } else {
963 snprintf(name, sizeof(name), "%d", range.axis);
964 }
965 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
966 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
967 name, range.source, range.min, range.max, range.flat, range.fuzz,
968 range.resolution);
969 }
970 }
971
972 size_t numMappers = mMappers.size();
973 for (size_t i = 0; i < numMappers; i++) {
974 InputMapper* mapper = mMappers[i];
975 mapper->dump(dump);
976 }
977}
978
979void InputDevice::addMapper(InputMapper* mapper) {
980 mMappers.add(mapper);
981}
982
983void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
984 mSources = 0;
985
986 if (!isIgnored()) {
987 if (!changes) { // first time only
988 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
989 }
990
991 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
992 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
993 sp<KeyCharacterMap> keyboardLayout =
994 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
995 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
996 bumpGeneration();
997 }
998 }
999 }
1000
1001 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1002 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1003 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1004 if (mAlias != alias) {
1005 mAlias = alias;
1006 bumpGeneration();
1007 }
1008 }
1009 }
1010
1011 size_t numMappers = mMappers.size();
1012 for (size_t i = 0; i < numMappers; i++) {
1013 InputMapper* mapper = mMappers[i];
1014 mapper->configure(when, config, changes);
1015 mSources |= mapper->getSources();
1016 }
1017 }
1018}
1019
1020void InputDevice::reset(nsecs_t when) {
1021 size_t numMappers = mMappers.size();
1022 for (size_t i = 0; i < numMappers; i++) {
1023 InputMapper* mapper = mMappers[i];
1024 mapper->reset(when);
1025 }
1026
1027 mContext->updateGlobalMetaState();
1028
1029 notifyReset(when);
1030}
1031
1032void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1033 // Process all of the events in order for each mapper.
1034 // We cannot simply ask each mapper to process them in bulk because mappers may
1035 // have side-effects that must be interleaved. For example, joystick movement events and
1036 // gamepad button presses are handled by different mappers but they should be dispatched
1037 // in the order received.
1038 size_t numMappers = mMappers.size();
1039 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
1040#if DEBUG_RAW_EVENTS
1041 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
1042 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1043 rawEvent->when);
1044#endif
1045
1046 if (mDropUntilNextSync) {
1047 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1048 mDropUntilNextSync = false;
1049#if DEBUG_RAW_EVENTS
1050 ALOGD("Recovered from input event buffer overrun.");
1051#endif
1052 } else {
1053#if DEBUG_RAW_EVENTS
1054 ALOGD("Dropped input event while waiting for next input sync.");
1055#endif
1056 }
1057 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1058 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1059 mDropUntilNextSync = true;
1060 reset(rawEvent->when);
1061 } else {
1062 for (size_t i = 0; i < numMappers; i++) {
1063 InputMapper* mapper = mMappers[i];
1064 mapper->process(rawEvent);
1065 }
1066 }
1067 }
1068}
1069
1070void InputDevice::timeoutExpired(nsecs_t when) {
1071 size_t numMappers = mMappers.size();
1072 for (size_t i = 0; i < numMappers; i++) {
1073 InputMapper* mapper = mMappers[i];
1074 mapper->timeoutExpired(when);
1075 }
1076}
1077
Michael Wright842500e2015-03-13 17:32:02 -07001078void InputDevice::updateExternalStylusState(const StylusState& state) {
1079 size_t numMappers = mMappers.size();
1080 for (size_t i = 0; i < numMappers; i++) {
1081 InputMapper* mapper = mMappers[i];
1082 mapper->updateExternalStylusState(state);
1083 }
1084}
1085
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1087 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001088 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 size_t numMappers = mMappers.size();
1090 for (size_t i = 0; i < numMappers; i++) {
1091 InputMapper* mapper = mMappers[i];
1092 mapper->populateDeviceInfo(outDeviceInfo);
1093 }
1094}
1095
1096int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1097 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1098}
1099
1100int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1101 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1102}
1103
1104int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1105 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1106}
1107
1108int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1109 int32_t result = AKEY_STATE_UNKNOWN;
1110 size_t numMappers = mMappers.size();
1111 for (size_t i = 0; i < numMappers; i++) {
1112 InputMapper* mapper = mMappers[i];
1113 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1114 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1115 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1116 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1117 if (currentResult >= AKEY_STATE_DOWN) {
1118 return currentResult;
1119 } else if (currentResult == AKEY_STATE_UP) {
1120 result = currentResult;
1121 }
1122 }
1123 }
1124 return result;
1125}
1126
1127bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1128 const int32_t* keyCodes, uint8_t* outFlags) {
1129 bool result = false;
1130 size_t numMappers = mMappers.size();
1131 for (size_t i = 0; i < numMappers; i++) {
1132 InputMapper* mapper = mMappers[i];
1133 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1134 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1135 }
1136 }
1137 return result;
1138}
1139
1140void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1141 int32_t token) {
1142 size_t numMappers = mMappers.size();
1143 for (size_t i = 0; i < numMappers; i++) {
1144 InputMapper* mapper = mMappers[i];
1145 mapper->vibrate(pattern, patternSize, repeat, token);
1146 }
1147}
1148
1149void InputDevice::cancelVibrate(int32_t token) {
1150 size_t numMappers = mMappers.size();
1151 for (size_t i = 0; i < numMappers; i++) {
1152 InputMapper* mapper = mMappers[i];
1153 mapper->cancelVibrate(token);
1154 }
1155}
1156
Jeff Brownc9aa6282015-02-11 19:03:28 -08001157void InputDevice::cancelTouch(nsecs_t when) {
1158 size_t numMappers = mMappers.size();
1159 for (size_t i = 0; i < numMappers; i++) {
1160 InputMapper* mapper = mMappers[i];
1161 mapper->cancelTouch(when);
1162 }
1163}
1164
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165int32_t InputDevice::getMetaState() {
1166 int32_t result = 0;
1167 size_t numMappers = mMappers.size();
1168 for (size_t i = 0; i < numMappers; i++) {
1169 InputMapper* mapper = mMappers[i];
1170 result |= mapper->getMetaState();
1171 }
1172 return result;
1173}
1174
1175void InputDevice::fadePointer() {
1176 size_t numMappers = mMappers.size();
1177 for (size_t i = 0; i < numMappers; i++) {
1178 InputMapper* mapper = mMappers[i];
1179 mapper->fadePointer();
1180 }
1181}
1182
1183void InputDevice::bumpGeneration() {
1184 mGeneration = mContext->bumpGeneration();
1185}
1186
1187void InputDevice::notifyReset(nsecs_t when) {
1188 NotifyDeviceResetArgs args(when, mId);
1189 mContext->getListener()->notifyDeviceReset(&args);
1190}
1191
1192
1193// --- CursorButtonAccumulator ---
1194
1195CursorButtonAccumulator::CursorButtonAccumulator() {
1196 clearButtons();
1197}
1198
1199void CursorButtonAccumulator::reset(InputDevice* device) {
1200 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1201 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1202 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1203 mBtnBack = device->isKeyPressed(BTN_BACK);
1204 mBtnSide = device->isKeyPressed(BTN_SIDE);
1205 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1206 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1207 mBtnTask = device->isKeyPressed(BTN_TASK);
1208}
1209
1210void CursorButtonAccumulator::clearButtons() {
1211 mBtnLeft = 0;
1212 mBtnRight = 0;
1213 mBtnMiddle = 0;
1214 mBtnBack = 0;
1215 mBtnSide = 0;
1216 mBtnForward = 0;
1217 mBtnExtra = 0;
1218 mBtnTask = 0;
1219}
1220
1221void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1222 if (rawEvent->type == EV_KEY) {
1223 switch (rawEvent->code) {
1224 case BTN_LEFT:
1225 mBtnLeft = rawEvent->value;
1226 break;
1227 case BTN_RIGHT:
1228 mBtnRight = rawEvent->value;
1229 break;
1230 case BTN_MIDDLE:
1231 mBtnMiddle = rawEvent->value;
1232 break;
1233 case BTN_BACK:
1234 mBtnBack = rawEvent->value;
1235 break;
1236 case BTN_SIDE:
1237 mBtnSide = rawEvent->value;
1238 break;
1239 case BTN_FORWARD:
1240 mBtnForward = rawEvent->value;
1241 break;
1242 case BTN_EXTRA:
1243 mBtnExtra = rawEvent->value;
1244 break;
1245 case BTN_TASK:
1246 mBtnTask = rawEvent->value;
1247 break;
1248 }
1249 }
1250}
1251
1252uint32_t CursorButtonAccumulator::getButtonState() const {
1253 uint32_t result = 0;
1254 if (mBtnLeft) {
1255 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1256 }
1257 if (mBtnRight) {
1258 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1259 }
1260 if (mBtnMiddle) {
1261 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1262 }
1263 if (mBtnBack || mBtnSide) {
1264 result |= AMOTION_EVENT_BUTTON_BACK;
1265 }
1266 if (mBtnForward || mBtnExtra) {
1267 result |= AMOTION_EVENT_BUTTON_FORWARD;
1268 }
1269 return result;
1270}
1271
1272
1273// --- CursorMotionAccumulator ---
1274
1275CursorMotionAccumulator::CursorMotionAccumulator() {
1276 clearRelativeAxes();
1277}
1278
1279void CursorMotionAccumulator::reset(InputDevice* device) {
1280 clearRelativeAxes();
1281}
1282
1283void CursorMotionAccumulator::clearRelativeAxes() {
1284 mRelX = 0;
1285 mRelY = 0;
1286}
1287
1288void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1289 if (rawEvent->type == EV_REL) {
1290 switch (rawEvent->code) {
1291 case REL_X:
1292 mRelX = rawEvent->value;
1293 break;
1294 case REL_Y:
1295 mRelY = rawEvent->value;
1296 break;
1297 }
1298 }
1299}
1300
1301void CursorMotionAccumulator::finishSync() {
1302 clearRelativeAxes();
1303}
1304
1305
1306// --- CursorScrollAccumulator ---
1307
1308CursorScrollAccumulator::CursorScrollAccumulator() :
1309 mHaveRelWheel(false), mHaveRelHWheel(false) {
1310 clearRelativeAxes();
1311}
1312
1313void CursorScrollAccumulator::configure(InputDevice* device) {
1314 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1315 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1316}
1317
1318void CursorScrollAccumulator::reset(InputDevice* device) {
1319 clearRelativeAxes();
1320}
1321
1322void CursorScrollAccumulator::clearRelativeAxes() {
1323 mRelWheel = 0;
1324 mRelHWheel = 0;
1325}
1326
1327void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1328 if (rawEvent->type == EV_REL) {
1329 switch (rawEvent->code) {
1330 case REL_WHEEL:
1331 mRelWheel = rawEvent->value;
1332 break;
1333 case REL_HWHEEL:
1334 mRelHWheel = rawEvent->value;
1335 break;
1336 }
1337 }
1338}
1339
1340void CursorScrollAccumulator::finishSync() {
1341 clearRelativeAxes();
1342}
1343
1344
1345// --- TouchButtonAccumulator ---
1346
1347TouchButtonAccumulator::TouchButtonAccumulator() :
1348 mHaveBtnTouch(false), mHaveStylus(false) {
1349 clearButtons();
1350}
1351
1352void TouchButtonAccumulator::configure(InputDevice* device) {
1353 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1354 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1355 || device->hasKey(BTN_TOOL_RUBBER)
1356 || device->hasKey(BTN_TOOL_BRUSH)
1357 || device->hasKey(BTN_TOOL_PENCIL)
1358 || device->hasKey(BTN_TOOL_AIRBRUSH);
1359}
1360
1361void TouchButtonAccumulator::reset(InputDevice* device) {
1362 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1363 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001364 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1365 mBtnStylus2 =
1366 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1368 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1369 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1370 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1371 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1372 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1373 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1374 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1375 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1376 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1377 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1378}
1379
1380void TouchButtonAccumulator::clearButtons() {
1381 mBtnTouch = 0;
1382 mBtnStylus = 0;
1383 mBtnStylus2 = 0;
1384 mBtnToolFinger = 0;
1385 mBtnToolPen = 0;
1386 mBtnToolRubber = 0;
1387 mBtnToolBrush = 0;
1388 mBtnToolPencil = 0;
1389 mBtnToolAirbrush = 0;
1390 mBtnToolMouse = 0;
1391 mBtnToolLens = 0;
1392 mBtnToolDoubleTap = 0;
1393 mBtnToolTripleTap = 0;
1394 mBtnToolQuadTap = 0;
1395}
1396
1397void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1398 if (rawEvent->type == EV_KEY) {
1399 switch (rawEvent->code) {
1400 case BTN_TOUCH:
1401 mBtnTouch = rawEvent->value;
1402 break;
1403 case BTN_STYLUS:
1404 mBtnStylus = rawEvent->value;
1405 break;
1406 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001407 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 mBtnStylus2 = rawEvent->value;
1409 break;
1410 case BTN_TOOL_FINGER:
1411 mBtnToolFinger = rawEvent->value;
1412 break;
1413 case BTN_TOOL_PEN:
1414 mBtnToolPen = rawEvent->value;
1415 break;
1416 case BTN_TOOL_RUBBER:
1417 mBtnToolRubber = rawEvent->value;
1418 break;
1419 case BTN_TOOL_BRUSH:
1420 mBtnToolBrush = rawEvent->value;
1421 break;
1422 case BTN_TOOL_PENCIL:
1423 mBtnToolPencil = rawEvent->value;
1424 break;
1425 case BTN_TOOL_AIRBRUSH:
1426 mBtnToolAirbrush = rawEvent->value;
1427 break;
1428 case BTN_TOOL_MOUSE:
1429 mBtnToolMouse = rawEvent->value;
1430 break;
1431 case BTN_TOOL_LENS:
1432 mBtnToolLens = rawEvent->value;
1433 break;
1434 case BTN_TOOL_DOUBLETAP:
1435 mBtnToolDoubleTap = rawEvent->value;
1436 break;
1437 case BTN_TOOL_TRIPLETAP:
1438 mBtnToolTripleTap = rawEvent->value;
1439 break;
1440 case BTN_TOOL_QUADTAP:
1441 mBtnToolQuadTap = rawEvent->value;
1442 break;
1443 }
1444 }
1445}
1446
1447uint32_t TouchButtonAccumulator::getButtonState() const {
1448 uint32_t result = 0;
1449 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001450 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 }
1452 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001453 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 }
1455 return result;
1456}
1457
1458int32_t TouchButtonAccumulator::getToolType() const {
1459 if (mBtnToolMouse || mBtnToolLens) {
1460 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1461 }
1462 if (mBtnToolRubber) {
1463 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1464 }
1465 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1466 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1467 }
1468 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1469 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1470 }
1471 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1472}
1473
1474bool TouchButtonAccumulator::isToolActive() const {
1475 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1476 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1477 || mBtnToolMouse || mBtnToolLens
1478 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1479}
1480
1481bool TouchButtonAccumulator::isHovering() const {
1482 return mHaveBtnTouch && !mBtnTouch;
1483}
1484
1485bool TouchButtonAccumulator::hasStylus() const {
1486 return mHaveStylus;
1487}
1488
1489
1490// --- RawPointerAxes ---
1491
1492RawPointerAxes::RawPointerAxes() {
1493 clear();
1494}
1495
1496void RawPointerAxes::clear() {
1497 x.clear();
1498 y.clear();
1499 pressure.clear();
1500 touchMajor.clear();
1501 touchMinor.clear();
1502 toolMajor.clear();
1503 toolMinor.clear();
1504 orientation.clear();
1505 distance.clear();
1506 tiltX.clear();
1507 tiltY.clear();
1508 trackingId.clear();
1509 slot.clear();
1510}
1511
1512
1513// --- RawPointerData ---
1514
1515RawPointerData::RawPointerData() {
1516 clear();
1517}
1518
1519void RawPointerData::clear() {
1520 pointerCount = 0;
1521 clearIdBits();
1522}
1523
1524void RawPointerData::copyFrom(const RawPointerData& other) {
1525 pointerCount = other.pointerCount;
1526 hoveringIdBits = other.hoveringIdBits;
1527 touchingIdBits = other.touchingIdBits;
1528
1529 for (uint32_t i = 0; i < pointerCount; i++) {
1530 pointers[i] = other.pointers[i];
1531
1532 int id = pointers[i].id;
1533 idToIndex[id] = other.idToIndex[id];
1534 }
1535}
1536
1537void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1538 float x = 0, y = 0;
1539 uint32_t count = touchingIdBits.count();
1540 if (count) {
1541 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1542 uint32_t id = idBits.clearFirstMarkedBit();
1543 const Pointer& pointer = pointerForId(id);
1544 x += pointer.x;
1545 y += pointer.y;
1546 }
1547 x /= count;
1548 y /= count;
1549 }
1550 *outX = x;
1551 *outY = y;
1552}
1553
1554
1555// --- CookedPointerData ---
1556
1557CookedPointerData::CookedPointerData() {
1558 clear();
1559}
1560
1561void CookedPointerData::clear() {
1562 pointerCount = 0;
1563 hoveringIdBits.clear();
1564 touchingIdBits.clear();
1565}
1566
1567void CookedPointerData::copyFrom(const CookedPointerData& other) {
1568 pointerCount = other.pointerCount;
1569 hoveringIdBits = other.hoveringIdBits;
1570 touchingIdBits = other.touchingIdBits;
1571
1572 for (uint32_t i = 0; i < pointerCount; i++) {
1573 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1574 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1575
1576 int id = pointerProperties[i].id;
1577 idToIndex[id] = other.idToIndex[id];
1578 }
1579}
1580
1581
1582// --- SingleTouchMotionAccumulator ---
1583
1584SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1585 clearAbsoluteAxes();
1586}
1587
1588void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1589 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1590 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1591 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1592 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1593 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1594 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1595 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1596}
1597
1598void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1599 mAbsX = 0;
1600 mAbsY = 0;
1601 mAbsPressure = 0;
1602 mAbsToolWidth = 0;
1603 mAbsDistance = 0;
1604 mAbsTiltX = 0;
1605 mAbsTiltY = 0;
1606}
1607
1608void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1609 if (rawEvent->type == EV_ABS) {
1610 switch (rawEvent->code) {
1611 case ABS_X:
1612 mAbsX = rawEvent->value;
1613 break;
1614 case ABS_Y:
1615 mAbsY = rawEvent->value;
1616 break;
1617 case ABS_PRESSURE:
1618 mAbsPressure = rawEvent->value;
1619 break;
1620 case ABS_TOOL_WIDTH:
1621 mAbsToolWidth = rawEvent->value;
1622 break;
1623 case ABS_DISTANCE:
1624 mAbsDistance = rawEvent->value;
1625 break;
1626 case ABS_TILT_X:
1627 mAbsTiltX = rawEvent->value;
1628 break;
1629 case ABS_TILT_Y:
1630 mAbsTiltY = rawEvent->value;
1631 break;
1632 }
1633 }
1634}
1635
1636
1637// --- MultiTouchMotionAccumulator ---
1638
1639MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1640 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1641 mHaveStylus(false) {
1642}
1643
1644MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1645 delete[] mSlots;
1646}
1647
1648void MultiTouchMotionAccumulator::configure(InputDevice* device,
1649 size_t slotCount, bool usingSlotsProtocol) {
1650 mSlotCount = slotCount;
1651 mUsingSlotsProtocol = usingSlotsProtocol;
1652 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1653
1654 delete[] mSlots;
1655 mSlots = new Slot[slotCount];
1656}
1657
1658void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1659 // Unfortunately there is no way to read the initial contents of the slots.
1660 // So when we reset the accumulator, we must assume they are all zeroes.
1661 if (mUsingSlotsProtocol) {
1662 // Query the driver for the current slot index and use it as the initial slot
1663 // before we start reading events from the device. It is possible that the
1664 // current slot index will not be the same as it was when the first event was
1665 // written into the evdev buffer, which means the input mapper could start
1666 // out of sync with the initial state of the events in the evdev buffer.
1667 // In the extremely unlikely case that this happens, the data from
1668 // two slots will be confused until the next ABS_MT_SLOT event is received.
1669 // This can cause the touch point to "jump", but at least there will be
1670 // no stuck touches.
1671 int32_t initialSlot;
1672 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1673 ABS_MT_SLOT, &initialSlot);
1674 if (status) {
1675 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1676 initialSlot = -1;
1677 }
1678 clearSlots(initialSlot);
1679 } else {
1680 clearSlots(-1);
1681 }
1682}
1683
1684void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1685 if (mSlots) {
1686 for (size_t i = 0; i < mSlotCount; i++) {
1687 mSlots[i].clear();
1688 }
1689 }
1690 mCurrentSlot = initialSlot;
1691}
1692
1693void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1694 if (rawEvent->type == EV_ABS) {
1695 bool newSlot = false;
1696 if (mUsingSlotsProtocol) {
1697 if (rawEvent->code == ABS_MT_SLOT) {
1698 mCurrentSlot = rawEvent->value;
1699 newSlot = true;
1700 }
1701 } else if (mCurrentSlot < 0) {
1702 mCurrentSlot = 0;
1703 }
1704
1705 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1706#if DEBUG_POINTERS
1707 if (newSlot) {
1708 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1709 "should be between 0 and %d; ignoring this slot.",
1710 mCurrentSlot, mSlotCount - 1);
1711 }
1712#endif
1713 } else {
1714 Slot* slot = &mSlots[mCurrentSlot];
1715
1716 switch (rawEvent->code) {
1717 case ABS_MT_POSITION_X:
1718 slot->mInUse = true;
1719 slot->mAbsMTPositionX = rawEvent->value;
1720 break;
1721 case ABS_MT_POSITION_Y:
1722 slot->mInUse = true;
1723 slot->mAbsMTPositionY = rawEvent->value;
1724 break;
1725 case ABS_MT_TOUCH_MAJOR:
1726 slot->mInUse = true;
1727 slot->mAbsMTTouchMajor = rawEvent->value;
1728 break;
1729 case ABS_MT_TOUCH_MINOR:
1730 slot->mInUse = true;
1731 slot->mAbsMTTouchMinor = rawEvent->value;
1732 slot->mHaveAbsMTTouchMinor = true;
1733 break;
1734 case ABS_MT_WIDTH_MAJOR:
1735 slot->mInUse = true;
1736 slot->mAbsMTWidthMajor = rawEvent->value;
1737 break;
1738 case ABS_MT_WIDTH_MINOR:
1739 slot->mInUse = true;
1740 slot->mAbsMTWidthMinor = rawEvent->value;
1741 slot->mHaveAbsMTWidthMinor = true;
1742 break;
1743 case ABS_MT_ORIENTATION:
1744 slot->mInUse = true;
1745 slot->mAbsMTOrientation = rawEvent->value;
1746 break;
1747 case ABS_MT_TRACKING_ID:
1748 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1749 // The slot is no longer in use but it retains its previous contents,
1750 // which may be reused for subsequent touches.
1751 slot->mInUse = false;
1752 } else {
1753 slot->mInUse = true;
1754 slot->mAbsMTTrackingId = rawEvent->value;
1755 }
1756 break;
1757 case ABS_MT_PRESSURE:
1758 slot->mInUse = true;
1759 slot->mAbsMTPressure = rawEvent->value;
1760 break;
1761 case ABS_MT_DISTANCE:
1762 slot->mInUse = true;
1763 slot->mAbsMTDistance = rawEvent->value;
1764 break;
1765 case ABS_MT_TOOL_TYPE:
1766 slot->mInUse = true;
1767 slot->mAbsMTToolType = rawEvent->value;
1768 slot->mHaveAbsMTToolType = true;
1769 break;
1770 }
1771 }
1772 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1773 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1774 mCurrentSlot += 1;
1775 }
1776}
1777
1778void MultiTouchMotionAccumulator::finishSync() {
1779 if (!mUsingSlotsProtocol) {
1780 clearSlots(-1);
1781 }
1782}
1783
1784bool MultiTouchMotionAccumulator::hasStylus() const {
1785 return mHaveStylus;
1786}
1787
1788
1789// --- MultiTouchMotionAccumulator::Slot ---
1790
1791MultiTouchMotionAccumulator::Slot::Slot() {
1792 clear();
1793}
1794
1795void MultiTouchMotionAccumulator::Slot::clear() {
1796 mInUse = false;
1797 mHaveAbsMTTouchMinor = false;
1798 mHaveAbsMTWidthMinor = false;
1799 mHaveAbsMTToolType = false;
1800 mAbsMTPositionX = 0;
1801 mAbsMTPositionY = 0;
1802 mAbsMTTouchMajor = 0;
1803 mAbsMTTouchMinor = 0;
1804 mAbsMTWidthMajor = 0;
1805 mAbsMTWidthMinor = 0;
1806 mAbsMTOrientation = 0;
1807 mAbsMTTrackingId = -1;
1808 mAbsMTPressure = 0;
1809 mAbsMTDistance = 0;
1810 mAbsMTToolType = 0;
1811}
1812
1813int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1814 if (mHaveAbsMTToolType) {
1815 switch (mAbsMTToolType) {
1816 case MT_TOOL_FINGER:
1817 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1818 case MT_TOOL_PEN:
1819 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1820 }
1821 }
1822 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1823}
1824
1825
1826// --- InputMapper ---
1827
1828InputMapper::InputMapper(InputDevice* device) :
1829 mDevice(device), mContext(device->getContext()) {
1830}
1831
1832InputMapper::~InputMapper() {
1833}
1834
1835void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1836 info->addSource(getSources());
1837}
1838
1839void InputMapper::dump(String8& dump) {
1840}
1841
1842void InputMapper::configure(nsecs_t when,
1843 const InputReaderConfiguration* config, uint32_t changes) {
1844}
1845
1846void InputMapper::reset(nsecs_t when) {
1847}
1848
1849void InputMapper::timeoutExpired(nsecs_t when) {
1850}
1851
1852int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1853 return AKEY_STATE_UNKNOWN;
1854}
1855
1856int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1857 return AKEY_STATE_UNKNOWN;
1858}
1859
1860int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1861 return AKEY_STATE_UNKNOWN;
1862}
1863
1864bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1865 const int32_t* keyCodes, uint8_t* outFlags) {
1866 return false;
1867}
1868
1869void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1870 int32_t token) {
1871}
1872
1873void InputMapper::cancelVibrate(int32_t token) {
1874}
1875
Jeff Brownc9aa6282015-02-11 19:03:28 -08001876void InputMapper::cancelTouch(nsecs_t when) {
1877}
1878
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879int32_t InputMapper::getMetaState() {
1880 return 0;
1881}
1882
Michael Wright842500e2015-03-13 17:32:02 -07001883void InputMapper::updateExternalStylusState(const StylusState& state) {
1884
1885}
1886
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887void InputMapper::fadePointer() {
1888}
1889
1890status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1891 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1892}
1893
1894void InputMapper::bumpGeneration() {
1895 mDevice->bumpGeneration();
1896}
1897
1898void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
1899 const RawAbsoluteAxisInfo& axis, const char* name) {
1900 if (axis.valid) {
1901 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
1902 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1903 } else {
1904 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1905 }
1906}
1907
Michael Wright842500e2015-03-13 17:32:02 -07001908void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
1909 dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
1910 dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
1911 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
1912 dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
1913}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914
1915// --- SwitchInputMapper ---
1916
1917SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001918 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919}
1920
1921SwitchInputMapper::~SwitchInputMapper() {
1922}
1923
1924uint32_t SwitchInputMapper::getSources() {
1925 return AINPUT_SOURCE_SWITCH;
1926}
1927
1928void SwitchInputMapper::process(const RawEvent* rawEvent) {
1929 switch (rawEvent->type) {
1930 case EV_SW:
1931 processSwitch(rawEvent->code, rawEvent->value);
1932 break;
1933
1934 case EV_SYN:
1935 if (rawEvent->code == SYN_REPORT) {
1936 sync(rawEvent->when);
1937 }
1938 }
1939}
1940
1941void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
1942 if (switchCode >= 0 && switchCode < 32) {
1943 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001944 mSwitchValues |= 1 << switchCode;
1945 } else {
1946 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 }
1948 mUpdatedSwitchMask |= 1 << switchCode;
1949 }
1950}
1951
1952void SwitchInputMapper::sync(nsecs_t when) {
1953 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07001954 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001955 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 getListener()->notifySwitch(&args);
1957
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958 mUpdatedSwitchMask = 0;
1959 }
1960}
1961
1962int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1963 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1964}
1965
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001966void SwitchInputMapper::dump(String8& dump) {
1967 dump.append(INDENT2 "Switch Input Mapper:\n");
1968 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
1969}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
1971// --- VibratorInputMapper ---
1972
1973VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
1974 InputMapper(device), mVibrating(false) {
1975}
1976
1977VibratorInputMapper::~VibratorInputMapper() {
1978}
1979
1980uint32_t VibratorInputMapper::getSources() {
1981 return 0;
1982}
1983
1984void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1985 InputMapper::populateDeviceInfo(info);
1986
1987 info->setVibrator(true);
1988}
1989
1990void VibratorInputMapper::process(const RawEvent* rawEvent) {
1991 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
1992}
1993
1994void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1995 int32_t token) {
1996#if DEBUG_VIBRATOR
1997 String8 patternStr;
1998 for (size_t i = 0; i < patternSize; i++) {
1999 if (i != 0) {
2000 patternStr.append(", ");
2001 }
2002 patternStr.appendFormat("%lld", pattern[i]);
2003 }
2004 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
2005 getDeviceId(), patternStr.string(), repeat, token);
2006#endif
2007
2008 mVibrating = true;
2009 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2010 mPatternSize = patternSize;
2011 mRepeat = repeat;
2012 mToken = token;
2013 mIndex = -1;
2014
2015 nextStep();
2016}
2017
2018void VibratorInputMapper::cancelVibrate(int32_t token) {
2019#if DEBUG_VIBRATOR
2020 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2021#endif
2022
2023 if (mVibrating && mToken == token) {
2024 stopVibrating();
2025 }
2026}
2027
2028void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2029 if (mVibrating) {
2030 if (when >= mNextStepTime) {
2031 nextStep();
2032 } else {
2033 getContext()->requestTimeoutAtTime(mNextStepTime);
2034 }
2035 }
2036}
2037
2038void VibratorInputMapper::nextStep() {
2039 mIndex += 1;
2040 if (size_t(mIndex) >= mPatternSize) {
2041 if (mRepeat < 0) {
2042 // We are done.
2043 stopVibrating();
2044 return;
2045 }
2046 mIndex = mRepeat;
2047 }
2048
2049 bool vibratorOn = mIndex & 1;
2050 nsecs_t duration = mPattern[mIndex];
2051 if (vibratorOn) {
2052#if DEBUG_VIBRATOR
2053 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
2054 getDeviceId(), duration);
2055#endif
2056 getEventHub()->vibrate(getDeviceId(), duration);
2057 } else {
2058#if DEBUG_VIBRATOR
2059 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2060#endif
2061 getEventHub()->cancelVibrate(getDeviceId());
2062 }
2063 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2064 mNextStepTime = now + duration;
2065 getContext()->requestTimeoutAtTime(mNextStepTime);
2066#if DEBUG_VIBRATOR
2067 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2068#endif
2069}
2070
2071void VibratorInputMapper::stopVibrating() {
2072 mVibrating = false;
2073#if DEBUG_VIBRATOR
2074 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2075#endif
2076 getEventHub()->cancelVibrate(getDeviceId());
2077}
2078
2079void VibratorInputMapper::dump(String8& dump) {
2080 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2081 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2082}
2083
2084
2085// --- KeyboardInputMapper ---
2086
2087KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2088 uint32_t source, int32_t keyboardType) :
2089 InputMapper(device), mSource(source),
2090 mKeyboardType(keyboardType) {
2091}
2092
2093KeyboardInputMapper::~KeyboardInputMapper() {
2094}
2095
2096uint32_t KeyboardInputMapper::getSources() {
2097 return mSource;
2098}
2099
2100void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2101 InputMapper::populateDeviceInfo(info);
2102
2103 info->setKeyboardType(mKeyboardType);
2104 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2105}
2106
2107void KeyboardInputMapper::dump(String8& dump) {
2108 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2109 dumpParameters(dump);
2110 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2111 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002112 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002114 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115}
2116
2117
2118void KeyboardInputMapper::configure(nsecs_t when,
2119 const InputReaderConfiguration* config, uint32_t changes) {
2120 InputMapper::configure(when, config, changes);
2121
2122 if (!changes) { // first time only
2123 // Configure basic parameters.
2124 configureParameters();
2125 }
2126
2127 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2128 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2129 DisplayViewport v;
2130 if (config->getDisplayInfo(false /*external*/, &v)) {
2131 mOrientation = v.orientation;
2132 } else {
2133 mOrientation = DISPLAY_ORIENTATION_0;
2134 }
2135 } else {
2136 mOrientation = DISPLAY_ORIENTATION_0;
2137 }
2138 }
2139}
2140
2141void KeyboardInputMapper::configureParameters() {
2142 mParameters.orientationAware = false;
2143 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
2144 mParameters.orientationAware);
2145
2146 mParameters.hasAssociatedDisplay = false;
2147 if (mParameters.orientationAware) {
2148 mParameters.hasAssociatedDisplay = true;
2149 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002150
2151 mParameters.handlesKeyRepeat = false;
2152 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.handlesKeyRepeat"),
2153 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154}
2155
2156void KeyboardInputMapper::dumpParameters(String8& dump) {
2157 dump.append(INDENT3 "Parameters:\n");
2158 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2159 toString(mParameters.hasAssociatedDisplay));
2160 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2161 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002162 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2163 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164}
2165
2166void KeyboardInputMapper::reset(nsecs_t when) {
2167 mMetaState = AMETA_NONE;
2168 mDownTime = 0;
2169 mKeyDowns.clear();
2170 mCurrentHidUsage = 0;
2171
2172 resetLedState();
2173
2174 InputMapper::reset(when);
2175}
2176
2177void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2178 switch (rawEvent->type) {
2179 case EV_KEY: {
2180 int32_t scanCode = rawEvent->code;
2181 int32_t usageCode = mCurrentHidUsage;
2182 mCurrentHidUsage = 0;
2183
2184 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002185 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187 break;
2188 }
2189 case EV_MSC: {
2190 if (rawEvent->code == MSC_SCAN) {
2191 mCurrentHidUsage = rawEvent->value;
2192 }
2193 break;
2194 }
2195 case EV_SYN: {
2196 if (rawEvent->code == SYN_REPORT) {
2197 mCurrentHidUsage = 0;
2198 }
2199 }
2200 }
2201}
2202
2203bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2204 return scanCode < BTN_MOUSE
2205 || scanCode >= KEY_OK
2206 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2207 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2208}
2209
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002210void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2211 int32_t usageCode) {
2212 int32_t keyCode;
2213 int32_t keyMetaState;
2214 uint32_t policyFlags;
2215
2216 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2217 &keyCode, &keyMetaState, &policyFlags)) {
2218 keyCode = AKEYCODE_UNKNOWN;
2219 keyMetaState = mMetaState;
2220 policyFlags = 0;
2221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222
2223 if (down) {
2224 // Rotate key codes according to orientation if needed.
2225 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2226 keyCode = rotateKeyCode(keyCode, mOrientation);
2227 }
2228
2229 // Add key down.
2230 ssize_t keyDownIndex = findKeyDown(scanCode);
2231 if (keyDownIndex >= 0) {
2232 // key repeat, be sure to use same keycode as before in case of rotation
2233 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2234 } else {
2235 // key down
2236 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2237 && mContext->shouldDropVirtualKey(when,
2238 getDevice(), keyCode, scanCode)) {
2239 return;
2240 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002241 if (policyFlags & POLICY_FLAG_GESTURE) {
2242 mDevice->cancelTouch(when);
2243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244
2245 mKeyDowns.push();
2246 KeyDown& keyDown = mKeyDowns.editTop();
2247 keyDown.keyCode = keyCode;
2248 keyDown.scanCode = scanCode;
2249 }
2250
2251 mDownTime = when;
2252 } else {
2253 // Remove key down.
2254 ssize_t keyDownIndex = findKeyDown(scanCode);
2255 if (keyDownIndex >= 0) {
2256 // key up, be sure to use same keycode as before in case of rotation
2257 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2258 mKeyDowns.removeAt(size_t(keyDownIndex));
2259 } else {
2260 // key was not actually down
2261 ALOGI("Dropping key up from device %s because the key was not down. "
2262 "keyCode=%d, scanCode=%d",
2263 getDeviceName().string(), keyCode, scanCode);
2264 return;
2265 }
2266 }
2267
2268 int32_t oldMetaState = mMetaState;
2269 int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState);
2270 bool metaStateChanged = oldMetaState != newMetaState;
2271 if (metaStateChanged) {
2272 mMetaState = newMetaState;
2273 updateLedState(false);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002274
2275 // If global meta state changed send it along with the key.
2276 // If it has not changed then we'll use what keymap gave us,
2277 // since key replacement logic might temporarily reset a few
2278 // meta bits for given key.
2279 keyMetaState = newMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 }
2281
2282 nsecs_t downTime = mDownTime;
2283
2284 // Key down on external an keyboard should wake the device.
2285 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2286 // For internal keyboards, the key layout file should specify the policy flags for
2287 // each wake key individually.
2288 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright872db4f2014-04-22 15:03:51 -07002289 if (down && getDevice()->isExternal()) {
2290 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 }
2292
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002293 if (mParameters.handlesKeyRepeat) {
2294 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2295 }
2296
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 if (metaStateChanged) {
2298 getContext()->updateGlobalMetaState();
2299 }
2300
2301 if (down && !isMetaKey(keyCode)) {
2302 getContext()->fadePointer();
2303 }
2304
2305 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2306 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002307 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 getListener()->notifyKey(&args);
2309}
2310
2311ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2312 size_t n = mKeyDowns.size();
2313 for (size_t i = 0; i < n; i++) {
2314 if (mKeyDowns[i].scanCode == scanCode) {
2315 return i;
2316 }
2317 }
2318 return -1;
2319}
2320
2321int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2322 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2323}
2324
2325int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2326 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2327}
2328
2329bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2330 const int32_t* keyCodes, uint8_t* outFlags) {
2331 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2332}
2333
2334int32_t KeyboardInputMapper::getMetaState() {
2335 return mMetaState;
2336}
2337
2338void KeyboardInputMapper::resetLedState() {
2339 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2340 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2341 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2342
2343 updateLedState(true);
2344}
2345
2346void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2347 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2348 ledState.on = false;
2349}
2350
2351void KeyboardInputMapper::updateLedState(bool reset) {
2352 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2353 AMETA_CAPS_LOCK_ON, reset);
2354 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2355 AMETA_NUM_LOCK_ON, reset);
2356 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2357 AMETA_SCROLL_LOCK_ON, reset);
2358}
2359
2360void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2361 int32_t led, int32_t modifier, bool reset) {
2362 if (ledState.avail) {
2363 bool desiredState = (mMetaState & modifier) != 0;
2364 if (reset || ledState.on != desiredState) {
2365 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2366 ledState.on = desiredState;
2367 }
2368 }
2369}
2370
2371
2372// --- CursorInputMapper ---
2373
2374CursorInputMapper::CursorInputMapper(InputDevice* device) :
2375 InputMapper(device) {
2376}
2377
2378CursorInputMapper::~CursorInputMapper() {
2379}
2380
2381uint32_t CursorInputMapper::getSources() {
2382 return mSource;
2383}
2384
2385void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2386 InputMapper::populateDeviceInfo(info);
2387
2388 if (mParameters.mode == Parameters::MODE_POINTER) {
2389 float minX, minY, maxX, maxY;
2390 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2391 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2392 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2393 }
2394 } else {
2395 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2396 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2397 }
2398 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2399
2400 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2401 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2402 }
2403 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2404 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2405 }
2406}
2407
2408void CursorInputMapper::dump(String8& dump) {
2409 dump.append(INDENT2 "Cursor Input Mapper:\n");
2410 dumpParameters(dump);
2411 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2412 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2413 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2414 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2415 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2416 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2417 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2418 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2419 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2420 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2421 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2422 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2423 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002424 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425}
2426
2427void CursorInputMapper::configure(nsecs_t when,
2428 const InputReaderConfiguration* config, uint32_t changes) {
2429 InputMapper::configure(when, config, changes);
2430
2431 if (!changes) { // first time only
2432 mCursorScrollAccumulator.configure(getDevice());
2433
2434 // Configure basic parameters.
2435 configureParameters();
2436
2437 // Configure device mode.
2438 switch (mParameters.mode) {
2439 case Parameters::MODE_POINTER:
2440 mSource = AINPUT_SOURCE_MOUSE;
2441 mXPrecision = 1.0f;
2442 mYPrecision = 1.0f;
2443 mXScale = 1.0f;
2444 mYScale = 1.0f;
2445 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2446 break;
2447 case Parameters::MODE_NAVIGATION:
2448 mSource = AINPUT_SOURCE_TRACKBALL;
2449 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2450 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2451 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2452 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2453 break;
2454 }
2455
2456 mVWheelScale = 1.0f;
2457 mHWheelScale = 1.0f;
2458 }
2459
2460 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2461 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2462 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2463 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2464 }
2465
2466 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2467 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2468 DisplayViewport v;
2469 if (config->getDisplayInfo(false /*external*/, &v)) {
2470 mOrientation = v.orientation;
2471 } else {
2472 mOrientation = DISPLAY_ORIENTATION_0;
2473 }
2474 } else {
2475 mOrientation = DISPLAY_ORIENTATION_0;
2476 }
2477 bumpGeneration();
2478 }
2479}
2480
2481void CursorInputMapper::configureParameters() {
2482 mParameters.mode = Parameters::MODE_POINTER;
2483 String8 cursorModeString;
2484 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2485 if (cursorModeString == "navigation") {
2486 mParameters.mode = Parameters::MODE_NAVIGATION;
2487 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2488 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2489 }
2490 }
2491
2492 mParameters.orientationAware = false;
2493 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2494 mParameters.orientationAware);
2495
2496 mParameters.hasAssociatedDisplay = false;
2497 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2498 mParameters.hasAssociatedDisplay = true;
2499 }
2500}
2501
2502void CursorInputMapper::dumpParameters(String8& dump) {
2503 dump.append(INDENT3 "Parameters:\n");
2504 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2505 toString(mParameters.hasAssociatedDisplay));
2506
2507 switch (mParameters.mode) {
2508 case Parameters::MODE_POINTER:
2509 dump.append(INDENT4 "Mode: pointer\n");
2510 break;
2511 case Parameters::MODE_NAVIGATION:
2512 dump.append(INDENT4 "Mode: navigation\n");
2513 break;
2514 default:
2515 ALOG_ASSERT(false);
2516 }
2517
2518 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2519 toString(mParameters.orientationAware));
2520}
2521
2522void CursorInputMapper::reset(nsecs_t when) {
2523 mButtonState = 0;
2524 mDownTime = 0;
2525
2526 mPointerVelocityControl.reset();
2527 mWheelXVelocityControl.reset();
2528 mWheelYVelocityControl.reset();
2529
2530 mCursorButtonAccumulator.reset(getDevice());
2531 mCursorMotionAccumulator.reset(getDevice());
2532 mCursorScrollAccumulator.reset(getDevice());
2533
2534 InputMapper::reset(when);
2535}
2536
2537void CursorInputMapper::process(const RawEvent* rawEvent) {
2538 mCursorButtonAccumulator.process(rawEvent);
2539 mCursorMotionAccumulator.process(rawEvent);
2540 mCursorScrollAccumulator.process(rawEvent);
2541
2542 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2543 sync(rawEvent->when);
2544 }
2545}
2546
2547void CursorInputMapper::sync(nsecs_t when) {
2548 int32_t lastButtonState = mButtonState;
2549 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2550 mButtonState = currentButtonState;
2551
2552 bool wasDown = isPointerDown(lastButtonState);
2553 bool down = isPointerDown(currentButtonState);
2554 bool downChanged;
2555 if (!wasDown && down) {
2556 mDownTime = when;
2557 downChanged = true;
2558 } else if (wasDown && !down) {
2559 downChanged = true;
2560 } else {
2561 downChanged = false;
2562 }
2563 nsecs_t downTime = mDownTime;
2564 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002565 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2566 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567
2568 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2569 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2570 bool moved = deltaX != 0 || deltaY != 0;
2571
2572 // Rotate delta according to orientation if needed.
2573 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2574 && (deltaX != 0.0f || deltaY != 0.0f)) {
2575 rotateDelta(mOrientation, &deltaX, &deltaY);
2576 }
2577
2578 // Move the pointer.
2579 PointerProperties pointerProperties;
2580 pointerProperties.clear();
2581 pointerProperties.id = 0;
2582 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2583
2584 PointerCoords pointerCoords;
2585 pointerCoords.clear();
2586
2587 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2588 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2589 bool scrolled = vscroll != 0 || hscroll != 0;
2590
2591 mWheelYVelocityControl.move(when, NULL, &vscroll);
2592 mWheelXVelocityControl.move(when, &hscroll, NULL);
2593
2594 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2595
2596 int32_t displayId;
2597 if (mPointerController != NULL) {
2598 if (moved || scrolled || buttonsChanged) {
2599 mPointerController->setPresentation(
2600 PointerControllerInterface::PRESENTATION_POINTER);
2601
2602 if (moved) {
2603 mPointerController->move(deltaX, deltaY);
2604 }
2605
2606 if (buttonsChanged) {
2607 mPointerController->setButtonState(currentButtonState);
2608 }
2609
2610 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2611 }
2612
2613 float x, y;
2614 mPointerController->getPosition(&x, &y);
2615 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2616 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002617 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2618 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 displayId = ADISPLAY_ID_DEFAULT;
2620 } else {
2621 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2622 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2623 displayId = ADISPLAY_ID_NONE;
2624 }
2625
2626 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2627
2628 // Moving an external trackball or mouse should wake the device.
2629 // We don't do this for internal cursor devices to prevent them from waking up
2630 // the device in your pocket.
2631 // TODO: Use the input device configuration to control this behavior more finely.
2632 uint32_t policyFlags = 0;
2633 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002634 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 }
2636
2637 // Synthesize key down from buttons if needed.
2638 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2639 policyFlags, lastButtonState, currentButtonState);
2640
2641 // Send motion event.
2642 if (downChanged || moved || scrolled || buttonsChanged) {
2643 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002644 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 int32_t motionEventAction;
2646 if (downChanged) {
2647 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2648 } else if (down || mPointerController == NULL) {
2649 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2650 } else {
2651 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2652 }
2653
Michael Wright7b159c92015-05-14 14:48:03 +01002654 if (buttonsReleased) {
2655 BitSet32 released(buttonsReleased);
2656 while (!released.isEmpty()) {
2657 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2658 buttonState &= ~actionButton;
2659 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2660 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2661 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2662 displayId, 1, &pointerProperties, &pointerCoords,
2663 mXPrecision, mYPrecision, downTime);
2664 getListener()->notifyMotion(&releaseArgs);
2665 }
2666 }
2667
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002669 motionEventAction, 0, 0, metaState, currentButtonState,
2670 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 displayId, 1, &pointerProperties, &pointerCoords,
2672 mXPrecision, mYPrecision, downTime);
2673 getListener()->notifyMotion(&args);
2674
Michael Wright7b159c92015-05-14 14:48:03 +01002675 if (buttonsPressed) {
2676 BitSet32 pressed(buttonsPressed);
2677 while (!pressed.isEmpty()) {
2678 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2679 buttonState |= actionButton;
2680 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2681 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2682 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2683 displayId, 1, &pointerProperties, &pointerCoords,
2684 mXPrecision, mYPrecision, downTime);
2685 getListener()->notifyMotion(&pressArgs);
2686 }
2687 }
2688
2689 ALOG_ASSERT(buttonState == currentButtonState);
2690
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 // Send hover move after UP to tell the application that the mouse is hovering now.
2692 if (motionEventAction == AMOTION_EVENT_ACTION_UP
2693 && mPointerController != NULL) {
2694 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002695 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2697 displayId, 1, &pointerProperties, &pointerCoords,
2698 mXPrecision, mYPrecision, downTime);
2699 getListener()->notifyMotion(&hoverArgs);
2700 }
2701
2702 // Send scroll events.
2703 if (scrolled) {
2704 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2705 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2706
2707 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002708 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 AMOTION_EVENT_EDGE_FLAG_NONE,
2710 displayId, 1, &pointerProperties, &pointerCoords,
2711 mXPrecision, mYPrecision, downTime);
2712 getListener()->notifyMotion(&scrollArgs);
2713 }
2714 }
2715
2716 // Synthesize key up from buttons if needed.
2717 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2718 policyFlags, lastButtonState, currentButtonState);
2719
2720 mCursorMotionAccumulator.finishSync();
2721 mCursorScrollAccumulator.finishSync();
2722}
2723
2724int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2725 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2726 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2727 } else {
2728 return AKEY_STATE_UNKNOWN;
2729 }
2730}
2731
2732void CursorInputMapper::fadePointer() {
2733 if (mPointerController != NULL) {
2734 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2735 }
2736}
2737
Prashant Malani1941ff52015-08-11 18:29:28 -07002738// --- RotaryEncoderInputMapper ---
2739
2740RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2741 InputMapper(device) {
2742 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2743}
2744
2745RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2746}
2747
2748uint32_t RotaryEncoderInputMapper::getSources() {
2749 return mSource;
2750}
2751
2752void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2753 InputMapper::populateDeviceInfo(info);
2754
2755 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002756 float res = 0.0f;
2757 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2758 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2759 }
2760 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2761 mScalingFactor)) {
2762 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2763 "default to 1.0!\n");
2764 mScalingFactor = 1.0f;
2765 }
2766 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2767 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002768 }
2769}
2770
2771void RotaryEncoderInputMapper::dump(String8& dump) {
2772 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2773 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2774 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2775}
2776
2777void RotaryEncoderInputMapper::configure(nsecs_t when,
2778 const InputReaderConfiguration* config, uint32_t changes) {
2779 InputMapper::configure(when, config, changes);
2780 if (!changes) {
2781 mRotaryEncoderScrollAccumulator.configure(getDevice());
2782 }
2783}
2784
2785void RotaryEncoderInputMapper::reset(nsecs_t when) {
2786 mRotaryEncoderScrollAccumulator.reset(getDevice());
2787
2788 InputMapper::reset(when);
2789}
2790
2791void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2792 mRotaryEncoderScrollAccumulator.process(rawEvent);
2793
2794 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2795 sync(rawEvent->when);
2796 }
2797}
2798
2799void RotaryEncoderInputMapper::sync(nsecs_t when) {
2800 PointerCoords pointerCoords;
2801 pointerCoords.clear();
2802
2803 PointerProperties pointerProperties;
2804 pointerProperties.clear();
2805 pointerProperties.id = 0;
2806 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2807
2808 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2809 bool scrolled = scroll != 0;
2810
2811 // This is not a pointer, so it's not associated with a display.
2812 int32_t displayId = ADISPLAY_ID_NONE;
2813
2814 // Moving the rotary encoder should wake the device (if specified).
2815 uint32_t policyFlags = 0;
2816 if (scrolled && getDevice()->isExternal()) {
2817 policyFlags |= POLICY_FLAG_WAKE;
2818 }
2819
2820 // Send motion event.
2821 if (scrolled) {
2822 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002823 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002824
2825 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2826 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2827 AMOTION_EVENT_EDGE_FLAG_NONE,
2828 displayId, 1, &pointerProperties, &pointerCoords,
2829 0, 0, 0);
2830 getListener()->notifyMotion(&scrollArgs);
2831 }
2832
2833 mRotaryEncoderScrollAccumulator.finishSync();
2834}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835
2836// --- TouchInputMapper ---
2837
2838TouchInputMapper::TouchInputMapper(InputDevice* device) :
2839 InputMapper(device),
2840 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2841 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2842 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2843}
2844
2845TouchInputMapper::~TouchInputMapper() {
2846}
2847
2848uint32_t TouchInputMapper::getSources() {
2849 return mSource;
2850}
2851
2852void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2853 InputMapper::populateDeviceInfo(info);
2854
2855 if (mDeviceMode != DEVICE_MODE_DISABLED) {
2856 info->addMotionRange(mOrientedRanges.x);
2857 info->addMotionRange(mOrientedRanges.y);
2858 info->addMotionRange(mOrientedRanges.pressure);
2859
2860 if (mOrientedRanges.haveSize) {
2861 info->addMotionRange(mOrientedRanges.size);
2862 }
2863
2864 if (mOrientedRanges.haveTouchSize) {
2865 info->addMotionRange(mOrientedRanges.touchMajor);
2866 info->addMotionRange(mOrientedRanges.touchMinor);
2867 }
2868
2869 if (mOrientedRanges.haveToolSize) {
2870 info->addMotionRange(mOrientedRanges.toolMajor);
2871 info->addMotionRange(mOrientedRanges.toolMinor);
2872 }
2873
2874 if (mOrientedRanges.haveOrientation) {
2875 info->addMotionRange(mOrientedRanges.orientation);
2876 }
2877
2878 if (mOrientedRanges.haveDistance) {
2879 info->addMotionRange(mOrientedRanges.distance);
2880 }
2881
2882 if (mOrientedRanges.haveTilt) {
2883 info->addMotionRange(mOrientedRanges.tilt);
2884 }
2885
2886 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2887 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2888 0.0f);
2889 }
2890 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2891 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2892 0.0f);
2893 }
2894 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2895 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2896 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2897 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2898 x.fuzz, x.resolution);
2899 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2900 y.fuzz, y.resolution);
2901 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2902 x.fuzz, x.resolution);
2903 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2904 y.fuzz, y.resolution);
2905 }
2906 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2907 }
2908}
2909
2910void TouchInputMapper::dump(String8& dump) {
2911 dump.append(INDENT2 "Touch Input Mapper:\n");
2912 dumpParameters(dump);
2913 dumpVirtualKeys(dump);
2914 dumpRawPointerAxes(dump);
2915 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07002916 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 dumpSurface(dump);
2918
2919 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2920 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2921 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2922 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2923 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2924 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
2925 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
2926 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
2927 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
2928 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
2929 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
2930 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
2931 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
2932 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
2933 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
2934 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
2935 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
2936
Michael Wright7b159c92015-05-14 14:48:03 +01002937 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07002939 mLastRawState.rawPointerData.pointerCount);
2940 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
2941 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
2943 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
2944 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
2945 "toolType=%d, isHovering=%s\n", i,
2946 pointer.id, pointer.x, pointer.y, pointer.pressure,
2947 pointer.touchMajor, pointer.touchMinor,
2948 pointer.toolMajor, pointer.toolMinor,
2949 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
2950 pointer.toolType, toString(pointer.isHovering));
2951 }
2952
Michael Wright7b159c92015-05-14 14:48:03 +01002953 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07002955 mLastCookedState.cookedPointerData.pointerCount);
2956 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
2957 const PointerProperties& pointerProperties =
2958 mLastCookedState.cookedPointerData.pointerProperties[i];
2959 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
2961 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
2962 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
2963 "toolType=%d, isHovering=%s\n", i,
2964 pointerProperties.id,
2965 pointerCoords.getX(),
2966 pointerCoords.getY(),
2967 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2968 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2969 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2970 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2971 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2972 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
2973 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
2974 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
2975 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07002976 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 }
2978
Michael Wright842500e2015-03-13 17:32:02 -07002979 dump.append(INDENT3 "Stylus Fusion:\n");
2980 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
2981 toString(mExternalStylusConnected));
2982 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
2983 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01002984 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07002985 dump.append(INDENT3 "External Stylus State:\n");
2986 dumpStylusState(dump, mExternalStylusState);
2987
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 if (mDeviceMode == DEVICE_MODE_POINTER) {
2989 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
2990 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
2991 mPointerXMovementScale);
2992 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
2993 mPointerYMovementScale);
2994 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
2995 mPointerXZoomScale);
2996 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
2997 mPointerYZoomScale);
2998 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
2999 mPointerGestureMaxSwipeWidth);
3000 }
3001}
3002
3003void TouchInputMapper::configure(nsecs_t when,
3004 const InputReaderConfiguration* config, uint32_t changes) {
3005 InputMapper::configure(when, config, changes);
3006
3007 mConfig = *config;
3008
3009 if (!changes) { // first time only
3010 // Configure basic parameters.
3011 configureParameters();
3012
3013 // Configure common accumulators.
3014 mCursorScrollAccumulator.configure(getDevice());
3015 mTouchButtonAccumulator.configure(getDevice());
3016
3017 // Configure absolute axis information.
3018 configureRawPointerAxes();
3019
3020 // Prepare input device calibration.
3021 parseCalibration();
3022 resolveCalibration();
3023 }
3024
Michael Wright842500e2015-03-13 17:32:02 -07003025 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003026 // Update location calibration to reflect current settings
3027 updateAffineTransformation();
3028 }
3029
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3031 // Update pointer speed.
3032 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3033 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3034 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3035 }
3036
3037 bool resetNeeded = false;
3038 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3039 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003040 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3041 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 // Configure device sources, surface dimensions, orientation and
3043 // scaling factors.
3044 configureSurface(when, &resetNeeded);
3045 }
3046
3047 if (changes && resetNeeded) {
3048 // Send reset, unless this is the first time the device has been configured,
3049 // in which case the reader will call reset itself after all mappers are ready.
3050 getDevice()->notifyReset(when);
3051 }
3052}
3053
Michael Wright842500e2015-03-13 17:32:02 -07003054void TouchInputMapper::resolveExternalStylusPresence() {
3055 Vector<InputDeviceInfo> devices;
3056 mContext->getExternalStylusDevices(devices);
3057 mExternalStylusConnected = !devices.isEmpty();
3058
3059 if (!mExternalStylusConnected) {
3060 resetExternalStylus();
3061 }
3062}
3063
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064void TouchInputMapper::configureParameters() {
3065 // Use the pointer presentation mode for devices that do not support distinct
3066 // multitouch. The spot-based presentation relies on being able to accurately
3067 // locate two or more fingers on the touch pad.
3068 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003069 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070
3071 String8 gestureModeString;
3072 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3073 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003074 if (gestureModeString == "single-touch") {
3075 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3076 } else if (gestureModeString == "multi-touch") {
3077 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 } else if (gestureModeString != "default") {
3079 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3080 }
3081 }
3082
3083 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3084 // The device is a touch screen.
3085 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3086 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3087 // The device is a pointing device like a track pad.
3088 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3089 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3090 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3091 // The device is a cursor device with a touch pad attached.
3092 // By default don't use the touch pad to move the pointer.
3093 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3094 } else {
3095 // The device is a touch pad of unknown purpose.
3096 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3097 }
3098
3099 mParameters.hasButtonUnderPad=
3100 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3101
3102 String8 deviceTypeString;
3103 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3104 deviceTypeString)) {
3105 if (deviceTypeString == "touchScreen") {
3106 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3107 } else if (deviceTypeString == "touchPad") {
3108 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3109 } else if (deviceTypeString == "touchNavigation") {
3110 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3111 } else if (deviceTypeString == "pointer") {
3112 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3113 } else if (deviceTypeString != "default") {
3114 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3115 }
3116 }
3117
3118 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3119 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3120 mParameters.orientationAware);
3121
3122 mParameters.hasAssociatedDisplay = false;
3123 mParameters.associatedDisplayIsExternal = false;
3124 if (mParameters.orientationAware
3125 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3126 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3127 mParameters.hasAssociatedDisplay = true;
3128 mParameters.associatedDisplayIsExternal =
3129 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3130 && getDevice()->isExternal();
3131 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003132
3133 // Initial downs on external touch devices should wake the device.
3134 // Normally we don't do this for internal touch screens to prevent them from waking
3135 // up in your pocket but you can enable it using the input device configuration.
3136 mParameters.wake = getDevice()->isExternal();
3137 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3138 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139}
3140
3141void TouchInputMapper::dumpParameters(String8& dump) {
3142 dump.append(INDENT3 "Parameters:\n");
3143
3144 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003145 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3146 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003148 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3149 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 break;
3151 default:
3152 assert(false);
3153 }
3154
3155 switch (mParameters.deviceType) {
3156 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3157 dump.append(INDENT4 "DeviceType: touchScreen\n");
3158 break;
3159 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3160 dump.append(INDENT4 "DeviceType: touchPad\n");
3161 break;
3162 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3163 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3164 break;
3165 case Parameters::DEVICE_TYPE_POINTER:
3166 dump.append(INDENT4 "DeviceType: pointer\n");
3167 break;
3168 default:
3169 ALOG_ASSERT(false);
3170 }
3171
3172 dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
3173 toString(mParameters.hasAssociatedDisplay),
3174 toString(mParameters.associatedDisplayIsExternal));
3175 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3176 toString(mParameters.orientationAware));
3177}
3178
3179void TouchInputMapper::configureRawPointerAxes() {
3180 mRawPointerAxes.clear();
3181}
3182
3183void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3184 dump.append(INDENT3 "Raw Touch Axes:\n");
3185 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3186 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3187 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3188 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3189 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3190 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3191 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3192 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3193 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3194 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3195 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3196 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3197 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3198}
3199
Michael Wright842500e2015-03-13 17:32:02 -07003200bool TouchInputMapper::hasExternalStylus() const {
3201 return mExternalStylusConnected;
3202}
3203
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3205 int32_t oldDeviceMode = mDeviceMode;
3206
Michael Wright842500e2015-03-13 17:32:02 -07003207 resolveExternalStylusPresence();
3208
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 // Determine device mode.
3210 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3211 && mConfig.pointerGesturesEnabled) {
3212 mSource = AINPUT_SOURCE_MOUSE;
3213 mDeviceMode = DEVICE_MODE_POINTER;
3214 if (hasStylus()) {
3215 mSource |= AINPUT_SOURCE_STYLUS;
3216 }
3217 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3218 && mParameters.hasAssociatedDisplay) {
3219 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3220 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003221 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 mSource |= AINPUT_SOURCE_STYLUS;
3223 }
Michael Wright2f78b682015-06-12 15:25:08 +01003224 if (hasExternalStylus()) {
3225 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3228 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3229 mDeviceMode = DEVICE_MODE_NAVIGATION;
3230 } else {
3231 mSource = AINPUT_SOURCE_TOUCHPAD;
3232 mDeviceMode = DEVICE_MODE_UNSCALED;
3233 }
3234
3235 // Ensure we have valid X and Y axes.
3236 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3237 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3238 "The device will be inoperable.", getDeviceName().string());
3239 mDeviceMode = DEVICE_MODE_DISABLED;
3240 return;
3241 }
3242
3243 // Raw width and height in the natural orientation.
3244 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3245 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3246
3247 // Get associated display dimensions.
3248 DisplayViewport newViewport;
3249 if (mParameters.hasAssociatedDisplay) {
3250 if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
3251 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3252 "display. The device will be inoperable until the display size "
3253 "becomes available.",
3254 getDeviceName().string());
3255 mDeviceMode = DEVICE_MODE_DISABLED;
3256 return;
3257 }
3258 } else {
3259 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3260 }
3261 bool viewportChanged = mViewport != newViewport;
3262 if (viewportChanged) {
3263 mViewport = newViewport;
3264
3265 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3266 // Convert rotated viewport to natural surface coordinates.
3267 int32_t naturalLogicalWidth, naturalLogicalHeight;
3268 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3269 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3270 int32_t naturalDeviceWidth, naturalDeviceHeight;
3271 switch (mViewport.orientation) {
3272 case DISPLAY_ORIENTATION_90:
3273 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3274 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3275 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3276 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3277 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3278 naturalPhysicalTop = mViewport.physicalLeft;
3279 naturalDeviceWidth = mViewport.deviceHeight;
3280 naturalDeviceHeight = mViewport.deviceWidth;
3281 break;
3282 case DISPLAY_ORIENTATION_180:
3283 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3284 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3285 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3286 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3287 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3288 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3289 naturalDeviceWidth = mViewport.deviceWidth;
3290 naturalDeviceHeight = mViewport.deviceHeight;
3291 break;
3292 case DISPLAY_ORIENTATION_270:
3293 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3294 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3295 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3296 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3297 naturalPhysicalLeft = mViewport.physicalTop;
3298 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3299 naturalDeviceWidth = mViewport.deviceHeight;
3300 naturalDeviceHeight = mViewport.deviceWidth;
3301 break;
3302 case DISPLAY_ORIENTATION_0:
3303 default:
3304 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3305 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3306 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3307 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3308 naturalPhysicalLeft = mViewport.physicalLeft;
3309 naturalPhysicalTop = mViewport.physicalTop;
3310 naturalDeviceWidth = mViewport.deviceWidth;
3311 naturalDeviceHeight = mViewport.deviceHeight;
3312 break;
3313 }
3314
3315 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3316 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3317 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3318 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3319
3320 mSurfaceOrientation = mParameters.orientationAware ?
3321 mViewport.orientation : DISPLAY_ORIENTATION_0;
3322 } else {
3323 mSurfaceWidth = rawWidth;
3324 mSurfaceHeight = rawHeight;
3325 mSurfaceLeft = 0;
3326 mSurfaceTop = 0;
3327 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3328 }
3329 }
3330
3331 // If moving between pointer modes, need to reset some state.
3332 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3333 if (deviceModeChanged) {
3334 mOrientedRanges.clear();
3335 }
3336
3337 // Create pointer controller if needed.
3338 if (mDeviceMode == DEVICE_MODE_POINTER ||
3339 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3340 if (mPointerController == NULL) {
3341 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3342 }
3343 } else {
3344 mPointerController.clear();
3345 }
3346
3347 if (viewportChanged || deviceModeChanged) {
3348 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3349 "display id %d",
3350 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3351 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3352
3353 // Configure X and Y factors.
3354 mXScale = float(mSurfaceWidth) / rawWidth;
3355 mYScale = float(mSurfaceHeight) / rawHeight;
3356 mXTranslate = -mSurfaceLeft;
3357 mYTranslate = -mSurfaceTop;
3358 mXPrecision = 1.0f / mXScale;
3359 mYPrecision = 1.0f / mYScale;
3360
3361 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3362 mOrientedRanges.x.source = mSource;
3363 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3364 mOrientedRanges.y.source = mSource;
3365
3366 configureVirtualKeys();
3367
3368 // Scale factor for terms that are not oriented in a particular axis.
3369 // If the pixels are square then xScale == yScale otherwise we fake it
3370 // by choosing an average.
3371 mGeometricScale = avg(mXScale, mYScale);
3372
3373 // Size of diagonal axis.
3374 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3375
3376 // Size factors.
3377 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3378 if (mRawPointerAxes.touchMajor.valid
3379 && mRawPointerAxes.touchMajor.maxValue != 0) {
3380 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3381 } else if (mRawPointerAxes.toolMajor.valid
3382 && mRawPointerAxes.toolMajor.maxValue != 0) {
3383 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3384 } else {
3385 mSizeScale = 0.0f;
3386 }
3387
3388 mOrientedRanges.haveTouchSize = true;
3389 mOrientedRanges.haveToolSize = true;
3390 mOrientedRanges.haveSize = true;
3391
3392 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3393 mOrientedRanges.touchMajor.source = mSource;
3394 mOrientedRanges.touchMajor.min = 0;
3395 mOrientedRanges.touchMajor.max = diagonalSize;
3396 mOrientedRanges.touchMajor.flat = 0;
3397 mOrientedRanges.touchMajor.fuzz = 0;
3398 mOrientedRanges.touchMajor.resolution = 0;
3399
3400 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3401 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3402
3403 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3404 mOrientedRanges.toolMajor.source = mSource;
3405 mOrientedRanges.toolMajor.min = 0;
3406 mOrientedRanges.toolMajor.max = diagonalSize;
3407 mOrientedRanges.toolMajor.flat = 0;
3408 mOrientedRanges.toolMajor.fuzz = 0;
3409 mOrientedRanges.toolMajor.resolution = 0;
3410
3411 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3412 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3413
3414 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3415 mOrientedRanges.size.source = mSource;
3416 mOrientedRanges.size.min = 0;
3417 mOrientedRanges.size.max = 1.0;
3418 mOrientedRanges.size.flat = 0;
3419 mOrientedRanges.size.fuzz = 0;
3420 mOrientedRanges.size.resolution = 0;
3421 } else {
3422 mSizeScale = 0.0f;
3423 }
3424
3425 // Pressure factors.
3426 mPressureScale = 0;
3427 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3428 || mCalibration.pressureCalibration
3429 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3430 if (mCalibration.havePressureScale) {
3431 mPressureScale = mCalibration.pressureScale;
3432 } else if (mRawPointerAxes.pressure.valid
3433 && mRawPointerAxes.pressure.maxValue != 0) {
3434 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3435 }
3436 }
3437
3438 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3439 mOrientedRanges.pressure.source = mSource;
3440 mOrientedRanges.pressure.min = 0;
3441 mOrientedRanges.pressure.max = 1.0;
3442 mOrientedRanges.pressure.flat = 0;
3443 mOrientedRanges.pressure.fuzz = 0;
3444 mOrientedRanges.pressure.resolution = 0;
3445
3446 // Tilt
3447 mTiltXCenter = 0;
3448 mTiltXScale = 0;
3449 mTiltYCenter = 0;
3450 mTiltYScale = 0;
3451 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3452 if (mHaveTilt) {
3453 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3454 mRawPointerAxes.tiltX.maxValue);
3455 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3456 mRawPointerAxes.tiltY.maxValue);
3457 mTiltXScale = M_PI / 180;
3458 mTiltYScale = M_PI / 180;
3459
3460 mOrientedRanges.haveTilt = true;
3461
3462 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3463 mOrientedRanges.tilt.source = mSource;
3464 mOrientedRanges.tilt.min = 0;
3465 mOrientedRanges.tilt.max = M_PI_2;
3466 mOrientedRanges.tilt.flat = 0;
3467 mOrientedRanges.tilt.fuzz = 0;
3468 mOrientedRanges.tilt.resolution = 0;
3469 }
3470
3471 // Orientation
3472 mOrientationScale = 0;
3473 if (mHaveTilt) {
3474 mOrientedRanges.haveOrientation = true;
3475
3476 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3477 mOrientedRanges.orientation.source = mSource;
3478 mOrientedRanges.orientation.min = -M_PI;
3479 mOrientedRanges.orientation.max = M_PI;
3480 mOrientedRanges.orientation.flat = 0;
3481 mOrientedRanges.orientation.fuzz = 0;
3482 mOrientedRanges.orientation.resolution = 0;
3483 } else if (mCalibration.orientationCalibration !=
3484 Calibration::ORIENTATION_CALIBRATION_NONE) {
3485 if (mCalibration.orientationCalibration
3486 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3487 if (mRawPointerAxes.orientation.valid) {
3488 if (mRawPointerAxes.orientation.maxValue > 0) {
3489 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3490 } else if (mRawPointerAxes.orientation.minValue < 0) {
3491 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3492 } else {
3493 mOrientationScale = 0;
3494 }
3495 }
3496 }
3497
3498 mOrientedRanges.haveOrientation = true;
3499
3500 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3501 mOrientedRanges.orientation.source = mSource;
3502 mOrientedRanges.orientation.min = -M_PI_2;
3503 mOrientedRanges.orientation.max = M_PI_2;
3504 mOrientedRanges.orientation.flat = 0;
3505 mOrientedRanges.orientation.fuzz = 0;
3506 mOrientedRanges.orientation.resolution = 0;
3507 }
3508
3509 // Distance
3510 mDistanceScale = 0;
3511 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3512 if (mCalibration.distanceCalibration
3513 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3514 if (mCalibration.haveDistanceScale) {
3515 mDistanceScale = mCalibration.distanceScale;
3516 } else {
3517 mDistanceScale = 1.0f;
3518 }
3519 }
3520
3521 mOrientedRanges.haveDistance = true;
3522
3523 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3524 mOrientedRanges.distance.source = mSource;
3525 mOrientedRanges.distance.min =
3526 mRawPointerAxes.distance.minValue * mDistanceScale;
3527 mOrientedRanges.distance.max =
3528 mRawPointerAxes.distance.maxValue * mDistanceScale;
3529 mOrientedRanges.distance.flat = 0;
3530 mOrientedRanges.distance.fuzz =
3531 mRawPointerAxes.distance.fuzz * mDistanceScale;
3532 mOrientedRanges.distance.resolution = 0;
3533 }
3534
3535 // Compute oriented precision, scales and ranges.
3536 // Note that the maximum value reported is an inclusive maximum value so it is one
3537 // unit less than the total width or height of surface.
3538 switch (mSurfaceOrientation) {
3539 case DISPLAY_ORIENTATION_90:
3540 case DISPLAY_ORIENTATION_270:
3541 mOrientedXPrecision = mYPrecision;
3542 mOrientedYPrecision = mXPrecision;
3543
3544 mOrientedRanges.x.min = mYTranslate;
3545 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3546 mOrientedRanges.x.flat = 0;
3547 mOrientedRanges.x.fuzz = 0;
3548 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3549
3550 mOrientedRanges.y.min = mXTranslate;
3551 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3552 mOrientedRanges.y.flat = 0;
3553 mOrientedRanges.y.fuzz = 0;
3554 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3555 break;
3556
3557 default:
3558 mOrientedXPrecision = mXPrecision;
3559 mOrientedYPrecision = mYPrecision;
3560
3561 mOrientedRanges.x.min = mXTranslate;
3562 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3563 mOrientedRanges.x.flat = 0;
3564 mOrientedRanges.x.fuzz = 0;
3565 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3566
3567 mOrientedRanges.y.min = mYTranslate;
3568 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3569 mOrientedRanges.y.flat = 0;
3570 mOrientedRanges.y.fuzz = 0;
3571 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3572 break;
3573 }
3574
Jason Gerecke71b16e82014-03-10 09:47:59 -07003575 // Location
3576 updateAffineTransformation();
3577
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 if (mDeviceMode == DEVICE_MODE_POINTER) {
3579 // Compute pointer gesture detection parameters.
3580 float rawDiagonal = hypotf(rawWidth, rawHeight);
3581 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3582
3583 // Scale movements such that one whole swipe of the touch pad covers a
3584 // given area relative to the diagonal size of the display when no acceleration
3585 // is applied.
3586 // Assume that the touch pad has a square aspect ratio such that movements in
3587 // X and Y of the same number of raw units cover the same physical distance.
3588 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3589 * displayDiagonal / rawDiagonal;
3590 mPointerYMovementScale = mPointerXMovementScale;
3591
3592 // Scale zooms to cover a smaller range of the display than movements do.
3593 // This value determines the area around the pointer that is affected by freeform
3594 // pointer gestures.
3595 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3596 * displayDiagonal / rawDiagonal;
3597 mPointerYZoomScale = mPointerXZoomScale;
3598
3599 // Max width between pointers to detect a swipe gesture is more than some fraction
3600 // of the diagonal axis of the touch pad. Touches that are wider than this are
3601 // translated into freeform gestures.
3602 mPointerGestureMaxSwipeWidth =
3603 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3604
3605 // Abort current pointer usages because the state has changed.
3606 abortPointerUsage(when, 0 /*policyFlags*/);
3607 }
3608
3609 // Inform the dispatcher about the changes.
3610 *outResetNeeded = true;
3611 bumpGeneration();
3612 }
3613}
3614
3615void TouchInputMapper::dumpSurface(String8& dump) {
3616 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3617 "logicalFrame=[%d, %d, %d, %d], "
3618 "physicalFrame=[%d, %d, %d, %d], "
3619 "deviceSize=[%d, %d]\n",
3620 mViewport.displayId, mViewport.orientation,
3621 mViewport.logicalLeft, mViewport.logicalTop,
3622 mViewport.logicalRight, mViewport.logicalBottom,
3623 mViewport.physicalLeft, mViewport.physicalTop,
3624 mViewport.physicalRight, mViewport.physicalBottom,
3625 mViewport.deviceWidth, mViewport.deviceHeight);
3626
3627 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3628 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3629 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3630 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3631 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3632}
3633
3634void TouchInputMapper::configureVirtualKeys() {
3635 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3636 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3637
3638 mVirtualKeys.clear();
3639
3640 if (virtualKeyDefinitions.size() == 0) {
3641 return;
3642 }
3643
3644 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3645
3646 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3647 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3648 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3649 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3650
3651 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3652 const VirtualKeyDefinition& virtualKeyDefinition =
3653 virtualKeyDefinitions[i];
3654
3655 mVirtualKeys.add();
3656 VirtualKey& virtualKey = mVirtualKeys.editTop();
3657
3658 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3659 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003660 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003662 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3663 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3665 virtualKey.scanCode);
3666 mVirtualKeys.pop(); // drop the key
3667 continue;
3668 }
3669
3670 virtualKey.keyCode = keyCode;
3671 virtualKey.flags = flags;
3672
3673 // convert the key definition's display coordinates into touch coordinates for a hit box
3674 int32_t halfWidth = virtualKeyDefinition.width / 2;
3675 int32_t halfHeight = virtualKeyDefinition.height / 2;
3676
3677 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3678 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3679 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3680 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3681 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3682 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3683 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3684 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3685 }
3686}
3687
3688void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3689 if (!mVirtualKeys.isEmpty()) {
3690 dump.append(INDENT3 "Virtual Keys:\n");
3691
3692 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3693 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003694 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3696 i, virtualKey.scanCode, virtualKey.keyCode,
3697 virtualKey.hitLeft, virtualKey.hitRight,
3698 virtualKey.hitTop, virtualKey.hitBottom);
3699 }
3700 }
3701}
3702
3703void TouchInputMapper::parseCalibration() {
3704 const PropertyMap& in = getDevice()->getConfiguration();
3705 Calibration& out = mCalibration;
3706
3707 // Size
3708 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3709 String8 sizeCalibrationString;
3710 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3711 if (sizeCalibrationString == "none") {
3712 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3713 } else if (sizeCalibrationString == "geometric") {
3714 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3715 } else if (sizeCalibrationString == "diameter") {
3716 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3717 } else if (sizeCalibrationString == "box") {
3718 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3719 } else if (sizeCalibrationString == "area") {
3720 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3721 } else if (sizeCalibrationString != "default") {
3722 ALOGW("Invalid value for touch.size.calibration: '%s'",
3723 sizeCalibrationString.string());
3724 }
3725 }
3726
3727 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3728 out.sizeScale);
3729 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3730 out.sizeBias);
3731 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3732 out.sizeIsSummed);
3733
3734 // Pressure
3735 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3736 String8 pressureCalibrationString;
3737 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3738 if (pressureCalibrationString == "none") {
3739 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3740 } else if (pressureCalibrationString == "physical") {
3741 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3742 } else if (pressureCalibrationString == "amplitude") {
3743 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3744 } else if (pressureCalibrationString != "default") {
3745 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3746 pressureCalibrationString.string());
3747 }
3748 }
3749
3750 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3751 out.pressureScale);
3752
3753 // Orientation
3754 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3755 String8 orientationCalibrationString;
3756 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3757 if (orientationCalibrationString == "none") {
3758 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3759 } else if (orientationCalibrationString == "interpolated") {
3760 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3761 } else if (orientationCalibrationString == "vector") {
3762 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3763 } else if (orientationCalibrationString != "default") {
3764 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3765 orientationCalibrationString.string());
3766 }
3767 }
3768
3769 // Distance
3770 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3771 String8 distanceCalibrationString;
3772 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3773 if (distanceCalibrationString == "none") {
3774 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3775 } else if (distanceCalibrationString == "scaled") {
3776 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3777 } else if (distanceCalibrationString != "default") {
3778 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3779 distanceCalibrationString.string());
3780 }
3781 }
3782
3783 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3784 out.distanceScale);
3785
3786 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3787 String8 coverageCalibrationString;
3788 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3789 if (coverageCalibrationString == "none") {
3790 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3791 } else if (coverageCalibrationString == "box") {
3792 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3793 } else if (coverageCalibrationString != "default") {
3794 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3795 coverageCalibrationString.string());
3796 }
3797 }
3798}
3799
3800void TouchInputMapper::resolveCalibration() {
3801 // Size
3802 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3803 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3804 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3805 }
3806 } else {
3807 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3808 }
3809
3810 // Pressure
3811 if (mRawPointerAxes.pressure.valid) {
3812 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3813 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3814 }
3815 } else {
3816 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3817 }
3818
3819 // Orientation
3820 if (mRawPointerAxes.orientation.valid) {
3821 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3822 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3823 }
3824 } else {
3825 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3826 }
3827
3828 // Distance
3829 if (mRawPointerAxes.distance.valid) {
3830 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3831 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3832 }
3833 } else {
3834 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3835 }
3836
3837 // Coverage
3838 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3839 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3840 }
3841}
3842
3843void TouchInputMapper::dumpCalibration(String8& dump) {
3844 dump.append(INDENT3 "Calibration:\n");
3845
3846 // Size
3847 switch (mCalibration.sizeCalibration) {
3848 case Calibration::SIZE_CALIBRATION_NONE:
3849 dump.append(INDENT4 "touch.size.calibration: none\n");
3850 break;
3851 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3852 dump.append(INDENT4 "touch.size.calibration: geometric\n");
3853 break;
3854 case Calibration::SIZE_CALIBRATION_DIAMETER:
3855 dump.append(INDENT4 "touch.size.calibration: diameter\n");
3856 break;
3857 case Calibration::SIZE_CALIBRATION_BOX:
3858 dump.append(INDENT4 "touch.size.calibration: box\n");
3859 break;
3860 case Calibration::SIZE_CALIBRATION_AREA:
3861 dump.append(INDENT4 "touch.size.calibration: area\n");
3862 break;
3863 default:
3864 ALOG_ASSERT(false);
3865 }
3866
3867 if (mCalibration.haveSizeScale) {
3868 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3869 mCalibration.sizeScale);
3870 }
3871
3872 if (mCalibration.haveSizeBias) {
3873 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3874 mCalibration.sizeBias);
3875 }
3876
3877 if (mCalibration.haveSizeIsSummed) {
3878 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3879 toString(mCalibration.sizeIsSummed));
3880 }
3881
3882 // Pressure
3883 switch (mCalibration.pressureCalibration) {
3884 case Calibration::PRESSURE_CALIBRATION_NONE:
3885 dump.append(INDENT4 "touch.pressure.calibration: none\n");
3886 break;
3887 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3888 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3889 break;
3890 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3891 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3892 break;
3893 default:
3894 ALOG_ASSERT(false);
3895 }
3896
3897 if (mCalibration.havePressureScale) {
3898 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3899 mCalibration.pressureScale);
3900 }
3901
3902 // Orientation
3903 switch (mCalibration.orientationCalibration) {
3904 case Calibration::ORIENTATION_CALIBRATION_NONE:
3905 dump.append(INDENT4 "touch.orientation.calibration: none\n");
3906 break;
3907 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3908 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3909 break;
3910 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3911 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3912 break;
3913 default:
3914 ALOG_ASSERT(false);
3915 }
3916
3917 // Distance
3918 switch (mCalibration.distanceCalibration) {
3919 case Calibration::DISTANCE_CALIBRATION_NONE:
3920 dump.append(INDENT4 "touch.distance.calibration: none\n");
3921 break;
3922 case Calibration::DISTANCE_CALIBRATION_SCALED:
3923 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3924 break;
3925 default:
3926 ALOG_ASSERT(false);
3927 }
3928
3929 if (mCalibration.haveDistanceScale) {
3930 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
3931 mCalibration.distanceScale);
3932 }
3933
3934 switch (mCalibration.coverageCalibration) {
3935 case Calibration::COVERAGE_CALIBRATION_NONE:
3936 dump.append(INDENT4 "touch.coverage.calibration: none\n");
3937 break;
3938 case Calibration::COVERAGE_CALIBRATION_BOX:
3939 dump.append(INDENT4 "touch.coverage.calibration: box\n");
3940 break;
3941 default:
3942 ALOG_ASSERT(false);
3943 }
3944}
3945
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003946void TouchInputMapper::dumpAffineTransformation(String8& dump) {
3947 dump.append(INDENT3 "Affine Transformation:\n");
3948
3949 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
3950 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
3951 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
3952 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
3953 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
3954 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
3955}
3956
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003957void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07003958 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
3959 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003960}
3961
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962void TouchInputMapper::reset(nsecs_t when) {
3963 mCursorButtonAccumulator.reset(getDevice());
3964 mCursorScrollAccumulator.reset(getDevice());
3965 mTouchButtonAccumulator.reset(getDevice());
3966
3967 mPointerVelocityControl.reset();
3968 mWheelXVelocityControl.reset();
3969 mWheelYVelocityControl.reset();
3970
Michael Wright842500e2015-03-13 17:32:02 -07003971 mRawStatesPending.clear();
3972 mCurrentRawState.clear();
3973 mCurrentCookedState.clear();
3974 mLastRawState.clear();
3975 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 mPointerUsage = POINTER_USAGE_NONE;
3977 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07003978 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01003979 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 mDownTime = 0;
3981
3982 mCurrentVirtualKey.down = false;
3983
3984 mPointerGesture.reset();
3985 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07003986 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
3988 if (mPointerController != NULL) {
3989 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3990 mPointerController->clearSpots();
3991 }
3992
3993 InputMapper::reset(when);
3994}
3995
Michael Wright842500e2015-03-13 17:32:02 -07003996void TouchInputMapper::resetExternalStylus() {
3997 mExternalStylusState.clear();
3998 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01003999 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004000 mExternalStylusDataPending = false;
4001}
4002
Michael Wright43fd19f2015-04-21 19:02:58 +01004003void TouchInputMapper::clearStylusDataPendingFlags() {
4004 mExternalStylusDataPending = false;
4005 mExternalStylusFusionTimeout = LLONG_MAX;
4006}
4007
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008void TouchInputMapper::process(const RawEvent* rawEvent) {
4009 mCursorButtonAccumulator.process(rawEvent);
4010 mCursorScrollAccumulator.process(rawEvent);
4011 mTouchButtonAccumulator.process(rawEvent);
4012
4013 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4014 sync(rawEvent->when);
4015 }
4016}
4017
4018void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004019 const RawState* last = mRawStatesPending.isEmpty() ?
4020 &mCurrentRawState : &mRawStatesPending.top();
4021
4022 // Push a new state.
4023 mRawStatesPending.push();
4024 RawState* next = &mRawStatesPending.editTop();
4025 next->clear();
4026 next->when = when;
4027
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004029 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 | mCursorButtonAccumulator.getButtonState();
4031
Michael Wright842500e2015-03-13 17:32:02 -07004032 // Sync scroll
4033 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4034 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 mCursorScrollAccumulator.finishSync();
4036
Michael Wright842500e2015-03-13 17:32:02 -07004037 // Sync touch
4038 syncTouch(when, next);
4039
4040 // Assign pointer ids.
4041 if (!mHavePointerIds) {
4042 assignPointerIds(last, next);
4043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
4045#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004046 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4047 "hovering ids 0x%08x -> 0x%08x",
4048 last->rawPointerData.pointerCount,
4049 next->rawPointerData.pointerCount,
4050 last->rawPointerData.touchingIdBits.value,
4051 next->rawPointerData.touchingIdBits.value,
4052 last->rawPointerData.hoveringIdBits.value,
4053 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054#endif
4055
Michael Wright842500e2015-03-13 17:32:02 -07004056 processRawTouches(false /*timeout*/);
4057}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
Michael Wright842500e2015-03-13 17:32:02 -07004059void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4061 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004062 mCurrentRawState.clear();
4063 mRawStatesPending.clear();
4064 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 }
4066
Michael Wright842500e2015-03-13 17:32:02 -07004067 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4068 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4069 // touching the current state will only observe the events that have been dispatched to the
4070 // rest of the pipeline.
4071 const size_t N = mRawStatesPending.size();
4072 size_t count;
4073 for(count = 0; count < N; count++) {
4074 const RawState& next = mRawStatesPending[count];
4075
4076 // A failure to assign the stylus id means that we're waiting on stylus data
4077 // and so should defer the rest of the pipeline.
4078 if (assignExternalStylusId(next, timeout)) {
4079 break;
4080 }
4081
4082 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004083 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004084 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004085 if (mCurrentRawState.when < mLastRawState.when) {
4086 mCurrentRawState.when = mLastRawState.when;
4087 }
Michael Wright842500e2015-03-13 17:32:02 -07004088 cookAndDispatch(mCurrentRawState.when);
4089 }
4090 if (count != 0) {
4091 mRawStatesPending.removeItemsAt(0, count);
4092 }
4093
Michael Wright842500e2015-03-13 17:32:02 -07004094 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004095 if (timeout) {
4096 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4097 clearStylusDataPendingFlags();
4098 mCurrentRawState.copyFrom(mLastRawState);
4099#if DEBUG_STYLUS_FUSION
4100 ALOGD("Timeout expired, synthesizing event with new stylus data");
4101#endif
4102 cookAndDispatch(when);
4103 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4104 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4105 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4106 }
Michael Wright842500e2015-03-13 17:32:02 -07004107 }
4108}
4109
4110void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4111 // Always start with a clean state.
4112 mCurrentCookedState.clear();
4113
4114 // Apply stylus buttons to current raw state.
4115 applyExternalStylusButtonState(when);
4116
4117 // Handle policy on initial down or hover events.
4118 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4119 && mCurrentRawState.rawPointerData.pointerCount != 0;
4120
4121 uint32_t policyFlags = 0;
4122 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4123 if (initialDown || buttonsPressed) {
4124 // If this is a touch screen, hide the pointer on an initial down.
4125 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4126 getContext()->fadePointer();
4127 }
4128
4129 if (mParameters.wake) {
4130 policyFlags |= POLICY_FLAG_WAKE;
4131 }
4132 }
4133
4134 // Consume raw off-screen touches before cooking pointer data.
4135 // If touches are consumed, subsequent code will not receive any pointer data.
4136 if (consumeRawTouches(when, policyFlags)) {
4137 mCurrentRawState.rawPointerData.clear();
4138 }
4139
4140 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4141 // with cooked pointer data that has the same ids and indices as the raw data.
4142 // The following code can use either the raw or cooked data, as needed.
4143 cookPointerData();
4144
4145 // Apply stylus pressure to current cooked state.
4146 applyExternalStylusTouchState(when);
4147
4148 // Synthesize key down from raw buttons if needed.
4149 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004150 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004151
4152 // Dispatch the touches either directly or by translation through a pointer on screen.
4153 if (mDeviceMode == DEVICE_MODE_POINTER) {
4154 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4155 !idBits.isEmpty(); ) {
4156 uint32_t id = idBits.clearFirstMarkedBit();
4157 const RawPointerData::Pointer& pointer =
4158 mCurrentRawState.rawPointerData.pointerForId(id);
4159 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4160 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4161 mCurrentCookedState.stylusIdBits.markBit(id);
4162 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4163 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4164 mCurrentCookedState.fingerIdBits.markBit(id);
4165 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4166 mCurrentCookedState.mouseIdBits.markBit(id);
4167 }
4168 }
4169 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4170 !idBits.isEmpty(); ) {
4171 uint32_t id = idBits.clearFirstMarkedBit();
4172 const RawPointerData::Pointer& pointer =
4173 mCurrentRawState.rawPointerData.pointerForId(id);
4174 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4175 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4176 mCurrentCookedState.stylusIdBits.markBit(id);
4177 }
4178 }
4179
4180 // Stylus takes precedence over all tools, then mouse, then finger.
4181 PointerUsage pointerUsage = mPointerUsage;
4182 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4183 mCurrentCookedState.mouseIdBits.clear();
4184 mCurrentCookedState.fingerIdBits.clear();
4185 pointerUsage = POINTER_USAGE_STYLUS;
4186 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4187 mCurrentCookedState.fingerIdBits.clear();
4188 pointerUsage = POINTER_USAGE_MOUSE;
4189 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4190 isPointerDown(mCurrentRawState.buttonState)) {
4191 pointerUsage = POINTER_USAGE_GESTURES;
4192 }
4193
4194 dispatchPointerUsage(when, policyFlags, pointerUsage);
4195 } else {
4196 if (mDeviceMode == DEVICE_MODE_DIRECT
4197 && mConfig.showTouches && mPointerController != NULL) {
4198 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4199 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4200
4201 mPointerController->setButtonState(mCurrentRawState.buttonState);
4202 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4203 mCurrentCookedState.cookedPointerData.idToIndex,
4204 mCurrentCookedState.cookedPointerData.touchingIdBits);
4205 }
4206
Michael Wright8e812822015-06-22 16:18:21 +01004207 if (!mCurrentMotionAborted) {
4208 dispatchButtonRelease(when, policyFlags);
4209 dispatchHoverExit(when, policyFlags);
4210 dispatchTouches(when, policyFlags);
4211 dispatchHoverEnterAndMove(when, policyFlags);
4212 dispatchButtonPress(when, policyFlags);
4213 }
4214
4215 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4216 mCurrentMotionAborted = false;
4217 }
Michael Wright842500e2015-03-13 17:32:02 -07004218 }
4219
4220 // Synthesize key up from raw buttons if needed.
4221 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004222 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223
4224 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004225 mCurrentRawState.rawVScroll = 0;
4226 mCurrentRawState.rawHScroll = 0;
4227
4228 // Copy current touch to last touch in preparation for the next cycle.
4229 mLastRawState.copyFrom(mCurrentRawState);
4230 mLastCookedState.copyFrom(mCurrentCookedState);
4231}
4232
4233void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004234 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004235 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4236 }
4237}
4238
4239void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004240 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4241 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004242
Michael Wright53dca3a2015-04-23 17:39:53 +01004243 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4244 float pressure = mExternalStylusState.pressure;
4245 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4246 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4247 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4248 }
4249 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4250 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4251
4252 PointerProperties& properties =
4253 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004254 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4255 properties.toolType = mExternalStylusState.toolType;
4256 }
4257 }
4258}
4259
4260bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4261 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4262 return false;
4263 }
4264
4265 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4266 && state.rawPointerData.pointerCount != 0;
4267 if (initialDown) {
4268 if (mExternalStylusState.pressure != 0.0f) {
4269#if DEBUG_STYLUS_FUSION
4270 ALOGD("Have both stylus and touch data, beginning fusion");
4271#endif
4272 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4273 } else if (timeout) {
4274#if DEBUG_STYLUS_FUSION
4275 ALOGD("Timeout expired, assuming touch is not a stylus.");
4276#endif
4277 resetExternalStylus();
4278 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004279 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4280 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004281 }
4282#if DEBUG_STYLUS_FUSION
4283 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004284 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004285#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004286 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004287 return true;
4288 }
4289 }
4290
4291 // Check if the stylus pointer has gone up.
4292 if (mExternalStylusId != -1 &&
4293 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4294#if DEBUG_STYLUS_FUSION
4295 ALOGD("Stylus pointer is going up");
4296#endif
4297 mExternalStylusId = -1;
4298 }
4299
4300 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301}
4302
4303void TouchInputMapper::timeoutExpired(nsecs_t when) {
4304 if (mDeviceMode == DEVICE_MODE_POINTER) {
4305 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4306 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4307 }
Michael Wright842500e2015-03-13 17:32:02 -07004308 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004309 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004310 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004311 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4312 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004313 }
4314 }
4315}
4316
4317void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004318 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004319 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004320 // We're either in the middle of a fused stream of data or we're waiting on data before
4321 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4322 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004323 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004324 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 }
4326}
4327
4328bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4329 // Check for release of a virtual key.
4330 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004331 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 // Pointer went up while virtual key was down.
4333 mCurrentVirtualKey.down = false;
4334 if (!mCurrentVirtualKey.ignored) {
4335#if DEBUG_VIRTUAL_KEYS
4336 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4337 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4338#endif
4339 dispatchVirtualKey(when, policyFlags,
4340 AKEY_EVENT_ACTION_UP,
4341 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4342 }
4343 return true;
4344 }
4345
Michael Wright842500e2015-03-13 17:32:02 -07004346 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4347 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4348 const RawPointerData::Pointer& pointer =
4349 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4351 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4352 // Pointer is still within the space of the virtual key.
4353 return true;
4354 }
4355 }
4356
4357 // Pointer left virtual key area or another pointer also went down.
4358 // Send key cancellation but do not consume the touch yet.
4359 // This is useful when the user swipes through from the virtual key area
4360 // into the main display surface.
4361 mCurrentVirtualKey.down = false;
4362 if (!mCurrentVirtualKey.ignored) {
4363#if DEBUG_VIRTUAL_KEYS
4364 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4365 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4366#endif
4367 dispatchVirtualKey(when, policyFlags,
4368 AKEY_EVENT_ACTION_UP,
4369 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4370 | AKEY_EVENT_FLAG_CANCELED);
4371 }
4372 }
4373
Michael Wright842500e2015-03-13 17:32:02 -07004374 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4375 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004377 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4378 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4380 // If exactly one pointer went down, check for virtual key hit.
4381 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004382 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4384 if (virtualKey) {
4385 mCurrentVirtualKey.down = true;
4386 mCurrentVirtualKey.downTime = when;
4387 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4388 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4389 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4390 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4391
4392 if (!mCurrentVirtualKey.ignored) {
4393#if DEBUG_VIRTUAL_KEYS
4394 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4395 mCurrentVirtualKey.keyCode,
4396 mCurrentVirtualKey.scanCode);
4397#endif
4398 dispatchVirtualKey(when, policyFlags,
4399 AKEY_EVENT_ACTION_DOWN,
4400 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4401 }
4402 }
4403 }
4404 return true;
4405 }
4406 }
4407
4408 // Disable all virtual key touches that happen within a short time interval of the
4409 // most recent touch within the screen area. The idea is to filter out stray
4410 // virtual key presses when interacting with the touch screen.
4411 //
4412 // Problems we're trying to solve:
4413 //
4414 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4415 // virtual key area that is implemented by a separate touch panel and accidentally
4416 // triggers a virtual key.
4417 //
4418 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4419 // area and accidentally triggers a virtual key. This often happens when virtual keys
4420 // are layed out below the screen near to where the on screen keyboard's space bar
4421 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004422 if (mConfig.virtualKeyQuietTime > 0 &&
4423 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4425 }
4426 return false;
4427}
4428
4429void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4430 int32_t keyEventAction, int32_t keyEventFlags) {
4431 int32_t keyCode = mCurrentVirtualKey.keyCode;
4432 int32_t scanCode = mCurrentVirtualKey.scanCode;
4433 nsecs_t downTime = mCurrentVirtualKey.downTime;
4434 int32_t metaState = mContext->getGlobalMetaState();
4435 policyFlags |= POLICY_FLAG_VIRTUAL;
4436
4437 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4438 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4439 getListener()->notifyKey(&args);
4440}
4441
Michael Wright8e812822015-06-22 16:18:21 +01004442void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4443 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4444 if (!currentIdBits.isEmpty()) {
4445 int32_t metaState = getContext()->getGlobalMetaState();
4446 int32_t buttonState = mCurrentCookedState.buttonState;
4447 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4448 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4449 mCurrentCookedState.cookedPointerData.pointerProperties,
4450 mCurrentCookedState.cookedPointerData.pointerCoords,
4451 mCurrentCookedState.cookedPointerData.idToIndex,
4452 currentIdBits, -1,
4453 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4454 mCurrentMotionAborted = true;
4455 }
4456}
4457
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004459 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4460 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004462 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463
4464 if (currentIdBits == lastIdBits) {
4465 if (!currentIdBits.isEmpty()) {
4466 // No pointer id changes so this is a move event.
4467 // The listener takes care of batching moves so we don't have to deal with that here.
4468 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004469 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004471 mCurrentCookedState.cookedPointerData.pointerProperties,
4472 mCurrentCookedState.cookedPointerData.pointerCoords,
4473 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 currentIdBits, -1,
4475 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4476 }
4477 } else {
4478 // There may be pointers going up and pointers going down and pointers moving
4479 // all at the same time.
4480 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4481 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4482 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4483 BitSet32 dispatchedIdBits(lastIdBits.value);
4484
4485 // Update last coordinates of pointers that have moved so that we observe the new
4486 // pointer positions at the same time as other pointers that have just gone up.
4487 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004488 mCurrentCookedState.cookedPointerData.pointerProperties,
4489 mCurrentCookedState.cookedPointerData.pointerCoords,
4490 mCurrentCookedState.cookedPointerData.idToIndex,
4491 mLastCookedState.cookedPointerData.pointerProperties,
4492 mLastCookedState.cookedPointerData.pointerCoords,
4493 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004495 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 moveNeeded = true;
4497 }
4498
4499 // Dispatch pointer up events.
4500 while (!upIdBits.isEmpty()) {
4501 uint32_t upId = upIdBits.clearFirstMarkedBit();
4502
4503 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004504 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004505 mLastCookedState.cookedPointerData.pointerProperties,
4506 mLastCookedState.cookedPointerData.pointerCoords,
4507 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004508 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 dispatchedIdBits.clearBit(upId);
4510 }
4511
4512 // Dispatch move events if any of the remaining pointers moved from their old locations.
4513 // Although applications receive new locations as part of individual pointer up
4514 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004515 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4517 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004518 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004519 mCurrentCookedState.cookedPointerData.pointerProperties,
4520 mCurrentCookedState.cookedPointerData.pointerCoords,
4521 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004522 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524
4525 // Dispatch pointer down events using the new pointer locations.
4526 while (!downIdBits.isEmpty()) {
4527 uint32_t downId = downIdBits.clearFirstMarkedBit();
4528 dispatchedIdBits.markBit(downId);
4529
4530 if (dispatchedIdBits.count() == 1) {
4531 // First pointer is going down. Set down time.
4532 mDownTime = when;
4533 }
4534
4535 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004536 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004537 mCurrentCookedState.cookedPointerData.pointerProperties,
4538 mCurrentCookedState.cookedPointerData.pointerCoords,
4539 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004540 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 }
4542 }
4543}
4544
4545void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4546 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004547 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4548 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 int32_t metaState = getContext()->getGlobalMetaState();
4550 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004551 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004552 mLastCookedState.cookedPointerData.pointerProperties,
4553 mLastCookedState.cookedPointerData.pointerCoords,
4554 mLastCookedState.cookedPointerData.idToIndex,
4555 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4557 mSentHoverEnter = false;
4558 }
4559}
4560
4561void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004562 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4563 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 int32_t metaState = getContext()->getGlobalMetaState();
4565 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004566 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004567 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004568 mCurrentCookedState.cookedPointerData.pointerProperties,
4569 mCurrentCookedState.cookedPointerData.pointerCoords,
4570 mCurrentCookedState.cookedPointerData.idToIndex,
4571 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4573 mSentHoverEnter = true;
4574 }
4575
4576 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004577 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004578 mCurrentRawState.buttonState, 0,
4579 mCurrentCookedState.cookedPointerData.pointerProperties,
4580 mCurrentCookedState.cookedPointerData.pointerCoords,
4581 mCurrentCookedState.cookedPointerData.idToIndex,
4582 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4584 }
4585}
4586
Michael Wright7b159c92015-05-14 14:48:03 +01004587void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4588 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4589 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4590 const int32_t metaState = getContext()->getGlobalMetaState();
4591 int32_t buttonState = mLastCookedState.buttonState;
4592 while (!releasedButtons.isEmpty()) {
4593 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4594 buttonState &= ~actionButton;
4595 dispatchMotion(when, policyFlags, mSource,
4596 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4597 0, metaState, buttonState, 0,
4598 mCurrentCookedState.cookedPointerData.pointerProperties,
4599 mCurrentCookedState.cookedPointerData.pointerCoords,
4600 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4601 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4602 }
4603}
4604
4605void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4606 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4607 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4608 const int32_t metaState = getContext()->getGlobalMetaState();
4609 int32_t buttonState = mLastCookedState.buttonState;
4610 while (!pressedButtons.isEmpty()) {
4611 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4612 buttonState |= actionButton;
4613 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4614 0, metaState, buttonState, 0,
4615 mCurrentCookedState.cookedPointerData.pointerProperties,
4616 mCurrentCookedState.cookedPointerData.pointerCoords,
4617 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4618 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4619 }
4620}
4621
4622const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4623 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4624 return cookedPointerData.touchingIdBits;
4625 }
4626 return cookedPointerData.hoveringIdBits;
4627}
4628
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004630 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631
Michael Wright842500e2015-03-13 17:32:02 -07004632 mCurrentCookedState.cookedPointerData.clear();
4633 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4634 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4635 mCurrentRawState.rawPointerData.hoveringIdBits;
4636 mCurrentCookedState.cookedPointerData.touchingIdBits =
4637 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638
Michael Wright7b159c92015-05-14 14:48:03 +01004639 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4640 mCurrentCookedState.buttonState = 0;
4641 } else {
4642 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4643 }
4644
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 // Walk through the the active pointers and map device coordinates onto
4646 // surface coordinates and adjust for display orientation.
4647 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004648 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649
4650 // Size
4651 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4652 switch (mCalibration.sizeCalibration) {
4653 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4654 case Calibration::SIZE_CALIBRATION_DIAMETER:
4655 case Calibration::SIZE_CALIBRATION_BOX:
4656 case Calibration::SIZE_CALIBRATION_AREA:
4657 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4658 touchMajor = in.touchMajor;
4659 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4660 toolMajor = in.toolMajor;
4661 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4662 size = mRawPointerAxes.touchMinor.valid
4663 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4664 } else if (mRawPointerAxes.touchMajor.valid) {
4665 toolMajor = touchMajor = in.touchMajor;
4666 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4667 ? in.touchMinor : in.touchMajor;
4668 size = mRawPointerAxes.touchMinor.valid
4669 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4670 } else if (mRawPointerAxes.toolMajor.valid) {
4671 touchMajor = toolMajor = in.toolMajor;
4672 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4673 ? in.toolMinor : in.toolMajor;
4674 size = mRawPointerAxes.toolMinor.valid
4675 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4676 } else {
4677 ALOG_ASSERT(false, "No touch or tool axes. "
4678 "Size calibration should have been resolved to NONE.");
4679 touchMajor = 0;
4680 touchMinor = 0;
4681 toolMajor = 0;
4682 toolMinor = 0;
4683 size = 0;
4684 }
4685
4686 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004687 uint32_t touchingCount =
4688 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 if (touchingCount > 1) {
4690 touchMajor /= touchingCount;
4691 touchMinor /= touchingCount;
4692 toolMajor /= touchingCount;
4693 toolMinor /= touchingCount;
4694 size /= touchingCount;
4695 }
4696 }
4697
4698 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4699 touchMajor *= mGeometricScale;
4700 touchMinor *= mGeometricScale;
4701 toolMajor *= mGeometricScale;
4702 toolMinor *= mGeometricScale;
4703 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4704 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4705 touchMinor = touchMajor;
4706 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4707 toolMinor = toolMajor;
4708 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4709 touchMinor = touchMajor;
4710 toolMinor = toolMajor;
4711 }
4712
4713 mCalibration.applySizeScaleAndBias(&touchMajor);
4714 mCalibration.applySizeScaleAndBias(&touchMinor);
4715 mCalibration.applySizeScaleAndBias(&toolMajor);
4716 mCalibration.applySizeScaleAndBias(&toolMinor);
4717 size *= mSizeScale;
4718 break;
4719 default:
4720 touchMajor = 0;
4721 touchMinor = 0;
4722 toolMajor = 0;
4723 toolMinor = 0;
4724 size = 0;
4725 break;
4726 }
4727
4728 // Pressure
4729 float pressure;
4730 switch (mCalibration.pressureCalibration) {
4731 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4732 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4733 pressure = in.pressure * mPressureScale;
4734 break;
4735 default:
4736 pressure = in.isHovering ? 0 : 1;
4737 break;
4738 }
4739
4740 // Tilt and Orientation
4741 float tilt;
4742 float orientation;
4743 if (mHaveTilt) {
4744 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4745 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4746 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4747 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4748 } else {
4749 tilt = 0;
4750
4751 switch (mCalibration.orientationCalibration) {
4752 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4753 orientation = in.orientation * mOrientationScale;
4754 break;
4755 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4756 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4757 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4758 if (c1 != 0 || c2 != 0) {
4759 orientation = atan2f(c1, c2) * 0.5f;
4760 float confidence = hypotf(c1, c2);
4761 float scale = 1.0f + confidence / 16.0f;
4762 touchMajor *= scale;
4763 touchMinor /= scale;
4764 toolMajor *= scale;
4765 toolMinor /= scale;
4766 } else {
4767 orientation = 0;
4768 }
4769 break;
4770 }
4771 default:
4772 orientation = 0;
4773 }
4774 }
4775
4776 // Distance
4777 float distance;
4778 switch (mCalibration.distanceCalibration) {
4779 case Calibration::DISTANCE_CALIBRATION_SCALED:
4780 distance = in.distance * mDistanceScale;
4781 break;
4782 default:
4783 distance = 0;
4784 }
4785
4786 // Coverage
4787 int32_t rawLeft, rawTop, rawRight, rawBottom;
4788 switch (mCalibration.coverageCalibration) {
4789 case Calibration::COVERAGE_CALIBRATION_BOX:
4790 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4791 rawRight = in.toolMinor & 0x0000ffff;
4792 rawBottom = in.toolMajor & 0x0000ffff;
4793 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4794 break;
4795 default:
4796 rawLeft = rawTop = rawRight = rawBottom = 0;
4797 break;
4798 }
4799
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004800 // Adjust X,Y coords for device calibration
4801 // TODO: Adjust coverage coords?
4802 float xTransformed = in.x, yTransformed = in.y;
4803 mAffineTransform.applyTo(xTransformed, yTransformed);
4804
4805 // Adjust X, Y, and coverage coords for surface orientation.
4806 float x, y;
4807 float left, top, right, bottom;
4808
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 switch (mSurfaceOrientation) {
4810 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004811 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4812 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4814 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4815 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4816 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4817 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004818 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4820 }
4821 break;
4822 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004823 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4824 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4826 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4827 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4828 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4829 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09004830 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4832 }
4833 break;
4834 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004835 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4836 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4838 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4839 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4840 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4841 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004842 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4844 }
4845 break;
4846 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004847 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4848 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4850 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4851 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4852 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4853 break;
4854 }
4855
4856 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07004857 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 out.clear();
4859 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4860 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4861 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4862 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4863 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4864 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4865 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4866 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4867 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4868 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4869 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4870 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4871 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4872 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4873 } else {
4874 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4875 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4876 }
4877
4878 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07004879 PointerProperties& properties =
4880 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 uint32_t id = in.id;
4882 properties.clear();
4883 properties.id = id;
4884 properties.toolType = in.toolType;
4885
4886 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07004887 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 }
4889}
4890
4891void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4892 PointerUsage pointerUsage) {
4893 if (pointerUsage != mPointerUsage) {
4894 abortPointerUsage(when, policyFlags);
4895 mPointerUsage = pointerUsage;
4896 }
4897
4898 switch (mPointerUsage) {
4899 case POINTER_USAGE_GESTURES:
4900 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4901 break;
4902 case POINTER_USAGE_STYLUS:
4903 dispatchPointerStylus(when, policyFlags);
4904 break;
4905 case POINTER_USAGE_MOUSE:
4906 dispatchPointerMouse(when, policyFlags);
4907 break;
4908 default:
4909 break;
4910 }
4911}
4912
4913void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4914 switch (mPointerUsage) {
4915 case POINTER_USAGE_GESTURES:
4916 abortPointerGestures(when, policyFlags);
4917 break;
4918 case POINTER_USAGE_STYLUS:
4919 abortPointerStylus(when, policyFlags);
4920 break;
4921 case POINTER_USAGE_MOUSE:
4922 abortPointerMouse(when, policyFlags);
4923 break;
4924 default:
4925 break;
4926 }
4927
4928 mPointerUsage = POINTER_USAGE_NONE;
4929}
4930
4931void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
4932 bool isTimeout) {
4933 // Update current gesture coordinates.
4934 bool cancelPreviousGesture, finishPreviousGesture;
4935 bool sendEvents = preparePointerGestures(when,
4936 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
4937 if (!sendEvents) {
4938 return;
4939 }
4940 if (finishPreviousGesture) {
4941 cancelPreviousGesture = false;
4942 }
4943
4944 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04004945 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
4946 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947 if (finishPreviousGesture || cancelPreviousGesture) {
4948 mPointerController->clearSpots();
4949 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04004950
4951 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
4952 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
4953 mPointerGesture.currentGestureIdToIndex,
4954 mPointerGesture.currentGestureIdBits);
4955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 } else {
4957 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4958 }
4959
4960 // Show or hide the pointer if needed.
4961 switch (mPointerGesture.currentGestureMode) {
4962 case PointerGesture::NEUTRAL:
4963 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04004964 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
4965 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 // Remind the user of where the pointer is after finishing a gesture with spots.
4967 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
4968 }
4969 break;
4970 case PointerGesture::TAP:
4971 case PointerGesture::TAP_DRAG:
4972 case PointerGesture::BUTTON_CLICK_OR_DRAG:
4973 case PointerGesture::HOVER:
4974 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04004975 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 // Unfade the pointer when the current gesture manipulates the
4977 // area directly under the pointer.
4978 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4979 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 case PointerGesture::FREEFORM:
4981 // Fade the pointer when the current gesture manipulates a different
4982 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04004983 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4985 } else {
4986 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4987 }
4988 break;
4989 }
4990
4991 // Send events!
4992 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004993 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994
4995 // Update last coordinates of pointers that have moved so that we observe the new
4996 // pointer positions at the same time as other pointers that have just gone up.
4997 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
4998 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
4999 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5000 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5001 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5002 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5003 bool moveNeeded = false;
5004 if (down && !cancelPreviousGesture && !finishPreviousGesture
5005 && !mPointerGesture.lastGestureIdBits.isEmpty()
5006 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5007 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5008 & mPointerGesture.lastGestureIdBits.value);
5009 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5010 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5011 mPointerGesture.lastGestureProperties,
5012 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5013 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005014 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 moveNeeded = true;
5016 }
5017 }
5018
5019 // Send motion events for all pointers that went up or were canceled.
5020 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5021 if (!dispatchedGestureIdBits.isEmpty()) {
5022 if (cancelPreviousGesture) {
5023 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005024 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 AMOTION_EVENT_EDGE_FLAG_NONE,
5026 mPointerGesture.lastGestureProperties,
5027 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005028 dispatchedGestureIdBits, -1, 0,
5029 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030
5031 dispatchedGestureIdBits.clear();
5032 } else {
5033 BitSet32 upGestureIdBits;
5034 if (finishPreviousGesture) {
5035 upGestureIdBits = dispatchedGestureIdBits;
5036 } else {
5037 upGestureIdBits.value = dispatchedGestureIdBits.value
5038 & ~mPointerGesture.currentGestureIdBits.value;
5039 }
5040 while (!upGestureIdBits.isEmpty()) {
5041 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5042
5043 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005044 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5046 mPointerGesture.lastGestureProperties,
5047 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5048 dispatchedGestureIdBits, id,
5049 0, 0, mPointerGesture.downTime);
5050
5051 dispatchedGestureIdBits.clearBit(id);
5052 }
5053 }
5054 }
5055
5056 // Send motion events for all pointers that moved.
5057 if (moveNeeded) {
5058 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005059 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5060 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 mPointerGesture.currentGestureProperties,
5062 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5063 dispatchedGestureIdBits, -1,
5064 0, 0, mPointerGesture.downTime);
5065 }
5066
5067 // Send motion events for all pointers that went down.
5068 if (down) {
5069 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5070 & ~dispatchedGestureIdBits.value);
5071 while (!downGestureIdBits.isEmpty()) {
5072 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5073 dispatchedGestureIdBits.markBit(id);
5074
5075 if (dispatchedGestureIdBits.count() == 1) {
5076 mPointerGesture.downTime = when;
5077 }
5078
5079 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005080 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 mPointerGesture.currentGestureProperties,
5082 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5083 dispatchedGestureIdBits, id,
5084 0, 0, mPointerGesture.downTime);
5085 }
5086 }
5087
5088 // Send motion events for hover.
5089 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5090 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005091 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5093 mPointerGesture.currentGestureProperties,
5094 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5095 mPointerGesture.currentGestureIdBits, -1,
5096 0, 0, mPointerGesture.downTime);
5097 } else if (dispatchedGestureIdBits.isEmpty()
5098 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5099 // Synthesize a hover move event after all pointers go up to indicate that
5100 // the pointer is hovering again even if the user is not currently touching
5101 // the touch pad. This ensures that a view will receive a fresh hover enter
5102 // event after a tap.
5103 float x, y;
5104 mPointerController->getPosition(&x, &y);
5105
5106 PointerProperties pointerProperties;
5107 pointerProperties.clear();
5108 pointerProperties.id = 0;
5109 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5110
5111 PointerCoords pointerCoords;
5112 pointerCoords.clear();
5113 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5114 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5115
5116 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005117 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5119 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5120 0, 0, mPointerGesture.downTime);
5121 getListener()->notifyMotion(&args);
5122 }
5123
5124 // Update state.
5125 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5126 if (!down) {
5127 mPointerGesture.lastGestureIdBits.clear();
5128 } else {
5129 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5130 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5131 uint32_t id = idBits.clearFirstMarkedBit();
5132 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5133 mPointerGesture.lastGestureProperties[index].copyFrom(
5134 mPointerGesture.currentGestureProperties[index]);
5135 mPointerGesture.lastGestureCoords[index].copyFrom(
5136 mPointerGesture.currentGestureCoords[index]);
5137 mPointerGesture.lastGestureIdToIndex[id] = index;
5138 }
5139 }
5140}
5141
5142void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5143 // Cancel previously dispatches pointers.
5144 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5145 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005146 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005148 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 AMOTION_EVENT_EDGE_FLAG_NONE,
5150 mPointerGesture.lastGestureProperties,
5151 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5152 mPointerGesture.lastGestureIdBits, -1,
5153 0, 0, mPointerGesture.downTime);
5154 }
5155
5156 // Reset the current pointer gesture.
5157 mPointerGesture.reset();
5158 mPointerVelocityControl.reset();
5159
5160 // Remove any current spots.
5161 if (mPointerController != NULL) {
5162 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5163 mPointerController->clearSpots();
5164 }
5165}
5166
5167bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5168 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5169 *outCancelPreviousGesture = false;
5170 *outFinishPreviousGesture = false;
5171
5172 // Handle TAP timeout.
5173 if (isTimeout) {
5174#if DEBUG_GESTURES
5175 ALOGD("Gestures: Processing timeout");
5176#endif
5177
5178 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5179 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5180 // The tap/drag timeout has not yet expired.
5181 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5182 + mConfig.pointerGestureTapDragInterval);
5183 } else {
5184 // The tap is finished.
5185#if DEBUG_GESTURES
5186 ALOGD("Gestures: TAP finished");
5187#endif
5188 *outFinishPreviousGesture = true;
5189
5190 mPointerGesture.activeGestureId = -1;
5191 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5192 mPointerGesture.currentGestureIdBits.clear();
5193
5194 mPointerVelocityControl.reset();
5195 return true;
5196 }
5197 }
5198
5199 // We did not handle this timeout.
5200 return false;
5201 }
5202
Michael Wright842500e2015-03-13 17:32:02 -07005203 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5204 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205
5206 // Update the velocity tracker.
5207 {
5208 VelocityTracker::Position positions[MAX_POINTERS];
5209 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005210 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005212 const RawPointerData::Pointer& pointer =
5213 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 positions[count].x = pointer.x * mPointerXMovementScale;
5215 positions[count].y = pointer.y * mPointerYMovementScale;
5216 }
5217 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005218 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 }
5220
5221 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5222 // to NEUTRAL, then we should not generate tap event.
5223 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5224 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5225 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5226 mPointerGesture.resetTap();
5227 }
5228
5229 // Pick a new active touch id if needed.
5230 // Choose an arbitrary pointer that just went down, if there is one.
5231 // Otherwise choose an arbitrary remaining pointer.
5232 // This guarantees we always have an active touch id when there is at least one pointer.
5233 // We keep the same active touch id for as long as possible.
5234 bool activeTouchChanged = false;
5235 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5236 int32_t activeTouchId = lastActiveTouchId;
5237 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005238 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 activeTouchChanged = true;
5240 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005241 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242 mPointerGesture.firstTouchTime = when;
5243 }
Michael Wright842500e2015-03-13 17:32:02 -07005244 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005246 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005248 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 } else {
5250 activeTouchId = mPointerGesture.activeTouchId = -1;
5251 }
5252 }
5253
5254 // Determine whether we are in quiet time.
5255 bool isQuietTime = false;
5256 if (activeTouchId < 0) {
5257 mPointerGesture.resetQuietTime();
5258 } else {
5259 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5260 if (!isQuietTime) {
5261 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5262 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5263 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5264 && currentFingerCount < 2) {
5265 // Enter quiet time when exiting swipe or freeform state.
5266 // This is to prevent accidentally entering the hover state and flinging the
5267 // pointer when finishing a swipe and there is still one pointer left onscreen.
5268 isQuietTime = true;
5269 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5270 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005271 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 // Enter quiet time when releasing the button and there are still two or more
5273 // fingers down. This may indicate that one finger was used to press the button
5274 // but it has not gone up yet.
5275 isQuietTime = true;
5276 }
5277 if (isQuietTime) {
5278 mPointerGesture.quietTime = when;
5279 }
5280 }
5281 }
5282
5283 // Switch states based on button and pointer state.
5284 if (isQuietTime) {
5285 // Case 1: Quiet time. (QUIET)
5286#if DEBUG_GESTURES
5287 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5288 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5289#endif
5290 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5291 *outFinishPreviousGesture = true;
5292 }
5293
5294 mPointerGesture.activeGestureId = -1;
5295 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5296 mPointerGesture.currentGestureIdBits.clear();
5297
5298 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005299 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5301 // The pointer follows the active touch point.
5302 // Emit DOWN, MOVE, UP events at the pointer location.
5303 //
5304 // Only the active touch matters; other fingers are ignored. This policy helps
5305 // to handle the case where the user places a second finger on the touch pad
5306 // to apply the necessary force to depress an integrated button below the surface.
5307 // We don't want the second finger to be delivered to applications.
5308 //
5309 // For this to work well, we need to make sure to track the pointer that is really
5310 // active. If the user first puts one finger down to click then adds another
5311 // finger to drag then the active pointer should switch to the finger that is
5312 // being dragged.
5313#if DEBUG_GESTURES
5314 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5315 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5316#endif
5317 // Reset state when just starting.
5318 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5319 *outFinishPreviousGesture = true;
5320 mPointerGesture.activeGestureId = 0;
5321 }
5322
5323 // Switch pointers if needed.
5324 // Find the fastest pointer and follow it.
5325 if (activeTouchId >= 0 && currentFingerCount > 1) {
5326 int32_t bestId = -1;
5327 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005328 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 uint32_t id = idBits.clearFirstMarkedBit();
5330 float vx, vy;
5331 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5332 float speed = hypotf(vx, vy);
5333 if (speed > bestSpeed) {
5334 bestId = id;
5335 bestSpeed = speed;
5336 }
5337 }
5338 }
5339 if (bestId >= 0 && bestId != activeTouchId) {
5340 mPointerGesture.activeTouchId = activeTouchId = bestId;
5341 activeTouchChanged = true;
5342#if DEBUG_GESTURES
5343 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5344 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5345#endif
5346 }
5347 }
5348
Jun Mukaifa1706a2015-12-03 01:14:46 -08005349 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005350 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005352 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005354 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005355 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5356 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357
5358 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5359 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5360
5361 // Move the pointer using a relative motion.
5362 // When using spots, the click will occur at the position of the anchor
5363 // spot and all other spots will move there.
5364 mPointerController->move(deltaX, deltaY);
5365 } else {
5366 mPointerVelocityControl.reset();
5367 }
5368
5369 float x, y;
5370 mPointerController->getPosition(&x, &y);
5371
5372 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5373 mPointerGesture.currentGestureIdBits.clear();
5374 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5375 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5376 mPointerGesture.currentGestureProperties[0].clear();
5377 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5378 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5379 mPointerGesture.currentGestureCoords[0].clear();
5380 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5381 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5382 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005383 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
5384 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 } else if (currentFingerCount == 0) {
5386 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5387 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5388 *outFinishPreviousGesture = true;
5389 }
5390
5391 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5392 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5393 bool tapped = false;
5394 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5395 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5396 && lastFingerCount == 1) {
5397 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5398 float x, y;
5399 mPointerController->getPosition(&x, &y);
5400 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5401 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5402#if DEBUG_GESTURES
5403 ALOGD("Gestures: TAP");
5404#endif
5405
5406 mPointerGesture.tapUpTime = when;
5407 getContext()->requestTimeoutAtTime(when
5408 + mConfig.pointerGestureTapDragInterval);
5409
5410 mPointerGesture.activeGestureId = 0;
5411 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5412 mPointerGesture.currentGestureIdBits.clear();
5413 mPointerGesture.currentGestureIdBits.markBit(
5414 mPointerGesture.activeGestureId);
5415 mPointerGesture.currentGestureIdToIndex[
5416 mPointerGesture.activeGestureId] = 0;
5417 mPointerGesture.currentGestureProperties[0].clear();
5418 mPointerGesture.currentGestureProperties[0].id =
5419 mPointerGesture.activeGestureId;
5420 mPointerGesture.currentGestureProperties[0].toolType =
5421 AMOTION_EVENT_TOOL_TYPE_FINGER;
5422 mPointerGesture.currentGestureCoords[0].clear();
5423 mPointerGesture.currentGestureCoords[0].setAxisValue(
5424 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5425 mPointerGesture.currentGestureCoords[0].setAxisValue(
5426 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5427 mPointerGesture.currentGestureCoords[0].setAxisValue(
5428 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5429
5430 tapped = true;
5431 } else {
5432#if DEBUG_GESTURES
5433 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5434 x - mPointerGesture.tapX,
5435 y - mPointerGesture.tapY);
5436#endif
5437 }
5438 } else {
5439#if DEBUG_GESTURES
5440 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5441 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5442 (when - mPointerGesture.tapDownTime) * 0.000001f);
5443 } else {
5444 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5445 }
5446#endif
5447 }
5448 }
5449
5450 mPointerVelocityControl.reset();
5451
5452 if (!tapped) {
5453#if DEBUG_GESTURES
5454 ALOGD("Gestures: NEUTRAL");
5455#endif
5456 mPointerGesture.activeGestureId = -1;
5457 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5458 mPointerGesture.currentGestureIdBits.clear();
5459 }
5460 } else if (currentFingerCount == 1) {
5461 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5462 // The pointer follows the active touch point.
5463 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5464 // When in TAP_DRAG, emit MOVE events at the pointer location.
5465 ALOG_ASSERT(activeTouchId >= 0);
5466
5467 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5468 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5469 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5470 float x, y;
5471 mPointerController->getPosition(&x, &y);
5472 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5473 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5474 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5475 } else {
5476#if DEBUG_GESTURES
5477 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5478 x - mPointerGesture.tapX,
5479 y - mPointerGesture.tapY);
5480#endif
5481 }
5482 } else {
5483#if DEBUG_GESTURES
5484 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5485 (when - mPointerGesture.tapUpTime) * 0.000001f);
5486#endif
5487 }
5488 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5489 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5490 }
5491
Jun Mukaifa1706a2015-12-03 01:14:46 -08005492 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005493 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005495 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005497 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005498 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5499 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500
5501 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5502 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5503
5504 // Move the pointer using a relative motion.
5505 // When using spots, the hover or drag will occur at the position of the anchor spot.
5506 mPointerController->move(deltaX, deltaY);
5507 } else {
5508 mPointerVelocityControl.reset();
5509 }
5510
5511 bool down;
5512 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5513#if DEBUG_GESTURES
5514 ALOGD("Gestures: TAP_DRAG");
5515#endif
5516 down = true;
5517 } else {
5518#if DEBUG_GESTURES
5519 ALOGD("Gestures: HOVER");
5520#endif
5521 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5522 *outFinishPreviousGesture = true;
5523 }
5524 mPointerGesture.activeGestureId = 0;
5525 down = false;
5526 }
5527
5528 float x, y;
5529 mPointerController->getPosition(&x, &y);
5530
5531 mPointerGesture.currentGestureIdBits.clear();
5532 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5533 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5534 mPointerGesture.currentGestureProperties[0].clear();
5535 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5536 mPointerGesture.currentGestureProperties[0].toolType =
5537 AMOTION_EVENT_TOOL_TYPE_FINGER;
5538 mPointerGesture.currentGestureCoords[0].clear();
5539 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5540 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5541 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5542 down ? 1.0f : 0.0f);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005543 mPointerGesture.currentGestureCoords[0].setAxisValue(
5544 AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
5545 mPointerGesture.currentGestureCoords[0].setAxisValue(
5546 AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547
5548 if (lastFingerCount == 0 && currentFingerCount != 0) {
5549 mPointerGesture.resetTap();
5550 mPointerGesture.tapDownTime = when;
5551 mPointerGesture.tapX = x;
5552 mPointerGesture.tapY = y;
5553 }
5554 } else {
5555 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5556 // We need to provide feedback for each finger that goes down so we cannot wait
5557 // for the fingers to move before deciding what to do.
5558 //
5559 // The ambiguous case is deciding what to do when there are two fingers down but they
5560 // have not moved enough to determine whether they are part of a drag or part of a
5561 // freeform gesture, or just a press or long-press at the pointer location.
5562 //
5563 // When there are two fingers we start with the PRESS hypothesis and we generate a
5564 // down at the pointer location.
5565 //
5566 // When the two fingers move enough or when additional fingers are added, we make
5567 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5568 ALOG_ASSERT(activeTouchId >= 0);
5569
5570 bool settled = when >= mPointerGesture.firstTouchTime
5571 + mConfig.pointerGestureMultitouchSettleInterval;
5572 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5573 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5574 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5575 *outFinishPreviousGesture = true;
5576 } else if (!settled && currentFingerCount > lastFingerCount) {
5577 // Additional pointers have gone down but not yet settled.
5578 // Reset the gesture.
5579#if DEBUG_GESTURES
5580 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5581 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5582 + mConfig.pointerGestureMultitouchSettleInterval - when)
5583 * 0.000001f);
5584#endif
5585 *outCancelPreviousGesture = true;
5586 } else {
5587 // Continue previous gesture.
5588 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5589 }
5590
5591 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5592 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5593 mPointerGesture.activeGestureId = 0;
5594 mPointerGesture.referenceIdBits.clear();
5595 mPointerVelocityControl.reset();
5596
5597 // Use the centroid and pointer location as the reference points for the gesture.
5598#if DEBUG_GESTURES
5599 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5600 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5601 + mConfig.pointerGestureMultitouchSettleInterval - when)
5602 * 0.000001f);
5603#endif
Michael Wright842500e2015-03-13 17:32:02 -07005604 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 &mPointerGesture.referenceTouchX,
5606 &mPointerGesture.referenceTouchY);
5607 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5608 &mPointerGesture.referenceGestureY);
5609 }
5610
5611 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005612 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5614 uint32_t id = idBits.clearFirstMarkedBit();
5615 mPointerGesture.referenceDeltas[id].dx = 0;
5616 mPointerGesture.referenceDeltas[id].dy = 0;
5617 }
Michael Wright842500e2015-03-13 17:32:02 -07005618 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619
5620 // Add delta for all fingers and calculate a common movement delta.
5621 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005622 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5623 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5625 bool first = (idBits == commonIdBits);
5626 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005627 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5628 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5630 delta.dx += cpd.x - lpd.x;
5631 delta.dy += cpd.y - lpd.y;
5632
5633 if (first) {
5634 commonDeltaX = delta.dx;
5635 commonDeltaY = delta.dy;
5636 } else {
5637 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5638 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5639 }
5640 }
5641
5642 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5643 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5644 float dist[MAX_POINTER_ID + 1];
5645 int32_t distOverThreshold = 0;
5646 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5647 uint32_t id = idBits.clearFirstMarkedBit();
5648 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5649 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5650 delta.dy * mPointerYZoomScale);
5651 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5652 distOverThreshold += 1;
5653 }
5654 }
5655
5656 // Only transition when at least two pointers have moved further than
5657 // the minimum distance threshold.
5658 if (distOverThreshold >= 2) {
5659 if (currentFingerCount > 2) {
5660 // There are more than two pointers, switch to FREEFORM.
5661#if DEBUG_GESTURES
5662 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5663 currentFingerCount);
5664#endif
5665 *outCancelPreviousGesture = true;
5666 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5667 } else {
5668 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005669 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 uint32_t id1 = idBits.clearFirstMarkedBit();
5671 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005672 const RawPointerData::Pointer& p1 =
5673 mCurrentRawState.rawPointerData.pointerForId(id1);
5674 const RawPointerData::Pointer& p2 =
5675 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5677 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5678 // There are two pointers but they are too far apart for a SWIPE,
5679 // switch to FREEFORM.
5680#if DEBUG_GESTURES
5681 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5682 mutualDistance, mPointerGestureMaxSwipeWidth);
5683#endif
5684 *outCancelPreviousGesture = true;
5685 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5686 } else {
5687 // There are two pointers. Wait for both pointers to start moving
5688 // before deciding whether this is a SWIPE or FREEFORM gesture.
5689 float dist1 = dist[id1];
5690 float dist2 = dist[id2];
5691 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5692 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5693 // Calculate the dot product of the displacement vectors.
5694 // When the vectors are oriented in approximately the same direction,
5695 // the angle betweeen them is near zero and the cosine of the angle
5696 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5697 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5698 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5699 float dx1 = delta1.dx * mPointerXZoomScale;
5700 float dy1 = delta1.dy * mPointerYZoomScale;
5701 float dx2 = delta2.dx * mPointerXZoomScale;
5702 float dy2 = delta2.dy * mPointerYZoomScale;
5703 float dot = dx1 * dx2 + dy1 * dy2;
5704 float cosine = dot / (dist1 * dist2); // denominator always > 0
5705 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5706 // Pointers are moving in the same direction. Switch to SWIPE.
5707#if DEBUG_GESTURES
5708 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5709 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5710 "cosine %0.3f >= %0.3f",
5711 dist1, mConfig.pointerGestureMultitouchMinDistance,
5712 dist2, mConfig.pointerGestureMultitouchMinDistance,
5713 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5714#endif
5715 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5716 } else {
5717 // Pointers are moving in different directions. Switch to FREEFORM.
5718#if DEBUG_GESTURES
5719 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5720 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5721 "cosine %0.3f < %0.3f",
5722 dist1, mConfig.pointerGestureMultitouchMinDistance,
5723 dist2, mConfig.pointerGestureMultitouchMinDistance,
5724 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5725#endif
5726 *outCancelPreviousGesture = true;
5727 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5728 }
5729 }
5730 }
5731 }
5732 }
5733 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5734 // Switch from SWIPE to FREEFORM if additional pointers go down.
5735 // Cancel previous gesture.
5736 if (currentFingerCount > 2) {
5737#if DEBUG_GESTURES
5738 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5739 currentFingerCount);
5740#endif
5741 *outCancelPreviousGesture = true;
5742 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5743 }
5744 }
5745
5746 // Move the reference points based on the overall group motion of the fingers
5747 // except in PRESS mode while waiting for a transition to occur.
5748 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5749 && (commonDeltaX || commonDeltaY)) {
5750 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5751 uint32_t id = idBits.clearFirstMarkedBit();
5752 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5753 delta.dx = 0;
5754 delta.dy = 0;
5755 }
5756
5757 mPointerGesture.referenceTouchX += commonDeltaX;
5758 mPointerGesture.referenceTouchY += commonDeltaY;
5759
5760 commonDeltaX *= mPointerXMovementScale;
5761 commonDeltaY *= mPointerYMovementScale;
5762
5763 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5764 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5765
5766 mPointerGesture.referenceGestureX += commonDeltaX;
5767 mPointerGesture.referenceGestureY += commonDeltaY;
5768 }
5769
5770 // Report gestures.
5771 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5772 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5773 // PRESS or SWIPE mode.
5774#if DEBUG_GESTURES
5775 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5776 "activeGestureId=%d, currentTouchPointerCount=%d",
5777 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5778#endif
5779 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5780
5781 mPointerGesture.currentGestureIdBits.clear();
5782 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5783 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5784 mPointerGesture.currentGestureProperties[0].clear();
5785 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5786 mPointerGesture.currentGestureProperties[0].toolType =
5787 AMOTION_EVENT_TOOL_TYPE_FINGER;
5788 mPointerGesture.currentGestureCoords[0].clear();
5789 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5790 mPointerGesture.referenceGestureX);
5791 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5792 mPointerGesture.referenceGestureY);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005793 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X,
5794 commonDeltaX);
5795 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y,
5796 commonDeltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5798 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5799 // FREEFORM mode.
5800#if DEBUG_GESTURES
5801 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5802 "activeGestureId=%d, currentTouchPointerCount=%d",
5803 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5804#endif
5805 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5806
5807 mPointerGesture.currentGestureIdBits.clear();
5808
5809 BitSet32 mappedTouchIdBits;
5810 BitSet32 usedGestureIdBits;
5811 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5812 // Initially, assign the active gesture id to the active touch point
5813 // if there is one. No other touch id bits are mapped yet.
5814 if (!*outCancelPreviousGesture) {
5815 mappedTouchIdBits.markBit(activeTouchId);
5816 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5817 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5818 mPointerGesture.activeGestureId;
5819 } else {
5820 mPointerGesture.activeGestureId = -1;
5821 }
5822 } else {
5823 // Otherwise, assume we mapped all touches from the previous frame.
5824 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07005825 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
5826 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5828
5829 // Check whether we need to choose a new active gesture id because the
5830 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07005831 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
5832 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 !upTouchIdBits.isEmpty(); ) {
5834 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5835 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5836 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5837 mPointerGesture.activeGestureId = -1;
5838 break;
5839 }
5840 }
5841 }
5842
5843#if DEBUG_GESTURES
5844 ALOGD("Gestures: FREEFORM follow up "
5845 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5846 "activeGestureId=%d",
5847 mappedTouchIdBits.value, usedGestureIdBits.value,
5848 mPointerGesture.activeGestureId);
5849#endif
5850
Michael Wright842500e2015-03-13 17:32:02 -07005851 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852 for (uint32_t i = 0; i < currentFingerCount; i++) {
5853 uint32_t touchId = idBits.clearFirstMarkedBit();
5854 uint32_t gestureId;
5855 if (!mappedTouchIdBits.hasBit(touchId)) {
5856 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5857 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5858#if DEBUG_GESTURES
5859 ALOGD("Gestures: FREEFORM "
5860 "new mapping for touch id %d -> gesture id %d",
5861 touchId, gestureId);
5862#endif
5863 } else {
5864 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5865#if DEBUG_GESTURES
5866 ALOGD("Gestures: FREEFORM "
5867 "existing mapping for touch id %d -> gesture id %d",
5868 touchId, gestureId);
5869#endif
5870 }
5871 mPointerGesture.currentGestureIdBits.markBit(gestureId);
5872 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5873
5874 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07005875 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005876 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5877 * mPointerXZoomScale;
5878 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5879 * mPointerYZoomScale;
5880 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5881
5882 mPointerGesture.currentGestureProperties[i].clear();
5883 mPointerGesture.currentGestureProperties[i].id = gestureId;
5884 mPointerGesture.currentGestureProperties[i].toolType =
5885 AMOTION_EVENT_TOOL_TYPE_FINGER;
5886 mPointerGesture.currentGestureCoords[i].clear();
5887 mPointerGesture.currentGestureCoords[i].setAxisValue(
5888 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5889 mPointerGesture.currentGestureCoords[i].setAxisValue(
5890 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5891 mPointerGesture.currentGestureCoords[i].setAxisValue(
5892 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005893 mPointerGesture.currentGestureCoords[i].setAxisValue(
5894 AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
5895 mPointerGesture.currentGestureCoords[i].setAxisValue(
5896 AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 }
5898
5899 if (mPointerGesture.activeGestureId < 0) {
5900 mPointerGesture.activeGestureId =
5901 mPointerGesture.currentGestureIdBits.firstMarkedBit();
5902#if DEBUG_GESTURES
5903 ALOGD("Gestures: FREEFORM new "
5904 "activeGestureId=%d", mPointerGesture.activeGestureId);
5905#endif
5906 }
5907 }
5908 }
5909
Michael Wright842500e2015-03-13 17:32:02 -07005910 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911
5912#if DEBUG_GESTURES
5913 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5914 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5915 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5916 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5917 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5918 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5919 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5920 uint32_t id = idBits.clearFirstMarkedBit();
5921 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5922 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5923 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5924 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
5925 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5926 id, index, properties.toolType,
5927 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5928 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5929 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5930 }
5931 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5932 uint32_t id = idBits.clearFirstMarkedBit();
5933 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5934 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5935 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5936 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
5937 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5938 id, index, properties.toolType,
5939 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5940 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5941 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5942 }
5943#endif
5944 return true;
5945}
5946
5947void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
5948 mPointerSimple.currentCoords.clear();
5949 mPointerSimple.currentProperties.clear();
5950
5951 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07005952 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
5953 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
5954 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
5955 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
5956 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957 mPointerController->setPosition(x, y);
5958
Michael Wright842500e2015-03-13 17:32:02 -07005959 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960 down = !hovering;
5961
5962 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07005963 mPointerSimple.currentCoords.copyFrom(
5964 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5966 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5967 mPointerSimple.currentProperties.id = 0;
5968 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07005969 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970 } else {
5971 down = false;
5972 hovering = false;
5973 }
5974
5975 dispatchPointerSimple(when, policyFlags, down, hovering);
5976}
5977
5978void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
5979 abortPointerSimple(when, policyFlags);
5980}
5981
5982void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
5983 mPointerSimple.currentCoords.clear();
5984 mPointerSimple.currentProperties.clear();
5985
5986 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07005987 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
5988 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
5989 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08005990 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005991 if (mLastCookedState.mouseIdBits.hasBit(id)) {
5992 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08005993 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07005994 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08005996 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07005997 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998 * mPointerYMovementScale;
5999
6000 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6001 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6002
6003 mPointerController->move(deltaX, deltaY);
6004 } else {
6005 mPointerVelocityControl.reset();
6006 }
6007
Michael Wright842500e2015-03-13 17:32:02 -07006008 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009 hovering = !down;
6010
6011 float x, y;
6012 mPointerController->getPosition(&x, &y);
6013 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006014 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6016 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6017 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6018 hovering ? 0.0f : 1.0f);
Jun Mukaifa1706a2015-12-03 01:14:46 -08006019 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, x);
6020 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, y);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006021 mPointerSimple.currentProperties.id = 0;
6022 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006023 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 } else {
6025 mPointerVelocityControl.reset();
6026
6027 down = false;
6028 hovering = false;
6029 }
6030
6031 dispatchPointerSimple(when, policyFlags, down, hovering);
6032}
6033
6034void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6035 abortPointerSimple(when, policyFlags);
6036
6037 mPointerVelocityControl.reset();
6038}
6039
6040void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6041 bool down, bool hovering) {
6042 int32_t metaState = getContext()->getGlobalMetaState();
6043
6044 if (mPointerController != NULL) {
6045 if (down || hovering) {
6046 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6047 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006048 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6050 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6051 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6052 }
6053 }
6054
6055 if (mPointerSimple.down && !down) {
6056 mPointerSimple.down = false;
6057
6058 // Send up.
6059 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006060 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 mViewport.displayId,
6062 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6063 mOrientedXPrecision, mOrientedYPrecision,
6064 mPointerSimple.downTime);
6065 getListener()->notifyMotion(&args);
6066 }
6067
6068 if (mPointerSimple.hovering && !hovering) {
6069 mPointerSimple.hovering = false;
6070
6071 // Send hover exit.
6072 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006073 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074 mViewport.displayId,
6075 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6076 mOrientedXPrecision, mOrientedYPrecision,
6077 mPointerSimple.downTime);
6078 getListener()->notifyMotion(&args);
6079 }
6080
6081 if (down) {
6082 if (!mPointerSimple.down) {
6083 mPointerSimple.down = true;
6084 mPointerSimple.downTime = when;
6085
6086 // Send down.
6087 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006088 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 mViewport.displayId,
6090 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6091 mOrientedXPrecision, mOrientedYPrecision,
6092 mPointerSimple.downTime);
6093 getListener()->notifyMotion(&args);
6094 }
6095
6096 // Send move.
6097 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006098 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 mViewport.displayId,
6100 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6101 mOrientedXPrecision, mOrientedYPrecision,
6102 mPointerSimple.downTime);
6103 getListener()->notifyMotion(&args);
6104 }
6105
6106 if (hovering) {
6107 if (!mPointerSimple.hovering) {
6108 mPointerSimple.hovering = true;
6109
6110 // Send hover enter.
6111 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006112 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006113 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114 mViewport.displayId,
6115 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6116 mOrientedXPrecision, mOrientedYPrecision,
6117 mPointerSimple.downTime);
6118 getListener()->notifyMotion(&args);
6119 }
6120
6121 // Send hover move.
6122 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006123 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006124 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006125 mViewport.displayId,
6126 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6127 mOrientedXPrecision, mOrientedYPrecision,
6128 mPointerSimple.downTime);
6129 getListener()->notifyMotion(&args);
6130 }
6131
Michael Wright842500e2015-03-13 17:32:02 -07006132 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6133 float vscroll = mCurrentRawState.rawVScroll;
6134 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006135 mWheelYVelocityControl.move(when, NULL, &vscroll);
6136 mWheelXVelocityControl.move(when, &hscroll, NULL);
6137
6138 // Send scroll.
6139 PointerCoords pointerCoords;
6140 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6141 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6142 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6143
6144 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006145 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146 mViewport.displayId,
6147 1, &mPointerSimple.currentProperties, &pointerCoords,
6148 mOrientedXPrecision, mOrientedYPrecision,
6149 mPointerSimple.downTime);
6150 getListener()->notifyMotion(&args);
6151 }
6152
6153 // Save state.
6154 if (down || hovering) {
6155 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6156 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6157 } else {
6158 mPointerSimple.reset();
6159 }
6160}
6161
6162void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6163 mPointerSimple.currentCoords.clear();
6164 mPointerSimple.currentProperties.clear();
6165
6166 dispatchPointerSimple(when, policyFlags, false, false);
6167}
6168
6169void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006170 int32_t action, int32_t actionButton, int32_t flags,
6171 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006172 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006173 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6174 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006175 PointerCoords pointerCoords[MAX_POINTERS];
6176 PointerProperties pointerProperties[MAX_POINTERS];
6177 uint32_t pointerCount = 0;
6178 while (!idBits.isEmpty()) {
6179 uint32_t id = idBits.clearFirstMarkedBit();
6180 uint32_t index = idToIndex[id];
6181 pointerProperties[pointerCount].copyFrom(properties[index]);
6182 pointerCoords[pointerCount].copyFrom(coords[index]);
6183
6184 if (changedId >= 0 && id == uint32_t(changedId)) {
6185 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6186 }
6187
6188 pointerCount += 1;
6189 }
6190
6191 ALOG_ASSERT(pointerCount != 0);
6192
6193 if (changedId >= 0 && pointerCount == 1) {
6194 // Replace initial down and final up action.
6195 // We can compare the action without masking off the changed pointer index
6196 // because we know the index is 0.
6197 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6198 action = AMOTION_EVENT_ACTION_DOWN;
6199 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6200 action = AMOTION_EVENT_ACTION_UP;
6201 } else {
6202 // Can't happen.
6203 ALOG_ASSERT(false);
6204 }
6205 }
6206
6207 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006208 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006209 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6210 xPrecision, yPrecision, downTime);
6211 getListener()->notifyMotion(&args);
6212}
6213
6214bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6215 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6216 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6217 BitSet32 idBits) const {
6218 bool changed = false;
6219 while (!idBits.isEmpty()) {
6220 uint32_t id = idBits.clearFirstMarkedBit();
6221 uint32_t inIndex = inIdToIndex[id];
6222 uint32_t outIndex = outIdToIndex[id];
6223
6224 const PointerProperties& curInProperties = inProperties[inIndex];
6225 const PointerCoords& curInCoords = inCoords[inIndex];
6226 PointerProperties& curOutProperties = outProperties[outIndex];
6227 PointerCoords& curOutCoords = outCoords[outIndex];
6228
6229 if (curInProperties != curOutProperties) {
6230 curOutProperties.copyFrom(curInProperties);
6231 changed = true;
6232 }
6233
6234 if (curInCoords != curOutCoords) {
6235 curOutCoords.copyFrom(curInCoords);
6236 changed = true;
6237 }
6238 }
6239 return changed;
6240}
6241
6242void TouchInputMapper::fadePointer() {
6243 if (mPointerController != NULL) {
6244 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6245 }
6246}
6247
Jeff Brownc9aa6282015-02-11 19:03:28 -08006248void TouchInputMapper::cancelTouch(nsecs_t when) {
6249 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006250 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006251}
6252
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6254 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6255 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6256}
6257
6258const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6259 int32_t x, int32_t y) {
6260 size_t numVirtualKeys = mVirtualKeys.size();
6261 for (size_t i = 0; i < numVirtualKeys; i++) {
6262 const VirtualKey& virtualKey = mVirtualKeys[i];
6263
6264#if DEBUG_VIRTUAL_KEYS
6265 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6266 "left=%d, top=%d, right=%d, bottom=%d",
6267 x, y,
6268 virtualKey.keyCode, virtualKey.scanCode,
6269 virtualKey.hitLeft, virtualKey.hitTop,
6270 virtualKey.hitRight, virtualKey.hitBottom);
6271#endif
6272
6273 if (virtualKey.isHit(x, y)) {
6274 return & virtualKey;
6275 }
6276 }
6277
6278 return NULL;
6279}
6280
Michael Wright842500e2015-03-13 17:32:02 -07006281void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6282 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6283 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006284
Michael Wright842500e2015-03-13 17:32:02 -07006285 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006286
6287 if (currentPointerCount == 0) {
6288 // No pointers to assign.
6289 return;
6290 }
6291
6292 if (lastPointerCount == 0) {
6293 // All pointers are new.
6294 for (uint32_t i = 0; i < currentPointerCount; i++) {
6295 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006296 current->rawPointerData.pointers[i].id = id;
6297 current->rawPointerData.idToIndex[id] = i;
6298 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299 }
6300 return;
6301 }
6302
6303 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006304 && current->rawPointerData.pointers[0].toolType
6305 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006306 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006307 uint32_t id = last->rawPointerData.pointers[0].id;
6308 current->rawPointerData.pointers[0].id = id;
6309 current->rawPointerData.idToIndex[id] = 0;
6310 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311 return;
6312 }
6313
6314 // General case.
6315 // We build a heap of squared euclidean distances between current and last pointers
6316 // associated with the current and last pointer indices. Then, we find the best
6317 // match (by distance) for each current pointer.
6318 // The pointers must have the same tool type but it is possible for them to
6319 // transition from hovering to touching or vice-versa while retaining the same id.
6320 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6321
6322 uint32_t heapSize = 0;
6323 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6324 currentPointerIndex++) {
6325 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6326 lastPointerIndex++) {
6327 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006328 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006330 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006331 if (currentPointer.toolType == lastPointer.toolType) {
6332 int64_t deltaX = currentPointer.x - lastPointer.x;
6333 int64_t deltaY = currentPointer.y - lastPointer.y;
6334
6335 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6336
6337 // Insert new element into the heap (sift up).
6338 heap[heapSize].currentPointerIndex = currentPointerIndex;
6339 heap[heapSize].lastPointerIndex = lastPointerIndex;
6340 heap[heapSize].distance = distance;
6341 heapSize += 1;
6342 }
6343 }
6344 }
6345
6346 // Heapify
6347 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6348 startIndex -= 1;
6349 for (uint32_t parentIndex = startIndex; ;) {
6350 uint32_t childIndex = parentIndex * 2 + 1;
6351 if (childIndex >= heapSize) {
6352 break;
6353 }
6354
6355 if (childIndex + 1 < heapSize
6356 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6357 childIndex += 1;
6358 }
6359
6360 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6361 break;
6362 }
6363
6364 swap(heap[parentIndex], heap[childIndex]);
6365 parentIndex = childIndex;
6366 }
6367 }
6368
6369#if DEBUG_POINTER_ASSIGNMENT
6370 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6371 for (size_t i = 0; i < heapSize; i++) {
6372 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6373 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6374 heap[i].distance);
6375 }
6376#endif
6377
6378 // Pull matches out by increasing order of distance.
6379 // To avoid reassigning pointers that have already been matched, the loop keeps track
6380 // of which last and current pointers have been matched using the matchedXXXBits variables.
6381 // It also tracks the used pointer id bits.
6382 BitSet32 matchedLastBits(0);
6383 BitSet32 matchedCurrentBits(0);
6384 BitSet32 usedIdBits(0);
6385 bool first = true;
6386 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6387 while (heapSize > 0) {
6388 if (first) {
6389 // The first time through the loop, we just consume the root element of
6390 // the heap (the one with smallest distance).
6391 first = false;
6392 } else {
6393 // Previous iterations consumed the root element of the heap.
6394 // Pop root element off of the heap (sift down).
6395 heap[0] = heap[heapSize];
6396 for (uint32_t parentIndex = 0; ;) {
6397 uint32_t childIndex = parentIndex * 2 + 1;
6398 if (childIndex >= heapSize) {
6399 break;
6400 }
6401
6402 if (childIndex + 1 < heapSize
6403 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6404 childIndex += 1;
6405 }
6406
6407 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6408 break;
6409 }
6410
6411 swap(heap[parentIndex], heap[childIndex]);
6412 parentIndex = childIndex;
6413 }
6414
6415#if DEBUG_POINTER_ASSIGNMENT
6416 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6417 for (size_t i = 0; i < heapSize; i++) {
6418 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6419 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6420 heap[i].distance);
6421 }
6422#endif
6423 }
6424
6425 heapSize -= 1;
6426
6427 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6428 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6429
6430 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6431 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6432
6433 matchedCurrentBits.markBit(currentPointerIndex);
6434 matchedLastBits.markBit(lastPointerIndex);
6435
Michael Wright842500e2015-03-13 17:32:02 -07006436 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6437 current->rawPointerData.pointers[currentPointerIndex].id = id;
6438 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6439 current->rawPointerData.markIdBit(id,
6440 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006441 usedIdBits.markBit(id);
6442
6443#if DEBUG_POINTER_ASSIGNMENT
6444 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6445 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6446#endif
6447 break;
6448 }
6449 }
6450
6451 // Assign fresh ids to pointers that were not matched in the process.
6452 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6453 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6454 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6455
Michael Wright842500e2015-03-13 17:32:02 -07006456 current->rawPointerData.pointers[currentPointerIndex].id = id;
6457 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6458 current->rawPointerData.markIdBit(id,
6459 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006460
6461#if DEBUG_POINTER_ASSIGNMENT
6462 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6463 currentPointerIndex, id);
6464#endif
6465 }
6466}
6467
6468int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6469 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6470 return AKEY_STATE_VIRTUAL;
6471 }
6472
6473 size_t numVirtualKeys = mVirtualKeys.size();
6474 for (size_t i = 0; i < numVirtualKeys; i++) {
6475 const VirtualKey& virtualKey = mVirtualKeys[i];
6476 if (virtualKey.keyCode == keyCode) {
6477 return AKEY_STATE_UP;
6478 }
6479 }
6480
6481 return AKEY_STATE_UNKNOWN;
6482}
6483
6484int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6485 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6486 return AKEY_STATE_VIRTUAL;
6487 }
6488
6489 size_t numVirtualKeys = mVirtualKeys.size();
6490 for (size_t i = 0; i < numVirtualKeys; i++) {
6491 const VirtualKey& virtualKey = mVirtualKeys[i];
6492 if (virtualKey.scanCode == scanCode) {
6493 return AKEY_STATE_UP;
6494 }
6495 }
6496
6497 return AKEY_STATE_UNKNOWN;
6498}
6499
6500bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6501 const int32_t* keyCodes, uint8_t* outFlags) {
6502 size_t numVirtualKeys = mVirtualKeys.size();
6503 for (size_t i = 0; i < numVirtualKeys; i++) {
6504 const VirtualKey& virtualKey = mVirtualKeys[i];
6505
6506 for (size_t i = 0; i < numCodes; i++) {
6507 if (virtualKey.keyCode == keyCodes[i]) {
6508 outFlags[i] = 1;
6509 }
6510 }
6511 }
6512
6513 return true;
6514}
6515
6516
6517// --- SingleTouchInputMapper ---
6518
6519SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6520 TouchInputMapper(device) {
6521}
6522
6523SingleTouchInputMapper::~SingleTouchInputMapper() {
6524}
6525
6526void SingleTouchInputMapper::reset(nsecs_t when) {
6527 mSingleTouchMotionAccumulator.reset(getDevice());
6528
6529 TouchInputMapper::reset(when);
6530}
6531
6532void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6533 TouchInputMapper::process(rawEvent);
6534
6535 mSingleTouchMotionAccumulator.process(rawEvent);
6536}
6537
Michael Wright842500e2015-03-13 17:32:02 -07006538void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006539 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006540 outState->rawPointerData.pointerCount = 1;
6541 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542
6543 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6544 && (mTouchButtonAccumulator.isHovering()
6545 || (mRawPointerAxes.pressure.valid
6546 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006547 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548
Michael Wright842500e2015-03-13 17:32:02 -07006549 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550 outPointer.id = 0;
6551 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6552 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6553 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6554 outPointer.touchMajor = 0;
6555 outPointer.touchMinor = 0;
6556 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6557 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6558 outPointer.orientation = 0;
6559 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6560 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6561 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6562 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6563 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6564 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6565 }
6566 outPointer.isHovering = isHovering;
6567 }
6568}
6569
6570void SingleTouchInputMapper::configureRawPointerAxes() {
6571 TouchInputMapper::configureRawPointerAxes();
6572
6573 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6574 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6575 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6576 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6577 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6578 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6579 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6580}
6581
6582bool SingleTouchInputMapper::hasStylus() const {
6583 return mTouchButtonAccumulator.hasStylus();
6584}
6585
6586
6587// --- MultiTouchInputMapper ---
6588
6589MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6590 TouchInputMapper(device) {
6591}
6592
6593MultiTouchInputMapper::~MultiTouchInputMapper() {
6594}
6595
6596void MultiTouchInputMapper::reset(nsecs_t when) {
6597 mMultiTouchMotionAccumulator.reset(getDevice());
6598
6599 mPointerIdBits.clear();
6600
6601 TouchInputMapper::reset(when);
6602}
6603
6604void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6605 TouchInputMapper::process(rawEvent);
6606
6607 mMultiTouchMotionAccumulator.process(rawEvent);
6608}
6609
Michael Wright842500e2015-03-13 17:32:02 -07006610void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006611 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6612 size_t outCount = 0;
6613 BitSet32 newPointerIdBits;
6614
6615 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6616 const MultiTouchMotionAccumulator::Slot* inSlot =
6617 mMultiTouchMotionAccumulator.getSlot(inIndex);
6618 if (!inSlot->isInUse()) {
6619 continue;
6620 }
6621
6622 if (outCount >= MAX_POINTERS) {
6623#if DEBUG_POINTERS
6624 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6625 "ignoring the rest.",
6626 getDeviceName().string(), MAX_POINTERS);
6627#endif
6628 break; // too many fingers!
6629 }
6630
Michael Wright842500e2015-03-13 17:32:02 -07006631 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632 outPointer.x = inSlot->getX();
6633 outPointer.y = inSlot->getY();
6634 outPointer.pressure = inSlot->getPressure();
6635 outPointer.touchMajor = inSlot->getTouchMajor();
6636 outPointer.touchMinor = inSlot->getTouchMinor();
6637 outPointer.toolMajor = inSlot->getToolMajor();
6638 outPointer.toolMinor = inSlot->getToolMinor();
6639 outPointer.orientation = inSlot->getOrientation();
6640 outPointer.distance = inSlot->getDistance();
6641 outPointer.tiltX = 0;
6642 outPointer.tiltY = 0;
6643
6644 outPointer.toolType = inSlot->getToolType();
6645 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6646 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6647 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6648 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6649 }
6650 }
6651
6652 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6653 && (mTouchButtonAccumulator.isHovering()
6654 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6655 outPointer.isHovering = isHovering;
6656
6657 // Assign pointer id using tracking id if available.
Michael Wright842500e2015-03-13 17:32:02 -07006658 mHavePointerIds = true;
6659 int32_t trackingId = inSlot->getTrackingId();
6660 int32_t id = -1;
6661 if (trackingId >= 0) {
6662 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6663 uint32_t n = idBits.clearFirstMarkedBit();
6664 if (mPointerTrackingIdMap[n] == trackingId) {
6665 id = n;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666 }
Michael Wright842500e2015-03-13 17:32:02 -07006667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006668
Michael Wright842500e2015-03-13 17:32:02 -07006669 if (id < 0 && !mPointerIdBits.isFull()) {
6670 id = mPointerIdBits.markFirstUnmarkedBit();
6671 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672 }
Michael Wright842500e2015-03-13 17:32:02 -07006673 }
6674 if (id < 0) {
6675 mHavePointerIds = false;
6676 outState->rawPointerData.clearIdBits();
6677 newPointerIdBits.clear();
6678 } else {
6679 outPointer.id = id;
6680 outState->rawPointerData.idToIndex[id] = outCount;
6681 outState->rawPointerData.markIdBit(id, isHovering);
6682 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006683 }
6684
6685 outCount += 1;
6686 }
6687
Michael Wright842500e2015-03-13 17:32:02 -07006688 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006689 mPointerIdBits = newPointerIdBits;
6690
6691 mMultiTouchMotionAccumulator.finishSync();
6692}
6693
6694void MultiTouchInputMapper::configureRawPointerAxes() {
6695 TouchInputMapper::configureRawPointerAxes();
6696
6697 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6698 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6699 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6700 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6701 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6702 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6703 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6704 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6705 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6706 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6707 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6708
6709 if (mRawPointerAxes.trackingId.valid
6710 && mRawPointerAxes.slot.valid
6711 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6712 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6713 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006714 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6715 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006716 getDeviceName().string(), slotCount, MAX_SLOTS);
6717 slotCount = MAX_SLOTS;
6718 }
6719 mMultiTouchMotionAccumulator.configure(getDevice(),
6720 slotCount, true /*usingSlotsProtocol*/);
6721 } else {
6722 mMultiTouchMotionAccumulator.configure(getDevice(),
6723 MAX_POINTERS, false /*usingSlotsProtocol*/);
6724 }
6725}
6726
6727bool MultiTouchInputMapper::hasStylus() const {
6728 return mMultiTouchMotionAccumulator.hasStylus()
6729 || mTouchButtonAccumulator.hasStylus();
6730}
6731
Michael Wright842500e2015-03-13 17:32:02 -07006732// --- ExternalStylusInputMapper
6733
6734ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6735 InputMapper(device) {
6736
6737}
6738
6739uint32_t ExternalStylusInputMapper::getSources() {
6740 return AINPUT_SOURCE_STYLUS;
6741}
6742
6743void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6744 InputMapper::populateDeviceInfo(info);
6745 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6746 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6747}
6748
6749void ExternalStylusInputMapper::dump(String8& dump) {
6750 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6751 dump.append(INDENT3 "Raw Stylus Axes:\n");
6752 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6753 dump.append(INDENT3 "Stylus State:\n");
6754 dumpStylusState(dump, mStylusState);
6755}
6756
6757void ExternalStylusInputMapper::configure(nsecs_t when,
6758 const InputReaderConfiguration* config, uint32_t changes) {
6759 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6760 mTouchButtonAccumulator.configure(getDevice());
6761}
6762
6763void ExternalStylusInputMapper::reset(nsecs_t when) {
6764 InputDevice* device = getDevice();
6765 mSingleTouchMotionAccumulator.reset(device);
6766 mTouchButtonAccumulator.reset(device);
6767 InputMapper::reset(when);
6768}
6769
6770void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6771 mSingleTouchMotionAccumulator.process(rawEvent);
6772 mTouchButtonAccumulator.process(rawEvent);
6773
6774 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6775 sync(rawEvent->when);
6776 }
6777}
6778
6779void ExternalStylusInputMapper::sync(nsecs_t when) {
6780 mStylusState.clear();
6781
6782 mStylusState.when = when;
6783
Michael Wright45ccacf2015-04-21 19:01:58 +01006784 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6785 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6786 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6787 }
6788
Michael Wright842500e2015-03-13 17:32:02 -07006789 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6790 if (mRawPressureAxis.valid) {
6791 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6792 } else if (mTouchButtonAccumulator.isToolActive()) {
6793 mStylusState.pressure = 1.0f;
6794 } else {
6795 mStylusState.pressure = 0.0f;
6796 }
6797
6798 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07006799
6800 mContext->dispatchExternalStylusState(mStylusState);
6801}
6802
Michael Wrightd02c5b62014-02-10 15:10:22 -08006803
6804// --- JoystickInputMapper ---
6805
6806JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6807 InputMapper(device) {
6808}
6809
6810JoystickInputMapper::~JoystickInputMapper() {
6811}
6812
6813uint32_t JoystickInputMapper::getSources() {
6814 return AINPUT_SOURCE_JOYSTICK;
6815}
6816
6817void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6818 InputMapper::populateDeviceInfo(info);
6819
6820 for (size_t i = 0; i < mAxes.size(); i++) {
6821 const Axis& axis = mAxes.valueAt(i);
6822 addMotionRange(axis.axisInfo.axis, axis, info);
6823
6824 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6825 addMotionRange(axis.axisInfo.highAxis, axis, info);
6826
6827 }
6828 }
6829}
6830
6831void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6832 InputDeviceInfo* info) {
6833 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6834 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6835 /* In order to ease the transition for developers from using the old axes
6836 * to the newer, more semantically correct axes, we'll continue to register
6837 * the old axes as duplicates of their corresponding new ones. */
6838 int32_t compatAxis = getCompatAxis(axisId);
6839 if (compatAxis >= 0) {
6840 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6841 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6842 }
6843}
6844
6845/* A mapping from axes the joystick actually has to the axes that should be
6846 * artificially created for compatibility purposes.
6847 * Returns -1 if no compatibility axis is needed. */
6848int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6849 switch(axis) {
6850 case AMOTION_EVENT_AXIS_LTRIGGER:
6851 return AMOTION_EVENT_AXIS_BRAKE;
6852 case AMOTION_EVENT_AXIS_RTRIGGER:
6853 return AMOTION_EVENT_AXIS_GAS;
6854 }
6855 return -1;
6856}
6857
6858void JoystickInputMapper::dump(String8& dump) {
6859 dump.append(INDENT2 "Joystick Input Mapper:\n");
6860
6861 dump.append(INDENT3 "Axes:\n");
6862 size_t numAxes = mAxes.size();
6863 for (size_t i = 0; i < numAxes; i++) {
6864 const Axis& axis = mAxes.valueAt(i);
6865 const char* label = getAxisLabel(axis.axisInfo.axis);
6866 if (label) {
6867 dump.appendFormat(INDENT4 "%s", label);
6868 } else {
6869 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6870 }
6871 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6872 label = getAxisLabel(axis.axisInfo.highAxis);
6873 if (label) {
6874 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6875 } else {
6876 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6877 axis.axisInfo.splitValue);
6878 }
6879 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6880 dump.append(" (invert)");
6881 }
6882
6883 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6884 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6885 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
6886 "highScale=%0.5f, highOffset=%0.5f\n",
6887 axis.scale, axis.offset, axis.highScale, axis.highOffset);
6888 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
6889 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6890 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6891 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6892 }
6893}
6894
6895void JoystickInputMapper::configure(nsecs_t when,
6896 const InputReaderConfiguration* config, uint32_t changes) {
6897 InputMapper::configure(when, config, changes);
6898
6899 if (!changes) { // first time only
6900 // Collect all axes.
6901 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6902 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6903 & INPUT_DEVICE_CLASS_JOYSTICK)) {
6904 continue; // axis must be claimed by a different device
6905 }
6906
6907 RawAbsoluteAxisInfo rawAxisInfo;
6908 getAbsoluteAxisInfo(abs, &rawAxisInfo);
6909 if (rawAxisInfo.valid) {
6910 // Map axis.
6911 AxisInfo axisInfo;
6912 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6913 if (!explicitlyMapped) {
6914 // Axis is not explicitly mapped, will choose a generic axis later.
6915 axisInfo.mode = AxisInfo::MODE_NORMAL;
6916 axisInfo.axis = -1;
6917 }
6918
6919 // Apply flat override.
6920 int32_t rawFlat = axisInfo.flatOverride < 0
6921 ? rawAxisInfo.flat : axisInfo.flatOverride;
6922
6923 // Calculate scaling factors and limits.
6924 Axis axis;
6925 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6926 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6927 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6928 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6929 scale, 0.0f, highScale, 0.0f,
6930 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6931 rawAxisInfo.resolution * scale);
6932 } else if (isCenteredAxis(axisInfo.axis)) {
6933 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6934 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6935 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6936 scale, offset, scale, offset,
6937 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6938 rawAxisInfo.resolution * scale);
6939 } else {
6940 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6941 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6942 scale, 0.0f, scale, 0.0f,
6943 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6944 rawAxisInfo.resolution * scale);
6945 }
6946
6947 // To eliminate noise while the joystick is at rest, filter out small variations
6948 // in axis values up front.
6949 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
6950
6951 mAxes.add(abs, axis);
6952 }
6953 }
6954
6955 // If there are too many axes, start dropping them.
6956 // Prefer to keep explicitly mapped axes.
6957 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006958 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006959 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
6960 pruneAxes(true);
6961 pruneAxes(false);
6962 }
6963
6964 // Assign generic axis ids to remaining axes.
6965 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
6966 size_t numAxes = mAxes.size();
6967 for (size_t i = 0; i < numAxes; i++) {
6968 Axis& axis = mAxes.editValueAt(i);
6969 if (axis.axisInfo.axis < 0) {
6970 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
6971 && haveAxis(nextGenericAxisId)) {
6972 nextGenericAxisId += 1;
6973 }
6974
6975 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
6976 axis.axisInfo.axis = nextGenericAxisId;
6977 nextGenericAxisId += 1;
6978 } else {
6979 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
6980 "have already been assigned to other axes.",
6981 getDeviceName().string(), mAxes.keyAt(i));
6982 mAxes.removeItemsAt(i--);
6983 numAxes -= 1;
6984 }
6985 }
6986 }
6987 }
6988}
6989
6990bool JoystickInputMapper::haveAxis(int32_t axisId) {
6991 size_t numAxes = mAxes.size();
6992 for (size_t i = 0; i < numAxes; i++) {
6993 const Axis& axis = mAxes.valueAt(i);
6994 if (axis.axisInfo.axis == axisId
6995 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
6996 && axis.axisInfo.highAxis == axisId)) {
6997 return true;
6998 }
6999 }
7000 return false;
7001}
7002
7003void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7004 size_t i = mAxes.size();
7005 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7006 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7007 continue;
7008 }
7009 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7010 getDeviceName().string(), mAxes.keyAt(i));
7011 mAxes.removeItemsAt(i);
7012 }
7013}
7014
7015bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7016 switch (axis) {
7017 case AMOTION_EVENT_AXIS_X:
7018 case AMOTION_EVENT_AXIS_Y:
7019 case AMOTION_EVENT_AXIS_Z:
7020 case AMOTION_EVENT_AXIS_RX:
7021 case AMOTION_EVENT_AXIS_RY:
7022 case AMOTION_EVENT_AXIS_RZ:
7023 case AMOTION_EVENT_AXIS_HAT_X:
7024 case AMOTION_EVENT_AXIS_HAT_Y:
7025 case AMOTION_EVENT_AXIS_ORIENTATION:
7026 case AMOTION_EVENT_AXIS_RUDDER:
7027 case AMOTION_EVENT_AXIS_WHEEL:
7028 return true;
7029 default:
7030 return false;
7031 }
7032}
7033
7034void JoystickInputMapper::reset(nsecs_t when) {
7035 // Recenter all axes.
7036 size_t numAxes = mAxes.size();
7037 for (size_t i = 0; i < numAxes; i++) {
7038 Axis& axis = mAxes.editValueAt(i);
7039 axis.resetValue();
7040 }
7041
7042 InputMapper::reset(when);
7043}
7044
7045void JoystickInputMapper::process(const RawEvent* rawEvent) {
7046 switch (rawEvent->type) {
7047 case EV_ABS: {
7048 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7049 if (index >= 0) {
7050 Axis& axis = mAxes.editValueAt(index);
7051 float newValue, highNewValue;
7052 switch (axis.axisInfo.mode) {
7053 case AxisInfo::MODE_INVERT:
7054 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7055 * axis.scale + axis.offset;
7056 highNewValue = 0.0f;
7057 break;
7058 case AxisInfo::MODE_SPLIT:
7059 if (rawEvent->value < axis.axisInfo.splitValue) {
7060 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7061 * axis.scale + axis.offset;
7062 highNewValue = 0.0f;
7063 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7064 newValue = 0.0f;
7065 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7066 * axis.highScale + axis.highOffset;
7067 } else {
7068 newValue = 0.0f;
7069 highNewValue = 0.0f;
7070 }
7071 break;
7072 default:
7073 newValue = rawEvent->value * axis.scale + axis.offset;
7074 highNewValue = 0.0f;
7075 break;
7076 }
7077 axis.newValue = newValue;
7078 axis.highNewValue = highNewValue;
7079 }
7080 break;
7081 }
7082
7083 case EV_SYN:
7084 switch (rawEvent->code) {
7085 case SYN_REPORT:
7086 sync(rawEvent->when, false /*force*/);
7087 break;
7088 }
7089 break;
7090 }
7091}
7092
7093void JoystickInputMapper::sync(nsecs_t when, bool force) {
7094 if (!filterAxes(force)) {
7095 return;
7096 }
7097
7098 int32_t metaState = mContext->getGlobalMetaState();
7099 int32_t buttonState = 0;
7100
7101 PointerProperties pointerProperties;
7102 pointerProperties.clear();
7103 pointerProperties.id = 0;
7104 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7105
7106 PointerCoords pointerCoords;
7107 pointerCoords.clear();
7108
7109 size_t numAxes = mAxes.size();
7110 for (size_t i = 0; i < numAxes; i++) {
7111 const Axis& axis = mAxes.valueAt(i);
7112 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7113 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7114 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7115 axis.highCurrentValue);
7116 }
7117 }
7118
7119 // Moving a joystick axis should not wake the device because joysticks can
7120 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7121 // button will likely wake the device.
7122 // TODO: Use the input device configuration to control this behavior more finely.
7123 uint32_t policyFlags = 0;
7124
7125 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007126 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007127 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7128 getListener()->notifyMotion(&args);
7129}
7130
7131void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7132 int32_t axis, float value) {
7133 pointerCoords->setAxisValue(axis, value);
7134 /* In order to ease the transition for developers from using the old axes
7135 * to the newer, more semantically correct axes, we'll continue to produce
7136 * values for the old axes as mirrors of the value of their corresponding
7137 * new axes. */
7138 int32_t compatAxis = getCompatAxis(axis);
7139 if (compatAxis >= 0) {
7140 pointerCoords->setAxisValue(compatAxis, value);
7141 }
7142}
7143
7144bool JoystickInputMapper::filterAxes(bool force) {
7145 bool atLeastOneSignificantChange = force;
7146 size_t numAxes = mAxes.size();
7147 for (size_t i = 0; i < numAxes; i++) {
7148 Axis& axis = mAxes.editValueAt(i);
7149 if (force || hasValueChangedSignificantly(axis.filter,
7150 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7151 axis.currentValue = axis.newValue;
7152 atLeastOneSignificantChange = true;
7153 }
7154 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7155 if (force || hasValueChangedSignificantly(axis.filter,
7156 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7157 axis.highCurrentValue = axis.highNewValue;
7158 atLeastOneSignificantChange = true;
7159 }
7160 }
7161 }
7162 return atLeastOneSignificantChange;
7163}
7164
7165bool JoystickInputMapper::hasValueChangedSignificantly(
7166 float filter, float newValue, float currentValue, float min, float max) {
7167 if (newValue != currentValue) {
7168 // Filter out small changes in value unless the value is converging on the axis
7169 // bounds or center point. This is intended to reduce the amount of information
7170 // sent to applications by particularly noisy joysticks (such as PS3).
7171 if (fabs(newValue - currentValue) > filter
7172 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7173 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7174 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7175 return true;
7176 }
7177 }
7178 return false;
7179}
7180
7181bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7182 float filter, float newValue, float currentValue, float thresholdValue) {
7183 float newDistance = fabs(newValue - thresholdValue);
7184 if (newDistance < filter) {
7185 float oldDistance = fabs(currentValue - thresholdValue);
7186 if (newDistance < oldDistance) {
7187 return true;
7188 }
7189 }
7190 return false;
7191}
7192
7193} // namespace android