blob: d7329d939f3cbcbc0dd81b74af448f4d7930f430 [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 Malaniac72bbf2015-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)) {
2185 int32_t keyCode;
2186 uint32_t flags;
2187 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, &keyCode, &flags)) {
2188 keyCode = AKEYCODE_UNKNOWN;
2189 flags = 0;
2190 }
2191 processKey(rawEvent->when, rawEvent->value != 0, keyCode, scanCode, flags);
2192 }
2193 break;
2194 }
2195 case EV_MSC: {
2196 if (rawEvent->code == MSC_SCAN) {
2197 mCurrentHidUsage = rawEvent->value;
2198 }
2199 break;
2200 }
2201 case EV_SYN: {
2202 if (rawEvent->code == SYN_REPORT) {
2203 mCurrentHidUsage = 0;
2204 }
2205 }
2206 }
2207}
2208
2209bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2210 return scanCode < BTN_MOUSE
2211 || scanCode >= KEY_OK
2212 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2213 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2214}
2215
2216void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
2217 int32_t scanCode, uint32_t policyFlags) {
2218
2219 if (down) {
2220 // Rotate key codes according to orientation if needed.
2221 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2222 keyCode = rotateKeyCode(keyCode, mOrientation);
2223 }
2224
2225 // Add key down.
2226 ssize_t keyDownIndex = findKeyDown(scanCode);
2227 if (keyDownIndex >= 0) {
2228 // key repeat, be sure to use same keycode as before in case of rotation
2229 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2230 } else {
2231 // key down
2232 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2233 && mContext->shouldDropVirtualKey(when,
2234 getDevice(), keyCode, scanCode)) {
2235 return;
2236 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002237 if (policyFlags & POLICY_FLAG_GESTURE) {
2238 mDevice->cancelTouch(when);
2239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240
2241 mKeyDowns.push();
2242 KeyDown& keyDown = mKeyDowns.editTop();
2243 keyDown.keyCode = keyCode;
2244 keyDown.scanCode = scanCode;
2245 }
2246
2247 mDownTime = when;
2248 } else {
2249 // Remove key down.
2250 ssize_t keyDownIndex = findKeyDown(scanCode);
2251 if (keyDownIndex >= 0) {
2252 // key up, be sure to use same keycode as before in case of rotation
2253 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2254 mKeyDowns.removeAt(size_t(keyDownIndex));
2255 } else {
2256 // key was not actually down
2257 ALOGI("Dropping key up from device %s because the key was not down. "
2258 "keyCode=%d, scanCode=%d",
2259 getDeviceName().string(), keyCode, scanCode);
2260 return;
2261 }
2262 }
2263
2264 int32_t oldMetaState = mMetaState;
2265 int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState);
2266 bool metaStateChanged = oldMetaState != newMetaState;
2267 if (metaStateChanged) {
2268 mMetaState = newMetaState;
2269 updateLedState(false);
2270 }
2271
2272 nsecs_t downTime = mDownTime;
2273
2274 // Key down on external an keyboard should wake the device.
2275 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2276 // For internal keyboards, the key layout file should specify the policy flags for
2277 // each wake key individually.
2278 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright872db4f2014-04-22 15:03:51 -07002279 if (down && getDevice()->isExternal()) {
2280 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002283 if (mParameters.handlesKeyRepeat) {
2284 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2285 }
2286
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 if (metaStateChanged) {
2288 getContext()->updateGlobalMetaState();
2289 }
2290
2291 if (down && !isMetaKey(keyCode)) {
2292 getContext()->fadePointer();
2293 }
2294
2295 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2296 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
2297 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
2298 getListener()->notifyKey(&args);
2299}
2300
2301ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2302 size_t n = mKeyDowns.size();
2303 for (size_t i = 0; i < n; i++) {
2304 if (mKeyDowns[i].scanCode == scanCode) {
2305 return i;
2306 }
2307 }
2308 return -1;
2309}
2310
2311int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2312 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2313}
2314
2315int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2316 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2317}
2318
2319bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2320 const int32_t* keyCodes, uint8_t* outFlags) {
2321 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2322}
2323
2324int32_t KeyboardInputMapper::getMetaState() {
2325 return mMetaState;
2326}
2327
2328void KeyboardInputMapper::resetLedState() {
2329 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2330 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2331 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2332
2333 updateLedState(true);
2334}
2335
2336void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2337 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2338 ledState.on = false;
2339}
2340
2341void KeyboardInputMapper::updateLedState(bool reset) {
2342 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2343 AMETA_CAPS_LOCK_ON, reset);
2344 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2345 AMETA_NUM_LOCK_ON, reset);
2346 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2347 AMETA_SCROLL_LOCK_ON, reset);
2348}
2349
2350void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2351 int32_t led, int32_t modifier, bool reset) {
2352 if (ledState.avail) {
2353 bool desiredState = (mMetaState & modifier) != 0;
2354 if (reset || ledState.on != desiredState) {
2355 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2356 ledState.on = desiredState;
2357 }
2358 }
2359}
2360
2361
2362// --- CursorInputMapper ---
2363
2364CursorInputMapper::CursorInputMapper(InputDevice* device) :
2365 InputMapper(device) {
2366}
2367
2368CursorInputMapper::~CursorInputMapper() {
2369}
2370
2371uint32_t CursorInputMapper::getSources() {
2372 return mSource;
2373}
2374
2375void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2376 InputMapper::populateDeviceInfo(info);
2377
2378 if (mParameters.mode == Parameters::MODE_POINTER) {
2379 float minX, minY, maxX, maxY;
2380 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2381 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2382 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2383 }
2384 } else {
2385 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2386 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2387 }
2388 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2389
2390 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2391 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2392 }
2393 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2394 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2395 }
2396}
2397
2398void CursorInputMapper::dump(String8& dump) {
2399 dump.append(INDENT2 "Cursor Input Mapper:\n");
2400 dumpParameters(dump);
2401 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2402 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2403 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2404 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2405 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2406 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2407 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2408 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2409 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2410 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2411 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2412 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2413 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002414 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415}
2416
2417void CursorInputMapper::configure(nsecs_t when,
2418 const InputReaderConfiguration* config, uint32_t changes) {
2419 InputMapper::configure(when, config, changes);
2420
2421 if (!changes) { // first time only
2422 mCursorScrollAccumulator.configure(getDevice());
2423
2424 // Configure basic parameters.
2425 configureParameters();
2426
2427 // Configure device mode.
2428 switch (mParameters.mode) {
2429 case Parameters::MODE_POINTER:
2430 mSource = AINPUT_SOURCE_MOUSE;
2431 mXPrecision = 1.0f;
2432 mYPrecision = 1.0f;
2433 mXScale = 1.0f;
2434 mYScale = 1.0f;
2435 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2436 break;
2437 case Parameters::MODE_NAVIGATION:
2438 mSource = AINPUT_SOURCE_TRACKBALL;
2439 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2440 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2441 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2442 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2443 break;
2444 }
2445
2446 mVWheelScale = 1.0f;
2447 mHWheelScale = 1.0f;
2448 }
2449
2450 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2451 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2452 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2453 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2454 }
2455
2456 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2457 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2458 DisplayViewport v;
2459 if (config->getDisplayInfo(false /*external*/, &v)) {
2460 mOrientation = v.orientation;
2461 } else {
2462 mOrientation = DISPLAY_ORIENTATION_0;
2463 }
2464 } else {
2465 mOrientation = DISPLAY_ORIENTATION_0;
2466 }
2467 bumpGeneration();
2468 }
2469}
2470
2471void CursorInputMapper::configureParameters() {
2472 mParameters.mode = Parameters::MODE_POINTER;
2473 String8 cursorModeString;
2474 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2475 if (cursorModeString == "navigation") {
2476 mParameters.mode = Parameters::MODE_NAVIGATION;
2477 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2478 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2479 }
2480 }
2481
2482 mParameters.orientationAware = false;
2483 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2484 mParameters.orientationAware);
2485
2486 mParameters.hasAssociatedDisplay = false;
2487 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2488 mParameters.hasAssociatedDisplay = true;
2489 }
2490}
2491
2492void CursorInputMapper::dumpParameters(String8& dump) {
2493 dump.append(INDENT3 "Parameters:\n");
2494 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2495 toString(mParameters.hasAssociatedDisplay));
2496
2497 switch (mParameters.mode) {
2498 case Parameters::MODE_POINTER:
2499 dump.append(INDENT4 "Mode: pointer\n");
2500 break;
2501 case Parameters::MODE_NAVIGATION:
2502 dump.append(INDENT4 "Mode: navigation\n");
2503 break;
2504 default:
2505 ALOG_ASSERT(false);
2506 }
2507
2508 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2509 toString(mParameters.orientationAware));
2510}
2511
2512void CursorInputMapper::reset(nsecs_t when) {
2513 mButtonState = 0;
2514 mDownTime = 0;
2515
2516 mPointerVelocityControl.reset();
2517 mWheelXVelocityControl.reset();
2518 mWheelYVelocityControl.reset();
2519
2520 mCursorButtonAccumulator.reset(getDevice());
2521 mCursorMotionAccumulator.reset(getDevice());
2522 mCursorScrollAccumulator.reset(getDevice());
2523
2524 InputMapper::reset(when);
2525}
2526
2527void CursorInputMapper::process(const RawEvent* rawEvent) {
2528 mCursorButtonAccumulator.process(rawEvent);
2529 mCursorMotionAccumulator.process(rawEvent);
2530 mCursorScrollAccumulator.process(rawEvent);
2531
2532 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2533 sync(rawEvent->when);
2534 }
2535}
2536
2537void CursorInputMapper::sync(nsecs_t when) {
2538 int32_t lastButtonState = mButtonState;
2539 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2540 mButtonState = currentButtonState;
2541
2542 bool wasDown = isPointerDown(lastButtonState);
2543 bool down = isPointerDown(currentButtonState);
2544 bool downChanged;
2545 if (!wasDown && down) {
2546 mDownTime = when;
2547 downChanged = true;
2548 } else if (wasDown && !down) {
2549 downChanged = true;
2550 } else {
2551 downChanged = false;
2552 }
2553 nsecs_t downTime = mDownTime;
2554 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002555 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2556 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557
2558 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2559 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2560 bool moved = deltaX != 0 || deltaY != 0;
2561
2562 // Rotate delta according to orientation if needed.
2563 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2564 && (deltaX != 0.0f || deltaY != 0.0f)) {
2565 rotateDelta(mOrientation, &deltaX, &deltaY);
2566 }
2567
2568 // Move the pointer.
2569 PointerProperties pointerProperties;
2570 pointerProperties.clear();
2571 pointerProperties.id = 0;
2572 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2573
2574 PointerCoords pointerCoords;
2575 pointerCoords.clear();
2576
2577 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2578 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2579 bool scrolled = vscroll != 0 || hscroll != 0;
2580
2581 mWheelYVelocityControl.move(when, NULL, &vscroll);
2582 mWheelXVelocityControl.move(when, &hscroll, NULL);
2583
2584 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2585
2586 int32_t displayId;
2587 if (mPointerController != NULL) {
2588 if (moved || scrolled || buttonsChanged) {
2589 mPointerController->setPresentation(
2590 PointerControllerInterface::PRESENTATION_POINTER);
2591
2592 if (moved) {
2593 mPointerController->move(deltaX, deltaY);
2594 }
2595
2596 if (buttonsChanged) {
2597 mPointerController->setButtonState(currentButtonState);
2598 }
2599
2600 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2601 }
2602
2603 float x, y;
2604 mPointerController->getPosition(&x, &y);
2605 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2606 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2607 displayId = ADISPLAY_ID_DEFAULT;
2608 } else {
2609 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2610 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2611 displayId = ADISPLAY_ID_NONE;
2612 }
2613
2614 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2615
2616 // Moving an external trackball or mouse should wake the device.
2617 // We don't do this for internal cursor devices to prevent them from waking up
2618 // the device in your pocket.
2619 // TODO: Use the input device configuration to control this behavior more finely.
2620 uint32_t policyFlags = 0;
2621 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002622 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 }
2624
2625 // Synthesize key down from buttons if needed.
2626 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2627 policyFlags, lastButtonState, currentButtonState);
2628
2629 // Send motion event.
2630 if (downChanged || moved || scrolled || buttonsChanged) {
2631 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002632 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 int32_t motionEventAction;
2634 if (downChanged) {
2635 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2636 } else if (down || mPointerController == NULL) {
2637 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2638 } else {
2639 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2640 }
2641
Michael Wright7b159c92015-05-14 14:48:03 +01002642 if (buttonsReleased) {
2643 BitSet32 released(buttonsReleased);
2644 while (!released.isEmpty()) {
2645 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2646 buttonState &= ~actionButton;
2647 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2648 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2649 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2650 displayId, 1, &pointerProperties, &pointerCoords,
2651 mXPrecision, mYPrecision, downTime);
2652 getListener()->notifyMotion(&releaseArgs);
2653 }
2654 }
2655
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002657 motionEventAction, 0, 0, metaState, currentButtonState,
2658 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 displayId, 1, &pointerProperties, &pointerCoords,
2660 mXPrecision, mYPrecision, downTime);
2661 getListener()->notifyMotion(&args);
2662
Michael Wright7b159c92015-05-14 14:48:03 +01002663 if (buttonsPressed) {
2664 BitSet32 pressed(buttonsPressed);
2665 while (!pressed.isEmpty()) {
2666 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2667 buttonState |= actionButton;
2668 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2669 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2670 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2671 displayId, 1, &pointerProperties, &pointerCoords,
2672 mXPrecision, mYPrecision, downTime);
2673 getListener()->notifyMotion(&pressArgs);
2674 }
2675 }
2676
2677 ALOG_ASSERT(buttonState == currentButtonState);
2678
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 // Send hover move after UP to tell the application that the mouse is hovering now.
2680 if (motionEventAction == AMOTION_EVENT_ACTION_UP
2681 && mPointerController != NULL) {
2682 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002683 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2685 displayId, 1, &pointerProperties, &pointerCoords,
2686 mXPrecision, mYPrecision, downTime);
2687 getListener()->notifyMotion(&hoverArgs);
2688 }
2689
2690 // Send scroll events.
2691 if (scrolled) {
2692 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2693 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2694
2695 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002696 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 AMOTION_EVENT_EDGE_FLAG_NONE,
2698 displayId, 1, &pointerProperties, &pointerCoords,
2699 mXPrecision, mYPrecision, downTime);
2700 getListener()->notifyMotion(&scrollArgs);
2701 }
2702 }
2703
2704 // Synthesize key up from buttons if needed.
2705 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2706 policyFlags, lastButtonState, currentButtonState);
2707
2708 mCursorMotionAccumulator.finishSync();
2709 mCursorScrollAccumulator.finishSync();
2710}
2711
2712int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2713 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2714 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2715 } else {
2716 return AKEY_STATE_UNKNOWN;
2717 }
2718}
2719
2720void CursorInputMapper::fadePointer() {
2721 if (mPointerController != NULL) {
2722 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2723 }
2724}
2725
Prashant Malaniac72bbf2015-08-11 18:29:28 -07002726// --- RotaryEncoderInputMapper ---
2727
2728RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2729 InputMapper(device) {
2730 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2731}
2732
2733RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2734}
2735
2736uint32_t RotaryEncoderInputMapper::getSources() {
2737 return mSource;
2738}
2739
2740void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2741 InputMapper::populateDeviceInfo(info);
2742
2743 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
2744 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2745 }
2746}
2747
2748void RotaryEncoderInputMapper::dump(String8& dump) {
2749 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2750 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2751 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2752}
2753
2754void RotaryEncoderInputMapper::configure(nsecs_t when,
2755 const InputReaderConfiguration* config, uint32_t changes) {
2756 InputMapper::configure(when, config, changes);
2757 if (!changes) {
2758 mRotaryEncoderScrollAccumulator.configure(getDevice());
2759 }
2760}
2761
2762void RotaryEncoderInputMapper::reset(nsecs_t when) {
2763 mRotaryEncoderScrollAccumulator.reset(getDevice());
2764
2765 InputMapper::reset(when);
2766}
2767
2768void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2769 mRotaryEncoderScrollAccumulator.process(rawEvent);
2770
2771 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2772 sync(rawEvent->when);
2773 }
2774}
2775
2776void RotaryEncoderInputMapper::sync(nsecs_t when) {
2777 PointerCoords pointerCoords;
2778 pointerCoords.clear();
2779
2780 PointerProperties pointerProperties;
2781 pointerProperties.clear();
2782 pointerProperties.id = 0;
2783 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2784
2785 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2786 bool scrolled = scroll != 0;
2787
2788 // This is not a pointer, so it's not associated with a display.
2789 int32_t displayId = ADISPLAY_ID_NONE;
2790
2791 // Moving the rotary encoder should wake the device (if specified).
2792 uint32_t policyFlags = 0;
2793 if (scrolled && getDevice()->isExternal()) {
2794 policyFlags |= POLICY_FLAG_WAKE;
2795 }
2796
2797 // Send motion event.
2798 if (scrolled) {
2799 int32_t metaState = mContext->getGlobalMetaState();
2800 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll);
2801
2802 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2803 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2804 AMOTION_EVENT_EDGE_FLAG_NONE,
2805 displayId, 1, &pointerProperties, &pointerCoords,
2806 0, 0, 0);
2807 getListener()->notifyMotion(&scrollArgs);
2808 }
2809
2810 mRotaryEncoderScrollAccumulator.finishSync();
2811}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812
2813// --- TouchInputMapper ---
2814
2815TouchInputMapper::TouchInputMapper(InputDevice* device) :
2816 InputMapper(device),
2817 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2818 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2819 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2820}
2821
2822TouchInputMapper::~TouchInputMapper() {
2823}
2824
2825uint32_t TouchInputMapper::getSources() {
2826 return mSource;
2827}
2828
2829void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2830 InputMapper::populateDeviceInfo(info);
2831
2832 if (mDeviceMode != DEVICE_MODE_DISABLED) {
2833 info->addMotionRange(mOrientedRanges.x);
2834 info->addMotionRange(mOrientedRanges.y);
2835 info->addMotionRange(mOrientedRanges.pressure);
2836
2837 if (mOrientedRanges.haveSize) {
2838 info->addMotionRange(mOrientedRanges.size);
2839 }
2840
2841 if (mOrientedRanges.haveTouchSize) {
2842 info->addMotionRange(mOrientedRanges.touchMajor);
2843 info->addMotionRange(mOrientedRanges.touchMinor);
2844 }
2845
2846 if (mOrientedRanges.haveToolSize) {
2847 info->addMotionRange(mOrientedRanges.toolMajor);
2848 info->addMotionRange(mOrientedRanges.toolMinor);
2849 }
2850
2851 if (mOrientedRanges.haveOrientation) {
2852 info->addMotionRange(mOrientedRanges.orientation);
2853 }
2854
2855 if (mOrientedRanges.haveDistance) {
2856 info->addMotionRange(mOrientedRanges.distance);
2857 }
2858
2859 if (mOrientedRanges.haveTilt) {
2860 info->addMotionRange(mOrientedRanges.tilt);
2861 }
2862
2863 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2864 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2865 0.0f);
2866 }
2867 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2868 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2869 0.0f);
2870 }
2871 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2872 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2873 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2874 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2875 x.fuzz, x.resolution);
2876 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2877 y.fuzz, y.resolution);
2878 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2879 x.fuzz, x.resolution);
2880 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2881 y.fuzz, y.resolution);
2882 }
2883 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2884 }
2885}
2886
2887void TouchInputMapper::dump(String8& dump) {
2888 dump.append(INDENT2 "Touch Input Mapper:\n");
2889 dumpParameters(dump);
2890 dumpVirtualKeys(dump);
2891 dumpRawPointerAxes(dump);
2892 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07002893 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 dumpSurface(dump);
2895
2896 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2897 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2898 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2899 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2900 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2901 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
2902 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
2903 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
2904 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
2905 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
2906 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
2907 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
2908 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
2909 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
2910 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
2911 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
2912 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
2913
Michael Wright7b159c92015-05-14 14:48:03 +01002914 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07002916 mLastRawState.rawPointerData.pointerCount);
2917 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
2918 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
2920 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
2921 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
2922 "toolType=%d, isHovering=%s\n", i,
2923 pointer.id, pointer.x, pointer.y, pointer.pressure,
2924 pointer.touchMajor, pointer.touchMinor,
2925 pointer.toolMajor, pointer.toolMinor,
2926 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
2927 pointer.toolType, toString(pointer.isHovering));
2928 }
2929
Michael Wright7b159c92015-05-14 14:48:03 +01002930 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07002932 mLastCookedState.cookedPointerData.pointerCount);
2933 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
2934 const PointerProperties& pointerProperties =
2935 mLastCookedState.cookedPointerData.pointerProperties[i];
2936 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
2938 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
2939 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
2940 "toolType=%d, isHovering=%s\n", i,
2941 pointerProperties.id,
2942 pointerCoords.getX(),
2943 pointerCoords.getY(),
2944 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2945 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2946 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2947 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2948 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2949 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
2950 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
2951 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
2952 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07002953 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 }
2955
Michael Wright842500e2015-03-13 17:32:02 -07002956 dump.append(INDENT3 "Stylus Fusion:\n");
2957 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
2958 toString(mExternalStylusConnected));
2959 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
2960 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01002961 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07002962 dump.append(INDENT3 "External Stylus State:\n");
2963 dumpStylusState(dump, mExternalStylusState);
2964
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 if (mDeviceMode == DEVICE_MODE_POINTER) {
2966 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
2967 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
2968 mPointerXMovementScale);
2969 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
2970 mPointerYMovementScale);
2971 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
2972 mPointerXZoomScale);
2973 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
2974 mPointerYZoomScale);
2975 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
2976 mPointerGestureMaxSwipeWidth);
2977 }
2978}
2979
2980void TouchInputMapper::configure(nsecs_t when,
2981 const InputReaderConfiguration* config, uint32_t changes) {
2982 InputMapper::configure(when, config, changes);
2983
2984 mConfig = *config;
2985
2986 if (!changes) { // first time only
2987 // Configure basic parameters.
2988 configureParameters();
2989
2990 // Configure common accumulators.
2991 mCursorScrollAccumulator.configure(getDevice());
2992 mTouchButtonAccumulator.configure(getDevice());
2993
2994 // Configure absolute axis information.
2995 configureRawPointerAxes();
2996
2997 // Prepare input device calibration.
2998 parseCalibration();
2999 resolveCalibration();
3000 }
3001
Michael Wright842500e2015-03-13 17:32:02 -07003002 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003003 // Update location calibration to reflect current settings
3004 updateAffineTransformation();
3005 }
3006
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3008 // Update pointer speed.
3009 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3010 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3011 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3012 }
3013
3014 bool resetNeeded = false;
3015 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3016 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003017 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3018 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 // Configure device sources, surface dimensions, orientation and
3020 // scaling factors.
3021 configureSurface(when, &resetNeeded);
3022 }
3023
3024 if (changes && resetNeeded) {
3025 // Send reset, unless this is the first time the device has been configured,
3026 // in which case the reader will call reset itself after all mappers are ready.
3027 getDevice()->notifyReset(when);
3028 }
3029}
3030
Michael Wright842500e2015-03-13 17:32:02 -07003031void TouchInputMapper::resolveExternalStylusPresence() {
3032 Vector<InputDeviceInfo> devices;
3033 mContext->getExternalStylusDevices(devices);
3034 mExternalStylusConnected = !devices.isEmpty();
3035
3036 if (!mExternalStylusConnected) {
3037 resetExternalStylus();
3038 }
3039}
3040
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041void TouchInputMapper::configureParameters() {
3042 // Use the pointer presentation mode for devices that do not support distinct
3043 // multitouch. The spot-based presentation relies on being able to accurately
3044 // locate two or more fingers on the touch pad.
3045 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
3046 ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
3047
3048 String8 gestureModeString;
3049 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3050 gestureModeString)) {
3051 if (gestureModeString == "pointer") {
3052 mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
3053 } else if (gestureModeString == "spots") {
3054 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
3055 } else if (gestureModeString != "default") {
3056 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3057 }
3058 }
3059
3060 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3061 // The device is a touch screen.
3062 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3063 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3064 // The device is a pointing device like a track pad.
3065 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3066 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3067 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3068 // The device is a cursor device with a touch pad attached.
3069 // By default don't use the touch pad to move the pointer.
3070 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3071 } else {
3072 // The device is a touch pad of unknown purpose.
3073 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3074 }
3075
3076 mParameters.hasButtonUnderPad=
3077 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3078
3079 String8 deviceTypeString;
3080 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3081 deviceTypeString)) {
3082 if (deviceTypeString == "touchScreen") {
3083 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3084 } else if (deviceTypeString == "touchPad") {
3085 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3086 } else if (deviceTypeString == "touchNavigation") {
3087 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3088 } else if (deviceTypeString == "pointer") {
3089 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3090 } else if (deviceTypeString != "default") {
3091 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3092 }
3093 }
3094
3095 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3096 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3097 mParameters.orientationAware);
3098
3099 mParameters.hasAssociatedDisplay = false;
3100 mParameters.associatedDisplayIsExternal = false;
3101 if (mParameters.orientationAware
3102 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3103 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3104 mParameters.hasAssociatedDisplay = true;
3105 mParameters.associatedDisplayIsExternal =
3106 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3107 && getDevice()->isExternal();
3108 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003109
3110 // Initial downs on external touch devices should wake the device.
3111 // Normally we don't do this for internal touch screens to prevent them from waking
3112 // up in your pocket but you can enable it using the input device configuration.
3113 mParameters.wake = getDevice()->isExternal();
3114 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3115 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116}
3117
3118void TouchInputMapper::dumpParameters(String8& dump) {
3119 dump.append(INDENT3 "Parameters:\n");
3120
3121 switch (mParameters.gestureMode) {
3122 case Parameters::GESTURE_MODE_POINTER:
3123 dump.append(INDENT4 "GestureMode: pointer\n");
3124 break;
3125 case Parameters::GESTURE_MODE_SPOTS:
3126 dump.append(INDENT4 "GestureMode: spots\n");
3127 break;
3128 default:
3129 assert(false);
3130 }
3131
3132 switch (mParameters.deviceType) {
3133 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3134 dump.append(INDENT4 "DeviceType: touchScreen\n");
3135 break;
3136 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3137 dump.append(INDENT4 "DeviceType: touchPad\n");
3138 break;
3139 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3140 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3141 break;
3142 case Parameters::DEVICE_TYPE_POINTER:
3143 dump.append(INDENT4 "DeviceType: pointer\n");
3144 break;
3145 default:
3146 ALOG_ASSERT(false);
3147 }
3148
3149 dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
3150 toString(mParameters.hasAssociatedDisplay),
3151 toString(mParameters.associatedDisplayIsExternal));
3152 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3153 toString(mParameters.orientationAware));
3154}
3155
3156void TouchInputMapper::configureRawPointerAxes() {
3157 mRawPointerAxes.clear();
3158}
3159
3160void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3161 dump.append(INDENT3 "Raw Touch Axes:\n");
3162 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3163 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3164 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3165 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3166 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3167 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3168 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3169 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3170 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3171 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3172 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3173 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3174 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3175}
3176
Michael Wright842500e2015-03-13 17:32:02 -07003177bool TouchInputMapper::hasExternalStylus() const {
3178 return mExternalStylusConnected;
3179}
3180
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3182 int32_t oldDeviceMode = mDeviceMode;
3183
Michael Wright842500e2015-03-13 17:32:02 -07003184 resolveExternalStylusPresence();
3185
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 // Determine device mode.
3187 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3188 && mConfig.pointerGesturesEnabled) {
3189 mSource = AINPUT_SOURCE_MOUSE;
3190 mDeviceMode = DEVICE_MODE_POINTER;
3191 if (hasStylus()) {
3192 mSource |= AINPUT_SOURCE_STYLUS;
3193 }
3194 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3195 && mParameters.hasAssociatedDisplay) {
3196 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3197 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003198 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 mSource |= AINPUT_SOURCE_STYLUS;
3200 }
Michael Wright2f78b682015-06-12 15:25:08 +01003201 if (hasExternalStylus()) {
3202 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3205 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3206 mDeviceMode = DEVICE_MODE_NAVIGATION;
3207 } else {
3208 mSource = AINPUT_SOURCE_TOUCHPAD;
3209 mDeviceMode = DEVICE_MODE_UNSCALED;
3210 }
3211
3212 // Ensure we have valid X and Y axes.
3213 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3214 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3215 "The device will be inoperable.", getDeviceName().string());
3216 mDeviceMode = DEVICE_MODE_DISABLED;
3217 return;
3218 }
3219
3220 // Raw width and height in the natural orientation.
3221 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3222 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3223
3224 // Get associated display dimensions.
3225 DisplayViewport newViewport;
3226 if (mParameters.hasAssociatedDisplay) {
3227 if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
3228 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3229 "display. The device will be inoperable until the display size "
3230 "becomes available.",
3231 getDeviceName().string());
3232 mDeviceMode = DEVICE_MODE_DISABLED;
3233 return;
3234 }
3235 } else {
3236 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3237 }
3238 bool viewportChanged = mViewport != newViewport;
3239 if (viewportChanged) {
3240 mViewport = newViewport;
3241
3242 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3243 // Convert rotated viewport to natural surface coordinates.
3244 int32_t naturalLogicalWidth, naturalLogicalHeight;
3245 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3246 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3247 int32_t naturalDeviceWidth, naturalDeviceHeight;
3248 switch (mViewport.orientation) {
3249 case DISPLAY_ORIENTATION_90:
3250 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3251 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3252 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3253 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3254 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3255 naturalPhysicalTop = mViewport.physicalLeft;
3256 naturalDeviceWidth = mViewport.deviceHeight;
3257 naturalDeviceHeight = mViewport.deviceWidth;
3258 break;
3259 case DISPLAY_ORIENTATION_180:
3260 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3261 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3262 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3263 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3264 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3265 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3266 naturalDeviceWidth = mViewport.deviceWidth;
3267 naturalDeviceHeight = mViewport.deviceHeight;
3268 break;
3269 case DISPLAY_ORIENTATION_270:
3270 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3271 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3272 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3273 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3274 naturalPhysicalLeft = mViewport.physicalTop;
3275 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3276 naturalDeviceWidth = mViewport.deviceHeight;
3277 naturalDeviceHeight = mViewport.deviceWidth;
3278 break;
3279 case DISPLAY_ORIENTATION_0:
3280 default:
3281 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3282 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3283 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3284 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3285 naturalPhysicalLeft = mViewport.physicalLeft;
3286 naturalPhysicalTop = mViewport.physicalTop;
3287 naturalDeviceWidth = mViewport.deviceWidth;
3288 naturalDeviceHeight = mViewport.deviceHeight;
3289 break;
3290 }
3291
3292 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3293 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3294 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3295 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3296
3297 mSurfaceOrientation = mParameters.orientationAware ?
3298 mViewport.orientation : DISPLAY_ORIENTATION_0;
3299 } else {
3300 mSurfaceWidth = rawWidth;
3301 mSurfaceHeight = rawHeight;
3302 mSurfaceLeft = 0;
3303 mSurfaceTop = 0;
3304 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3305 }
3306 }
3307
3308 // If moving between pointer modes, need to reset some state.
3309 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3310 if (deviceModeChanged) {
3311 mOrientedRanges.clear();
3312 }
3313
3314 // Create pointer controller if needed.
3315 if (mDeviceMode == DEVICE_MODE_POINTER ||
3316 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3317 if (mPointerController == NULL) {
3318 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3319 }
3320 } else {
3321 mPointerController.clear();
3322 }
3323
3324 if (viewportChanged || deviceModeChanged) {
3325 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3326 "display id %d",
3327 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3328 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3329
3330 // Configure X and Y factors.
3331 mXScale = float(mSurfaceWidth) / rawWidth;
3332 mYScale = float(mSurfaceHeight) / rawHeight;
3333 mXTranslate = -mSurfaceLeft;
3334 mYTranslate = -mSurfaceTop;
3335 mXPrecision = 1.0f / mXScale;
3336 mYPrecision = 1.0f / mYScale;
3337
3338 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3339 mOrientedRanges.x.source = mSource;
3340 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3341 mOrientedRanges.y.source = mSource;
3342
3343 configureVirtualKeys();
3344
3345 // Scale factor for terms that are not oriented in a particular axis.
3346 // If the pixels are square then xScale == yScale otherwise we fake it
3347 // by choosing an average.
3348 mGeometricScale = avg(mXScale, mYScale);
3349
3350 // Size of diagonal axis.
3351 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3352
3353 // Size factors.
3354 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3355 if (mRawPointerAxes.touchMajor.valid
3356 && mRawPointerAxes.touchMajor.maxValue != 0) {
3357 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3358 } else if (mRawPointerAxes.toolMajor.valid
3359 && mRawPointerAxes.toolMajor.maxValue != 0) {
3360 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3361 } else {
3362 mSizeScale = 0.0f;
3363 }
3364
3365 mOrientedRanges.haveTouchSize = true;
3366 mOrientedRanges.haveToolSize = true;
3367 mOrientedRanges.haveSize = true;
3368
3369 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3370 mOrientedRanges.touchMajor.source = mSource;
3371 mOrientedRanges.touchMajor.min = 0;
3372 mOrientedRanges.touchMajor.max = diagonalSize;
3373 mOrientedRanges.touchMajor.flat = 0;
3374 mOrientedRanges.touchMajor.fuzz = 0;
3375 mOrientedRanges.touchMajor.resolution = 0;
3376
3377 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3378 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3379
3380 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3381 mOrientedRanges.toolMajor.source = mSource;
3382 mOrientedRanges.toolMajor.min = 0;
3383 mOrientedRanges.toolMajor.max = diagonalSize;
3384 mOrientedRanges.toolMajor.flat = 0;
3385 mOrientedRanges.toolMajor.fuzz = 0;
3386 mOrientedRanges.toolMajor.resolution = 0;
3387
3388 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3389 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3390
3391 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3392 mOrientedRanges.size.source = mSource;
3393 mOrientedRanges.size.min = 0;
3394 mOrientedRanges.size.max = 1.0;
3395 mOrientedRanges.size.flat = 0;
3396 mOrientedRanges.size.fuzz = 0;
3397 mOrientedRanges.size.resolution = 0;
3398 } else {
3399 mSizeScale = 0.0f;
3400 }
3401
3402 // Pressure factors.
3403 mPressureScale = 0;
3404 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3405 || mCalibration.pressureCalibration
3406 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3407 if (mCalibration.havePressureScale) {
3408 mPressureScale = mCalibration.pressureScale;
3409 } else if (mRawPointerAxes.pressure.valid
3410 && mRawPointerAxes.pressure.maxValue != 0) {
3411 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3412 }
3413 }
3414
3415 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3416 mOrientedRanges.pressure.source = mSource;
3417 mOrientedRanges.pressure.min = 0;
3418 mOrientedRanges.pressure.max = 1.0;
3419 mOrientedRanges.pressure.flat = 0;
3420 mOrientedRanges.pressure.fuzz = 0;
3421 mOrientedRanges.pressure.resolution = 0;
3422
3423 // Tilt
3424 mTiltXCenter = 0;
3425 mTiltXScale = 0;
3426 mTiltYCenter = 0;
3427 mTiltYScale = 0;
3428 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3429 if (mHaveTilt) {
3430 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3431 mRawPointerAxes.tiltX.maxValue);
3432 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3433 mRawPointerAxes.tiltY.maxValue);
3434 mTiltXScale = M_PI / 180;
3435 mTiltYScale = M_PI / 180;
3436
3437 mOrientedRanges.haveTilt = true;
3438
3439 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3440 mOrientedRanges.tilt.source = mSource;
3441 mOrientedRanges.tilt.min = 0;
3442 mOrientedRanges.tilt.max = M_PI_2;
3443 mOrientedRanges.tilt.flat = 0;
3444 mOrientedRanges.tilt.fuzz = 0;
3445 mOrientedRanges.tilt.resolution = 0;
3446 }
3447
3448 // Orientation
3449 mOrientationScale = 0;
3450 if (mHaveTilt) {
3451 mOrientedRanges.haveOrientation = true;
3452
3453 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3454 mOrientedRanges.orientation.source = mSource;
3455 mOrientedRanges.orientation.min = -M_PI;
3456 mOrientedRanges.orientation.max = M_PI;
3457 mOrientedRanges.orientation.flat = 0;
3458 mOrientedRanges.orientation.fuzz = 0;
3459 mOrientedRanges.orientation.resolution = 0;
3460 } else if (mCalibration.orientationCalibration !=
3461 Calibration::ORIENTATION_CALIBRATION_NONE) {
3462 if (mCalibration.orientationCalibration
3463 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3464 if (mRawPointerAxes.orientation.valid) {
3465 if (mRawPointerAxes.orientation.maxValue > 0) {
3466 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3467 } else if (mRawPointerAxes.orientation.minValue < 0) {
3468 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3469 } else {
3470 mOrientationScale = 0;
3471 }
3472 }
3473 }
3474
3475 mOrientedRanges.haveOrientation = true;
3476
3477 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3478 mOrientedRanges.orientation.source = mSource;
3479 mOrientedRanges.orientation.min = -M_PI_2;
3480 mOrientedRanges.orientation.max = M_PI_2;
3481 mOrientedRanges.orientation.flat = 0;
3482 mOrientedRanges.orientation.fuzz = 0;
3483 mOrientedRanges.orientation.resolution = 0;
3484 }
3485
3486 // Distance
3487 mDistanceScale = 0;
3488 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3489 if (mCalibration.distanceCalibration
3490 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3491 if (mCalibration.haveDistanceScale) {
3492 mDistanceScale = mCalibration.distanceScale;
3493 } else {
3494 mDistanceScale = 1.0f;
3495 }
3496 }
3497
3498 mOrientedRanges.haveDistance = true;
3499
3500 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3501 mOrientedRanges.distance.source = mSource;
3502 mOrientedRanges.distance.min =
3503 mRawPointerAxes.distance.minValue * mDistanceScale;
3504 mOrientedRanges.distance.max =
3505 mRawPointerAxes.distance.maxValue * mDistanceScale;
3506 mOrientedRanges.distance.flat = 0;
3507 mOrientedRanges.distance.fuzz =
3508 mRawPointerAxes.distance.fuzz * mDistanceScale;
3509 mOrientedRanges.distance.resolution = 0;
3510 }
3511
3512 // Compute oriented precision, scales and ranges.
3513 // Note that the maximum value reported is an inclusive maximum value so it is one
3514 // unit less than the total width or height of surface.
3515 switch (mSurfaceOrientation) {
3516 case DISPLAY_ORIENTATION_90:
3517 case DISPLAY_ORIENTATION_270:
3518 mOrientedXPrecision = mYPrecision;
3519 mOrientedYPrecision = mXPrecision;
3520
3521 mOrientedRanges.x.min = mYTranslate;
3522 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3523 mOrientedRanges.x.flat = 0;
3524 mOrientedRanges.x.fuzz = 0;
3525 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3526
3527 mOrientedRanges.y.min = mXTranslate;
3528 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3529 mOrientedRanges.y.flat = 0;
3530 mOrientedRanges.y.fuzz = 0;
3531 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3532 break;
3533
3534 default:
3535 mOrientedXPrecision = mXPrecision;
3536 mOrientedYPrecision = mYPrecision;
3537
3538 mOrientedRanges.x.min = mXTranslate;
3539 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3540 mOrientedRanges.x.flat = 0;
3541 mOrientedRanges.x.fuzz = 0;
3542 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3543
3544 mOrientedRanges.y.min = mYTranslate;
3545 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3546 mOrientedRanges.y.flat = 0;
3547 mOrientedRanges.y.fuzz = 0;
3548 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3549 break;
3550 }
3551
Jason Gerecke71b16e82014-03-10 09:47:59 -07003552 // Location
3553 updateAffineTransformation();
3554
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 if (mDeviceMode == DEVICE_MODE_POINTER) {
3556 // Compute pointer gesture detection parameters.
3557 float rawDiagonal = hypotf(rawWidth, rawHeight);
3558 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3559
3560 // Scale movements such that one whole swipe of the touch pad covers a
3561 // given area relative to the diagonal size of the display when no acceleration
3562 // is applied.
3563 // Assume that the touch pad has a square aspect ratio such that movements in
3564 // X and Y of the same number of raw units cover the same physical distance.
3565 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3566 * displayDiagonal / rawDiagonal;
3567 mPointerYMovementScale = mPointerXMovementScale;
3568
3569 // Scale zooms to cover a smaller range of the display than movements do.
3570 // This value determines the area around the pointer that is affected by freeform
3571 // pointer gestures.
3572 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3573 * displayDiagonal / rawDiagonal;
3574 mPointerYZoomScale = mPointerXZoomScale;
3575
3576 // Max width between pointers to detect a swipe gesture is more than some fraction
3577 // of the diagonal axis of the touch pad. Touches that are wider than this are
3578 // translated into freeform gestures.
3579 mPointerGestureMaxSwipeWidth =
3580 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3581
3582 // Abort current pointer usages because the state has changed.
3583 abortPointerUsage(when, 0 /*policyFlags*/);
3584 }
3585
3586 // Inform the dispatcher about the changes.
3587 *outResetNeeded = true;
3588 bumpGeneration();
3589 }
3590}
3591
3592void TouchInputMapper::dumpSurface(String8& dump) {
3593 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3594 "logicalFrame=[%d, %d, %d, %d], "
3595 "physicalFrame=[%d, %d, %d, %d], "
3596 "deviceSize=[%d, %d]\n",
3597 mViewport.displayId, mViewport.orientation,
3598 mViewport.logicalLeft, mViewport.logicalTop,
3599 mViewport.logicalRight, mViewport.logicalBottom,
3600 mViewport.physicalLeft, mViewport.physicalTop,
3601 mViewport.physicalRight, mViewport.physicalBottom,
3602 mViewport.deviceWidth, mViewport.deviceHeight);
3603
3604 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3605 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3606 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3607 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3608 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3609}
3610
3611void TouchInputMapper::configureVirtualKeys() {
3612 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3613 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3614
3615 mVirtualKeys.clear();
3616
3617 if (virtualKeyDefinitions.size() == 0) {
3618 return;
3619 }
3620
3621 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3622
3623 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3624 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3625 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3626 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3627
3628 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3629 const VirtualKeyDefinition& virtualKeyDefinition =
3630 virtualKeyDefinitions[i];
3631
3632 mVirtualKeys.add();
3633 VirtualKey& virtualKey = mVirtualKeys.editTop();
3634
3635 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3636 int32_t keyCode;
3637 uint32_t flags;
3638 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, &keyCode, &flags)) {
3639 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3640 virtualKey.scanCode);
3641 mVirtualKeys.pop(); // drop the key
3642 continue;
3643 }
3644
3645 virtualKey.keyCode = keyCode;
3646 virtualKey.flags = flags;
3647
3648 // convert the key definition's display coordinates into touch coordinates for a hit box
3649 int32_t halfWidth = virtualKeyDefinition.width / 2;
3650 int32_t halfHeight = virtualKeyDefinition.height / 2;
3651
3652 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3653 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3654 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3655 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3656 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3657 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3658 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3659 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3660 }
3661}
3662
3663void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3664 if (!mVirtualKeys.isEmpty()) {
3665 dump.append(INDENT3 "Virtual Keys:\n");
3666
3667 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3668 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003669 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3671 i, virtualKey.scanCode, virtualKey.keyCode,
3672 virtualKey.hitLeft, virtualKey.hitRight,
3673 virtualKey.hitTop, virtualKey.hitBottom);
3674 }
3675 }
3676}
3677
3678void TouchInputMapper::parseCalibration() {
3679 const PropertyMap& in = getDevice()->getConfiguration();
3680 Calibration& out = mCalibration;
3681
3682 // Size
3683 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3684 String8 sizeCalibrationString;
3685 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3686 if (sizeCalibrationString == "none") {
3687 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3688 } else if (sizeCalibrationString == "geometric") {
3689 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3690 } else if (sizeCalibrationString == "diameter") {
3691 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3692 } else if (sizeCalibrationString == "box") {
3693 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3694 } else if (sizeCalibrationString == "area") {
3695 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3696 } else if (sizeCalibrationString != "default") {
3697 ALOGW("Invalid value for touch.size.calibration: '%s'",
3698 sizeCalibrationString.string());
3699 }
3700 }
3701
3702 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3703 out.sizeScale);
3704 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3705 out.sizeBias);
3706 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3707 out.sizeIsSummed);
3708
3709 // Pressure
3710 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3711 String8 pressureCalibrationString;
3712 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3713 if (pressureCalibrationString == "none") {
3714 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3715 } else if (pressureCalibrationString == "physical") {
3716 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3717 } else if (pressureCalibrationString == "amplitude") {
3718 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3719 } else if (pressureCalibrationString != "default") {
3720 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3721 pressureCalibrationString.string());
3722 }
3723 }
3724
3725 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3726 out.pressureScale);
3727
3728 // Orientation
3729 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3730 String8 orientationCalibrationString;
3731 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3732 if (orientationCalibrationString == "none") {
3733 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3734 } else if (orientationCalibrationString == "interpolated") {
3735 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3736 } else if (orientationCalibrationString == "vector") {
3737 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3738 } else if (orientationCalibrationString != "default") {
3739 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3740 orientationCalibrationString.string());
3741 }
3742 }
3743
3744 // Distance
3745 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3746 String8 distanceCalibrationString;
3747 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3748 if (distanceCalibrationString == "none") {
3749 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3750 } else if (distanceCalibrationString == "scaled") {
3751 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3752 } else if (distanceCalibrationString != "default") {
3753 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3754 distanceCalibrationString.string());
3755 }
3756 }
3757
3758 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3759 out.distanceScale);
3760
3761 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3762 String8 coverageCalibrationString;
3763 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3764 if (coverageCalibrationString == "none") {
3765 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3766 } else if (coverageCalibrationString == "box") {
3767 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3768 } else if (coverageCalibrationString != "default") {
3769 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3770 coverageCalibrationString.string());
3771 }
3772 }
3773}
3774
3775void TouchInputMapper::resolveCalibration() {
3776 // Size
3777 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3778 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3779 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3780 }
3781 } else {
3782 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3783 }
3784
3785 // Pressure
3786 if (mRawPointerAxes.pressure.valid) {
3787 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3788 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3789 }
3790 } else {
3791 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3792 }
3793
3794 // Orientation
3795 if (mRawPointerAxes.orientation.valid) {
3796 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3797 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3798 }
3799 } else {
3800 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3801 }
3802
3803 // Distance
3804 if (mRawPointerAxes.distance.valid) {
3805 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3806 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3807 }
3808 } else {
3809 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3810 }
3811
3812 // Coverage
3813 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3814 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3815 }
3816}
3817
3818void TouchInputMapper::dumpCalibration(String8& dump) {
3819 dump.append(INDENT3 "Calibration:\n");
3820
3821 // Size
3822 switch (mCalibration.sizeCalibration) {
3823 case Calibration::SIZE_CALIBRATION_NONE:
3824 dump.append(INDENT4 "touch.size.calibration: none\n");
3825 break;
3826 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3827 dump.append(INDENT4 "touch.size.calibration: geometric\n");
3828 break;
3829 case Calibration::SIZE_CALIBRATION_DIAMETER:
3830 dump.append(INDENT4 "touch.size.calibration: diameter\n");
3831 break;
3832 case Calibration::SIZE_CALIBRATION_BOX:
3833 dump.append(INDENT4 "touch.size.calibration: box\n");
3834 break;
3835 case Calibration::SIZE_CALIBRATION_AREA:
3836 dump.append(INDENT4 "touch.size.calibration: area\n");
3837 break;
3838 default:
3839 ALOG_ASSERT(false);
3840 }
3841
3842 if (mCalibration.haveSizeScale) {
3843 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3844 mCalibration.sizeScale);
3845 }
3846
3847 if (mCalibration.haveSizeBias) {
3848 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3849 mCalibration.sizeBias);
3850 }
3851
3852 if (mCalibration.haveSizeIsSummed) {
3853 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3854 toString(mCalibration.sizeIsSummed));
3855 }
3856
3857 // Pressure
3858 switch (mCalibration.pressureCalibration) {
3859 case Calibration::PRESSURE_CALIBRATION_NONE:
3860 dump.append(INDENT4 "touch.pressure.calibration: none\n");
3861 break;
3862 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3863 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3864 break;
3865 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3866 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3867 break;
3868 default:
3869 ALOG_ASSERT(false);
3870 }
3871
3872 if (mCalibration.havePressureScale) {
3873 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3874 mCalibration.pressureScale);
3875 }
3876
3877 // Orientation
3878 switch (mCalibration.orientationCalibration) {
3879 case Calibration::ORIENTATION_CALIBRATION_NONE:
3880 dump.append(INDENT4 "touch.orientation.calibration: none\n");
3881 break;
3882 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3883 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3884 break;
3885 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3886 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3887 break;
3888 default:
3889 ALOG_ASSERT(false);
3890 }
3891
3892 // Distance
3893 switch (mCalibration.distanceCalibration) {
3894 case Calibration::DISTANCE_CALIBRATION_NONE:
3895 dump.append(INDENT4 "touch.distance.calibration: none\n");
3896 break;
3897 case Calibration::DISTANCE_CALIBRATION_SCALED:
3898 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3899 break;
3900 default:
3901 ALOG_ASSERT(false);
3902 }
3903
3904 if (mCalibration.haveDistanceScale) {
3905 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
3906 mCalibration.distanceScale);
3907 }
3908
3909 switch (mCalibration.coverageCalibration) {
3910 case Calibration::COVERAGE_CALIBRATION_NONE:
3911 dump.append(INDENT4 "touch.coverage.calibration: none\n");
3912 break;
3913 case Calibration::COVERAGE_CALIBRATION_BOX:
3914 dump.append(INDENT4 "touch.coverage.calibration: box\n");
3915 break;
3916 default:
3917 ALOG_ASSERT(false);
3918 }
3919}
3920
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003921void TouchInputMapper::dumpAffineTransformation(String8& dump) {
3922 dump.append(INDENT3 "Affine Transformation:\n");
3923
3924 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
3925 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
3926 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
3927 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
3928 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
3929 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
3930}
3931
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003932void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07003933 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
3934 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003935}
3936
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937void TouchInputMapper::reset(nsecs_t when) {
3938 mCursorButtonAccumulator.reset(getDevice());
3939 mCursorScrollAccumulator.reset(getDevice());
3940 mTouchButtonAccumulator.reset(getDevice());
3941
3942 mPointerVelocityControl.reset();
3943 mWheelXVelocityControl.reset();
3944 mWheelYVelocityControl.reset();
3945
Michael Wright842500e2015-03-13 17:32:02 -07003946 mRawStatesPending.clear();
3947 mCurrentRawState.clear();
3948 mCurrentCookedState.clear();
3949 mLastRawState.clear();
3950 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 mPointerUsage = POINTER_USAGE_NONE;
3952 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07003953 mHavePointerIds = false;
Michael Wrightfbbaf2e2015-06-22 16:18:21 +01003954 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 mDownTime = 0;
3956
3957 mCurrentVirtualKey.down = false;
3958
3959 mPointerGesture.reset();
3960 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07003961 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
3963 if (mPointerController != NULL) {
3964 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3965 mPointerController->clearSpots();
3966 }
3967
3968 InputMapper::reset(when);
3969}
3970
Michael Wright842500e2015-03-13 17:32:02 -07003971void TouchInputMapper::resetExternalStylus() {
3972 mExternalStylusState.clear();
3973 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01003974 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07003975 mExternalStylusDataPending = false;
3976}
3977
Michael Wright43fd19f2015-04-21 19:02:58 +01003978void TouchInputMapper::clearStylusDataPendingFlags() {
3979 mExternalStylusDataPending = false;
3980 mExternalStylusFusionTimeout = LLONG_MAX;
3981}
3982
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983void TouchInputMapper::process(const RawEvent* rawEvent) {
3984 mCursorButtonAccumulator.process(rawEvent);
3985 mCursorScrollAccumulator.process(rawEvent);
3986 mTouchButtonAccumulator.process(rawEvent);
3987
3988 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3989 sync(rawEvent->when);
3990 }
3991}
3992
3993void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07003994 const RawState* last = mRawStatesPending.isEmpty() ?
3995 &mCurrentRawState : &mRawStatesPending.top();
3996
3997 // Push a new state.
3998 mRawStatesPending.push();
3999 RawState* next = &mRawStatesPending.editTop();
4000 next->clear();
4001 next->when = when;
4002
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004004 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 | mCursorButtonAccumulator.getButtonState();
4006
Michael Wright842500e2015-03-13 17:32:02 -07004007 // Sync scroll
4008 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4009 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 mCursorScrollAccumulator.finishSync();
4011
Michael Wright842500e2015-03-13 17:32:02 -07004012 // Sync touch
4013 syncTouch(when, next);
4014
4015 // Assign pointer ids.
4016 if (!mHavePointerIds) {
4017 assignPointerIds(last, next);
4018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
4020#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004021 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4022 "hovering ids 0x%08x -> 0x%08x",
4023 last->rawPointerData.pointerCount,
4024 next->rawPointerData.pointerCount,
4025 last->rawPointerData.touchingIdBits.value,
4026 next->rawPointerData.touchingIdBits.value,
4027 last->rawPointerData.hoveringIdBits.value,
4028 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029#endif
4030
Michael Wright842500e2015-03-13 17:32:02 -07004031 processRawTouches(false /*timeout*/);
4032}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Michael Wright842500e2015-03-13 17:32:02 -07004034void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4036 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004037 mCurrentRawState.clear();
4038 mRawStatesPending.clear();
4039 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040 }
4041
Michael Wright842500e2015-03-13 17:32:02 -07004042 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4043 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4044 // touching the current state will only observe the events that have been dispatched to the
4045 // rest of the pipeline.
4046 const size_t N = mRawStatesPending.size();
4047 size_t count;
4048 for(count = 0; count < N; count++) {
4049 const RawState& next = mRawStatesPending[count];
4050
4051 // A failure to assign the stylus id means that we're waiting on stylus data
4052 // and so should defer the rest of the pipeline.
4053 if (assignExternalStylusId(next, timeout)) {
4054 break;
4055 }
4056
4057 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004058 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004059 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004060 if (mCurrentRawState.when < mLastRawState.when) {
4061 mCurrentRawState.when = mLastRawState.when;
4062 }
Michael Wright842500e2015-03-13 17:32:02 -07004063 cookAndDispatch(mCurrentRawState.when);
4064 }
4065 if (count != 0) {
4066 mRawStatesPending.removeItemsAt(0, count);
4067 }
4068
Michael Wright842500e2015-03-13 17:32:02 -07004069 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004070 if (timeout) {
4071 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4072 clearStylusDataPendingFlags();
4073 mCurrentRawState.copyFrom(mLastRawState);
4074#if DEBUG_STYLUS_FUSION
4075 ALOGD("Timeout expired, synthesizing event with new stylus data");
4076#endif
4077 cookAndDispatch(when);
4078 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4079 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4080 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4081 }
Michael Wright842500e2015-03-13 17:32:02 -07004082 }
4083}
4084
4085void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4086 // Always start with a clean state.
4087 mCurrentCookedState.clear();
4088
4089 // Apply stylus buttons to current raw state.
4090 applyExternalStylusButtonState(when);
4091
4092 // Handle policy on initial down or hover events.
4093 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4094 && mCurrentRawState.rawPointerData.pointerCount != 0;
4095
4096 uint32_t policyFlags = 0;
4097 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4098 if (initialDown || buttonsPressed) {
4099 // If this is a touch screen, hide the pointer on an initial down.
4100 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4101 getContext()->fadePointer();
4102 }
4103
4104 if (mParameters.wake) {
4105 policyFlags |= POLICY_FLAG_WAKE;
4106 }
4107 }
4108
4109 // Consume raw off-screen touches before cooking pointer data.
4110 // If touches are consumed, subsequent code will not receive any pointer data.
4111 if (consumeRawTouches(when, policyFlags)) {
4112 mCurrentRawState.rawPointerData.clear();
4113 }
4114
4115 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4116 // with cooked pointer data that has the same ids and indices as the raw data.
4117 // The following code can use either the raw or cooked data, as needed.
4118 cookPointerData();
4119
4120 // Apply stylus pressure to current cooked state.
4121 applyExternalStylusTouchState(when);
4122
4123 // Synthesize key down from raw buttons if needed.
4124 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004125 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004126
4127 // Dispatch the touches either directly or by translation through a pointer on screen.
4128 if (mDeviceMode == DEVICE_MODE_POINTER) {
4129 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4130 !idBits.isEmpty(); ) {
4131 uint32_t id = idBits.clearFirstMarkedBit();
4132 const RawPointerData::Pointer& pointer =
4133 mCurrentRawState.rawPointerData.pointerForId(id);
4134 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4135 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4136 mCurrentCookedState.stylusIdBits.markBit(id);
4137 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4138 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4139 mCurrentCookedState.fingerIdBits.markBit(id);
4140 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4141 mCurrentCookedState.mouseIdBits.markBit(id);
4142 }
4143 }
4144 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4145 !idBits.isEmpty(); ) {
4146 uint32_t id = idBits.clearFirstMarkedBit();
4147 const RawPointerData::Pointer& pointer =
4148 mCurrentRawState.rawPointerData.pointerForId(id);
4149 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4150 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4151 mCurrentCookedState.stylusIdBits.markBit(id);
4152 }
4153 }
4154
4155 // Stylus takes precedence over all tools, then mouse, then finger.
4156 PointerUsage pointerUsage = mPointerUsage;
4157 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4158 mCurrentCookedState.mouseIdBits.clear();
4159 mCurrentCookedState.fingerIdBits.clear();
4160 pointerUsage = POINTER_USAGE_STYLUS;
4161 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4162 mCurrentCookedState.fingerIdBits.clear();
4163 pointerUsage = POINTER_USAGE_MOUSE;
4164 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4165 isPointerDown(mCurrentRawState.buttonState)) {
4166 pointerUsage = POINTER_USAGE_GESTURES;
4167 }
4168
4169 dispatchPointerUsage(when, policyFlags, pointerUsage);
4170 } else {
4171 if (mDeviceMode == DEVICE_MODE_DIRECT
4172 && mConfig.showTouches && mPointerController != NULL) {
4173 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4174 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4175
4176 mPointerController->setButtonState(mCurrentRawState.buttonState);
4177 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4178 mCurrentCookedState.cookedPointerData.idToIndex,
4179 mCurrentCookedState.cookedPointerData.touchingIdBits);
4180 }
4181
Michael Wrightfbbaf2e2015-06-22 16:18:21 +01004182 if (!mCurrentMotionAborted) {
4183 dispatchButtonRelease(when, policyFlags);
4184 dispatchHoverExit(when, policyFlags);
4185 dispatchTouches(when, policyFlags);
4186 dispatchHoverEnterAndMove(when, policyFlags);
4187 dispatchButtonPress(when, policyFlags);
4188 }
4189
4190 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4191 mCurrentMotionAborted = false;
4192 }
Michael Wright842500e2015-03-13 17:32:02 -07004193 }
4194
4195 // Synthesize key up from raw buttons if needed.
4196 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004197 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198
4199 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004200 mCurrentRawState.rawVScroll = 0;
4201 mCurrentRawState.rawHScroll = 0;
4202
4203 // Copy current touch to last touch in preparation for the next cycle.
4204 mLastRawState.copyFrom(mCurrentRawState);
4205 mLastCookedState.copyFrom(mCurrentCookedState);
4206}
4207
4208void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004209 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004210 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4211 }
4212}
4213
4214void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004215 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4216 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004217
Michael Wright53dca3a2015-04-23 17:39:53 +01004218 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4219 float pressure = mExternalStylusState.pressure;
4220 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4221 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4222 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4223 }
4224 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4225 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4226
4227 PointerProperties& properties =
4228 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004229 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4230 properties.toolType = mExternalStylusState.toolType;
4231 }
4232 }
4233}
4234
4235bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4236 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4237 return false;
4238 }
4239
4240 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4241 && state.rawPointerData.pointerCount != 0;
4242 if (initialDown) {
4243 if (mExternalStylusState.pressure != 0.0f) {
4244#if DEBUG_STYLUS_FUSION
4245 ALOGD("Have both stylus and touch data, beginning fusion");
4246#endif
4247 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4248 } else if (timeout) {
4249#if DEBUG_STYLUS_FUSION
4250 ALOGD("Timeout expired, assuming touch is not a stylus.");
4251#endif
4252 resetExternalStylus();
4253 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004254 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4255 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004256 }
4257#if DEBUG_STYLUS_FUSION
4258 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004259 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004260#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004261 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004262 return true;
4263 }
4264 }
4265
4266 // Check if the stylus pointer has gone up.
4267 if (mExternalStylusId != -1 &&
4268 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4269#if DEBUG_STYLUS_FUSION
4270 ALOGD("Stylus pointer is going up");
4271#endif
4272 mExternalStylusId = -1;
4273 }
4274
4275 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276}
4277
4278void TouchInputMapper::timeoutExpired(nsecs_t when) {
4279 if (mDeviceMode == DEVICE_MODE_POINTER) {
4280 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4281 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4282 }
Michael Wright842500e2015-03-13 17:32:02 -07004283 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004284 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004285 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004286 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4287 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004288 }
4289 }
4290}
4291
4292void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004293 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004294 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004295 // We're either in the middle of a fused stream of data or we're waiting on data before
4296 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4297 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004298 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004299 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301}
4302
4303bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4304 // Check for release of a virtual key.
4305 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004306 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 // Pointer went up while virtual key was down.
4308 mCurrentVirtualKey.down = false;
4309 if (!mCurrentVirtualKey.ignored) {
4310#if DEBUG_VIRTUAL_KEYS
4311 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4312 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4313#endif
4314 dispatchVirtualKey(when, policyFlags,
4315 AKEY_EVENT_ACTION_UP,
4316 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4317 }
4318 return true;
4319 }
4320
Michael Wright842500e2015-03-13 17:32:02 -07004321 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4322 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4323 const RawPointerData::Pointer& pointer =
4324 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4326 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4327 // Pointer is still within the space of the virtual key.
4328 return true;
4329 }
4330 }
4331
4332 // Pointer left virtual key area or another pointer also went down.
4333 // Send key cancellation but do not consume the touch yet.
4334 // This is useful when the user swipes through from the virtual key area
4335 // into the main display surface.
4336 mCurrentVirtualKey.down = false;
4337 if (!mCurrentVirtualKey.ignored) {
4338#if DEBUG_VIRTUAL_KEYS
4339 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4340 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4341#endif
4342 dispatchVirtualKey(when, policyFlags,
4343 AKEY_EVENT_ACTION_UP,
4344 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4345 | AKEY_EVENT_FLAG_CANCELED);
4346 }
4347 }
4348
Michael Wright842500e2015-03-13 17:32:02 -07004349 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4350 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004352 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4353 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4355 // If exactly one pointer went down, check for virtual key hit.
4356 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004357 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4359 if (virtualKey) {
4360 mCurrentVirtualKey.down = true;
4361 mCurrentVirtualKey.downTime = when;
4362 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4363 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4364 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4365 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4366
4367 if (!mCurrentVirtualKey.ignored) {
4368#if DEBUG_VIRTUAL_KEYS
4369 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4370 mCurrentVirtualKey.keyCode,
4371 mCurrentVirtualKey.scanCode);
4372#endif
4373 dispatchVirtualKey(when, policyFlags,
4374 AKEY_EVENT_ACTION_DOWN,
4375 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4376 }
4377 }
4378 }
4379 return true;
4380 }
4381 }
4382
4383 // Disable all virtual key touches that happen within a short time interval of the
4384 // most recent touch within the screen area. The idea is to filter out stray
4385 // virtual key presses when interacting with the touch screen.
4386 //
4387 // Problems we're trying to solve:
4388 //
4389 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4390 // virtual key area that is implemented by a separate touch panel and accidentally
4391 // triggers a virtual key.
4392 //
4393 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4394 // area and accidentally triggers a virtual key. This often happens when virtual keys
4395 // are layed out below the screen near to where the on screen keyboard's space bar
4396 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004397 if (mConfig.virtualKeyQuietTime > 0 &&
4398 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4400 }
4401 return false;
4402}
4403
4404void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4405 int32_t keyEventAction, int32_t keyEventFlags) {
4406 int32_t keyCode = mCurrentVirtualKey.keyCode;
4407 int32_t scanCode = mCurrentVirtualKey.scanCode;
4408 nsecs_t downTime = mCurrentVirtualKey.downTime;
4409 int32_t metaState = mContext->getGlobalMetaState();
4410 policyFlags |= POLICY_FLAG_VIRTUAL;
4411
4412 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4413 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4414 getListener()->notifyKey(&args);
4415}
4416
Michael Wrightfbbaf2e2015-06-22 16:18:21 +01004417void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4418 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4419 if (!currentIdBits.isEmpty()) {
4420 int32_t metaState = getContext()->getGlobalMetaState();
4421 int32_t buttonState = mCurrentCookedState.buttonState;
4422 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4423 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4424 mCurrentCookedState.cookedPointerData.pointerProperties,
4425 mCurrentCookedState.cookedPointerData.pointerCoords,
4426 mCurrentCookedState.cookedPointerData.idToIndex,
4427 currentIdBits, -1,
4428 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4429 mCurrentMotionAborted = true;
4430 }
4431}
4432
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004434 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4435 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004437 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438
4439 if (currentIdBits == lastIdBits) {
4440 if (!currentIdBits.isEmpty()) {
4441 // No pointer id changes so this is a move event.
4442 // The listener takes care of batching moves so we don't have to deal with that here.
4443 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004444 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004446 mCurrentCookedState.cookedPointerData.pointerProperties,
4447 mCurrentCookedState.cookedPointerData.pointerCoords,
4448 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 currentIdBits, -1,
4450 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4451 }
4452 } else {
4453 // There may be pointers going up and pointers going down and pointers moving
4454 // all at the same time.
4455 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4456 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4457 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4458 BitSet32 dispatchedIdBits(lastIdBits.value);
4459
4460 // Update last coordinates of pointers that have moved so that we observe the new
4461 // pointer positions at the same time as other pointers that have just gone up.
4462 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004463 mCurrentCookedState.cookedPointerData.pointerProperties,
4464 mCurrentCookedState.cookedPointerData.pointerCoords,
4465 mCurrentCookedState.cookedPointerData.idToIndex,
4466 mLastCookedState.cookedPointerData.pointerProperties,
4467 mLastCookedState.cookedPointerData.pointerCoords,
4468 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004470 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 moveNeeded = true;
4472 }
4473
4474 // Dispatch pointer up events.
4475 while (!upIdBits.isEmpty()) {
4476 uint32_t upId = upIdBits.clearFirstMarkedBit();
4477
4478 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004479 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004480 mLastCookedState.cookedPointerData.pointerProperties,
4481 mLastCookedState.cookedPointerData.pointerCoords,
4482 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004483 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 dispatchedIdBits.clearBit(upId);
4485 }
4486
4487 // Dispatch move events if any of the remaining pointers moved from their old locations.
4488 // Although applications receive new locations as part of individual pointer up
4489 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004490 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4492 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004493 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004494 mCurrentCookedState.cookedPointerData.pointerProperties,
4495 mCurrentCookedState.cookedPointerData.pointerCoords,
4496 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004497 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 }
4499
4500 // Dispatch pointer down events using the new pointer locations.
4501 while (!downIdBits.isEmpty()) {
4502 uint32_t downId = downIdBits.clearFirstMarkedBit();
4503 dispatchedIdBits.markBit(downId);
4504
4505 if (dispatchedIdBits.count() == 1) {
4506 // First pointer is going down. Set down time.
4507 mDownTime = when;
4508 }
4509
4510 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004511 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004512 mCurrentCookedState.cookedPointerData.pointerProperties,
4513 mCurrentCookedState.cookedPointerData.pointerCoords,
4514 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004515 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 }
4517 }
4518}
4519
4520void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4521 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004522 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4523 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 int32_t metaState = getContext()->getGlobalMetaState();
4525 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004526 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004527 mLastCookedState.cookedPointerData.pointerProperties,
4528 mLastCookedState.cookedPointerData.pointerCoords,
4529 mLastCookedState.cookedPointerData.idToIndex,
4530 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4532 mSentHoverEnter = false;
4533 }
4534}
4535
4536void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004537 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4538 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 int32_t metaState = getContext()->getGlobalMetaState();
4540 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004541 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004542 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004543 mCurrentCookedState.cookedPointerData.pointerProperties,
4544 mCurrentCookedState.cookedPointerData.pointerCoords,
4545 mCurrentCookedState.cookedPointerData.idToIndex,
4546 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4548 mSentHoverEnter = true;
4549 }
4550
4551 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004552 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004553 mCurrentRawState.buttonState, 0,
4554 mCurrentCookedState.cookedPointerData.pointerProperties,
4555 mCurrentCookedState.cookedPointerData.pointerCoords,
4556 mCurrentCookedState.cookedPointerData.idToIndex,
4557 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4559 }
4560}
4561
Michael Wright7b159c92015-05-14 14:48:03 +01004562void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4563 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4564 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4565 const int32_t metaState = getContext()->getGlobalMetaState();
4566 int32_t buttonState = mLastCookedState.buttonState;
4567 while (!releasedButtons.isEmpty()) {
4568 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4569 buttonState &= ~actionButton;
4570 dispatchMotion(when, policyFlags, mSource,
4571 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4572 0, metaState, buttonState, 0,
4573 mCurrentCookedState.cookedPointerData.pointerProperties,
4574 mCurrentCookedState.cookedPointerData.pointerCoords,
4575 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4576 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4577 }
4578}
4579
4580void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4581 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4582 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4583 const int32_t metaState = getContext()->getGlobalMetaState();
4584 int32_t buttonState = mLastCookedState.buttonState;
4585 while (!pressedButtons.isEmpty()) {
4586 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4587 buttonState |= actionButton;
4588 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4589 0, metaState, buttonState, 0,
4590 mCurrentCookedState.cookedPointerData.pointerProperties,
4591 mCurrentCookedState.cookedPointerData.pointerCoords,
4592 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4593 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4594 }
4595}
4596
4597const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4598 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4599 return cookedPointerData.touchingIdBits;
4600 }
4601 return cookedPointerData.hoveringIdBits;
4602}
4603
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004605 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606
Michael Wright842500e2015-03-13 17:32:02 -07004607 mCurrentCookedState.cookedPointerData.clear();
4608 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4609 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4610 mCurrentRawState.rawPointerData.hoveringIdBits;
4611 mCurrentCookedState.cookedPointerData.touchingIdBits =
4612 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613
Michael Wright7b159c92015-05-14 14:48:03 +01004614 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4615 mCurrentCookedState.buttonState = 0;
4616 } else {
4617 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4618 }
4619
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 // Walk through the the active pointers and map device coordinates onto
4621 // surface coordinates and adjust for display orientation.
4622 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004623 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624
4625 // Size
4626 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4627 switch (mCalibration.sizeCalibration) {
4628 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4629 case Calibration::SIZE_CALIBRATION_DIAMETER:
4630 case Calibration::SIZE_CALIBRATION_BOX:
4631 case Calibration::SIZE_CALIBRATION_AREA:
4632 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4633 touchMajor = in.touchMajor;
4634 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4635 toolMajor = in.toolMajor;
4636 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4637 size = mRawPointerAxes.touchMinor.valid
4638 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4639 } else if (mRawPointerAxes.touchMajor.valid) {
4640 toolMajor = touchMajor = in.touchMajor;
4641 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4642 ? in.touchMinor : in.touchMajor;
4643 size = mRawPointerAxes.touchMinor.valid
4644 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4645 } else if (mRawPointerAxes.toolMajor.valid) {
4646 touchMajor = toolMajor = in.toolMajor;
4647 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4648 ? in.toolMinor : in.toolMajor;
4649 size = mRawPointerAxes.toolMinor.valid
4650 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4651 } else {
4652 ALOG_ASSERT(false, "No touch or tool axes. "
4653 "Size calibration should have been resolved to NONE.");
4654 touchMajor = 0;
4655 touchMinor = 0;
4656 toolMajor = 0;
4657 toolMinor = 0;
4658 size = 0;
4659 }
4660
4661 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004662 uint32_t touchingCount =
4663 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 if (touchingCount > 1) {
4665 touchMajor /= touchingCount;
4666 touchMinor /= touchingCount;
4667 toolMajor /= touchingCount;
4668 toolMinor /= touchingCount;
4669 size /= touchingCount;
4670 }
4671 }
4672
4673 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4674 touchMajor *= mGeometricScale;
4675 touchMinor *= mGeometricScale;
4676 toolMajor *= mGeometricScale;
4677 toolMinor *= mGeometricScale;
4678 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4679 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4680 touchMinor = touchMajor;
4681 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4682 toolMinor = toolMajor;
4683 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4684 touchMinor = touchMajor;
4685 toolMinor = toolMajor;
4686 }
4687
4688 mCalibration.applySizeScaleAndBias(&touchMajor);
4689 mCalibration.applySizeScaleAndBias(&touchMinor);
4690 mCalibration.applySizeScaleAndBias(&toolMajor);
4691 mCalibration.applySizeScaleAndBias(&toolMinor);
4692 size *= mSizeScale;
4693 break;
4694 default:
4695 touchMajor = 0;
4696 touchMinor = 0;
4697 toolMajor = 0;
4698 toolMinor = 0;
4699 size = 0;
4700 break;
4701 }
4702
4703 // Pressure
4704 float pressure;
4705 switch (mCalibration.pressureCalibration) {
4706 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4707 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4708 pressure = in.pressure * mPressureScale;
4709 break;
4710 default:
4711 pressure = in.isHovering ? 0 : 1;
4712 break;
4713 }
4714
4715 // Tilt and Orientation
4716 float tilt;
4717 float orientation;
4718 if (mHaveTilt) {
4719 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4720 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4721 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4722 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4723 } else {
4724 tilt = 0;
4725
4726 switch (mCalibration.orientationCalibration) {
4727 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4728 orientation = in.orientation * mOrientationScale;
4729 break;
4730 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4731 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4732 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4733 if (c1 != 0 || c2 != 0) {
4734 orientation = atan2f(c1, c2) * 0.5f;
4735 float confidence = hypotf(c1, c2);
4736 float scale = 1.0f + confidence / 16.0f;
4737 touchMajor *= scale;
4738 touchMinor /= scale;
4739 toolMajor *= scale;
4740 toolMinor /= scale;
4741 } else {
4742 orientation = 0;
4743 }
4744 break;
4745 }
4746 default:
4747 orientation = 0;
4748 }
4749 }
4750
4751 // Distance
4752 float distance;
4753 switch (mCalibration.distanceCalibration) {
4754 case Calibration::DISTANCE_CALIBRATION_SCALED:
4755 distance = in.distance * mDistanceScale;
4756 break;
4757 default:
4758 distance = 0;
4759 }
4760
4761 // Coverage
4762 int32_t rawLeft, rawTop, rawRight, rawBottom;
4763 switch (mCalibration.coverageCalibration) {
4764 case Calibration::COVERAGE_CALIBRATION_BOX:
4765 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4766 rawRight = in.toolMinor & 0x0000ffff;
4767 rawBottom = in.toolMajor & 0x0000ffff;
4768 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4769 break;
4770 default:
4771 rawLeft = rawTop = rawRight = rawBottom = 0;
4772 break;
4773 }
4774
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004775 // Adjust X,Y coords for device calibration
4776 // TODO: Adjust coverage coords?
4777 float xTransformed = in.x, yTransformed = in.y;
4778 mAffineTransform.applyTo(xTransformed, yTransformed);
4779
4780 // Adjust X, Y, and coverage coords for surface orientation.
4781 float x, y;
4782 float left, top, right, bottom;
4783
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 switch (mSurfaceOrientation) {
4785 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004786 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4787 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4789 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4790 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4791 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4792 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004793 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4795 }
4796 break;
4797 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004798 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4799 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4801 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4802 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4803 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4804 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09004805 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4807 }
4808 break;
4809 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004810 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4811 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4813 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4814 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4815 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4816 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004817 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4819 }
4820 break;
4821 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004822 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4823 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4825 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4826 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4827 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4828 break;
4829 }
4830
4831 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07004832 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 out.clear();
4834 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4835 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4836 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4837 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4838 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4839 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4840 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4841 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4842 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4843 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4844 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4845 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4846 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4847 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4848 } else {
4849 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4850 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4851 }
4852
4853 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07004854 PointerProperties& properties =
4855 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 uint32_t id = in.id;
4857 properties.clear();
4858 properties.id = id;
4859 properties.toolType = in.toolType;
4860
4861 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07004862 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 }
4864}
4865
4866void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4867 PointerUsage pointerUsage) {
4868 if (pointerUsage != mPointerUsage) {
4869 abortPointerUsage(when, policyFlags);
4870 mPointerUsage = pointerUsage;
4871 }
4872
4873 switch (mPointerUsage) {
4874 case POINTER_USAGE_GESTURES:
4875 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4876 break;
4877 case POINTER_USAGE_STYLUS:
4878 dispatchPointerStylus(when, policyFlags);
4879 break;
4880 case POINTER_USAGE_MOUSE:
4881 dispatchPointerMouse(when, policyFlags);
4882 break;
4883 default:
4884 break;
4885 }
4886}
4887
4888void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4889 switch (mPointerUsage) {
4890 case POINTER_USAGE_GESTURES:
4891 abortPointerGestures(when, policyFlags);
4892 break;
4893 case POINTER_USAGE_STYLUS:
4894 abortPointerStylus(when, policyFlags);
4895 break;
4896 case POINTER_USAGE_MOUSE:
4897 abortPointerMouse(when, policyFlags);
4898 break;
4899 default:
4900 break;
4901 }
4902
4903 mPointerUsage = POINTER_USAGE_NONE;
4904}
4905
4906void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
4907 bool isTimeout) {
4908 // Update current gesture coordinates.
4909 bool cancelPreviousGesture, finishPreviousGesture;
4910 bool sendEvents = preparePointerGestures(when,
4911 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
4912 if (!sendEvents) {
4913 return;
4914 }
4915 if (finishPreviousGesture) {
4916 cancelPreviousGesture = false;
4917 }
4918
4919 // Update the pointer presentation and spots.
4920 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4921 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4922 if (finishPreviousGesture || cancelPreviousGesture) {
4923 mPointerController->clearSpots();
4924 }
4925 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
4926 mPointerGesture.currentGestureIdToIndex,
4927 mPointerGesture.currentGestureIdBits);
4928 } else {
4929 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4930 }
4931
4932 // Show or hide the pointer if needed.
4933 switch (mPointerGesture.currentGestureMode) {
4934 case PointerGesture::NEUTRAL:
4935 case PointerGesture::QUIET:
4936 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
4937 && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4938 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
4939 // Remind the user of where the pointer is after finishing a gesture with spots.
4940 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
4941 }
4942 break;
4943 case PointerGesture::TAP:
4944 case PointerGesture::TAP_DRAG:
4945 case PointerGesture::BUTTON_CLICK_OR_DRAG:
4946 case PointerGesture::HOVER:
4947 case PointerGesture::PRESS:
4948 // Unfade the pointer when the current gesture manipulates the
4949 // area directly under the pointer.
4950 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4951 break;
4952 case PointerGesture::SWIPE:
4953 case PointerGesture::FREEFORM:
4954 // Fade the pointer when the current gesture manipulates a different
4955 // area and there are spots to guide the user experience.
4956 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4957 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4958 } else {
4959 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4960 }
4961 break;
4962 }
4963
4964 // Send events!
4965 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004966 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967
4968 // Update last coordinates of pointers that have moved so that we observe the new
4969 // pointer positions at the same time as other pointers that have just gone up.
4970 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
4971 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
4972 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4973 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
4974 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
4975 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
4976 bool moveNeeded = false;
4977 if (down && !cancelPreviousGesture && !finishPreviousGesture
4978 && !mPointerGesture.lastGestureIdBits.isEmpty()
4979 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
4980 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
4981 & mPointerGesture.lastGestureIdBits.value);
4982 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
4983 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4984 mPointerGesture.lastGestureProperties,
4985 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4986 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004987 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 moveNeeded = true;
4989 }
4990 }
4991
4992 // Send motion events for all pointers that went up or were canceled.
4993 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
4994 if (!dispatchedGestureIdBits.isEmpty()) {
4995 if (cancelPreviousGesture) {
4996 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004997 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 AMOTION_EVENT_EDGE_FLAG_NONE,
4999 mPointerGesture.lastGestureProperties,
5000 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005001 dispatchedGestureIdBits, -1, 0,
5002 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003
5004 dispatchedGestureIdBits.clear();
5005 } else {
5006 BitSet32 upGestureIdBits;
5007 if (finishPreviousGesture) {
5008 upGestureIdBits = dispatchedGestureIdBits;
5009 } else {
5010 upGestureIdBits.value = dispatchedGestureIdBits.value
5011 & ~mPointerGesture.currentGestureIdBits.value;
5012 }
5013 while (!upGestureIdBits.isEmpty()) {
5014 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5015
5016 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005017 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5019 mPointerGesture.lastGestureProperties,
5020 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5021 dispatchedGestureIdBits, id,
5022 0, 0, mPointerGesture.downTime);
5023
5024 dispatchedGestureIdBits.clearBit(id);
5025 }
5026 }
5027 }
5028
5029 // Send motion events for all pointers that moved.
5030 if (moveNeeded) {
5031 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005032 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5033 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034 mPointerGesture.currentGestureProperties,
5035 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5036 dispatchedGestureIdBits, -1,
5037 0, 0, mPointerGesture.downTime);
5038 }
5039
5040 // Send motion events for all pointers that went down.
5041 if (down) {
5042 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5043 & ~dispatchedGestureIdBits.value);
5044 while (!downGestureIdBits.isEmpty()) {
5045 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5046 dispatchedGestureIdBits.markBit(id);
5047
5048 if (dispatchedGestureIdBits.count() == 1) {
5049 mPointerGesture.downTime = when;
5050 }
5051
5052 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005053 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005054 mPointerGesture.currentGestureProperties,
5055 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5056 dispatchedGestureIdBits, id,
5057 0, 0, mPointerGesture.downTime);
5058 }
5059 }
5060
5061 // Send motion events for hover.
5062 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5063 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005064 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5066 mPointerGesture.currentGestureProperties,
5067 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5068 mPointerGesture.currentGestureIdBits, -1,
5069 0, 0, mPointerGesture.downTime);
5070 } else if (dispatchedGestureIdBits.isEmpty()
5071 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5072 // Synthesize a hover move event after all pointers go up to indicate that
5073 // the pointer is hovering again even if the user is not currently touching
5074 // the touch pad. This ensures that a view will receive a fresh hover enter
5075 // event after a tap.
5076 float x, y;
5077 mPointerController->getPosition(&x, &y);
5078
5079 PointerProperties pointerProperties;
5080 pointerProperties.clear();
5081 pointerProperties.id = 0;
5082 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5083
5084 PointerCoords pointerCoords;
5085 pointerCoords.clear();
5086 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5087 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5088
5089 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005090 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5092 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5093 0, 0, mPointerGesture.downTime);
5094 getListener()->notifyMotion(&args);
5095 }
5096
5097 // Update state.
5098 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5099 if (!down) {
5100 mPointerGesture.lastGestureIdBits.clear();
5101 } else {
5102 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5103 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5104 uint32_t id = idBits.clearFirstMarkedBit();
5105 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5106 mPointerGesture.lastGestureProperties[index].copyFrom(
5107 mPointerGesture.currentGestureProperties[index]);
5108 mPointerGesture.lastGestureCoords[index].copyFrom(
5109 mPointerGesture.currentGestureCoords[index]);
5110 mPointerGesture.lastGestureIdToIndex[id] = index;
5111 }
5112 }
5113}
5114
5115void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5116 // Cancel previously dispatches pointers.
5117 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5118 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005119 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005121 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122 AMOTION_EVENT_EDGE_FLAG_NONE,
5123 mPointerGesture.lastGestureProperties,
5124 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5125 mPointerGesture.lastGestureIdBits, -1,
5126 0, 0, mPointerGesture.downTime);
5127 }
5128
5129 // Reset the current pointer gesture.
5130 mPointerGesture.reset();
5131 mPointerVelocityControl.reset();
5132
5133 // Remove any current spots.
5134 if (mPointerController != NULL) {
5135 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5136 mPointerController->clearSpots();
5137 }
5138}
5139
5140bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5141 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5142 *outCancelPreviousGesture = false;
5143 *outFinishPreviousGesture = false;
5144
5145 // Handle TAP timeout.
5146 if (isTimeout) {
5147#if DEBUG_GESTURES
5148 ALOGD("Gestures: Processing timeout");
5149#endif
5150
5151 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5152 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5153 // The tap/drag timeout has not yet expired.
5154 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5155 + mConfig.pointerGestureTapDragInterval);
5156 } else {
5157 // The tap is finished.
5158#if DEBUG_GESTURES
5159 ALOGD("Gestures: TAP finished");
5160#endif
5161 *outFinishPreviousGesture = true;
5162
5163 mPointerGesture.activeGestureId = -1;
5164 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5165 mPointerGesture.currentGestureIdBits.clear();
5166
5167 mPointerVelocityControl.reset();
5168 return true;
5169 }
5170 }
5171
5172 // We did not handle this timeout.
5173 return false;
5174 }
5175
Michael Wright842500e2015-03-13 17:32:02 -07005176 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5177 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178
5179 // Update the velocity tracker.
5180 {
5181 VelocityTracker::Position positions[MAX_POINTERS];
5182 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005183 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005185 const RawPointerData::Pointer& pointer =
5186 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 positions[count].x = pointer.x * mPointerXMovementScale;
5188 positions[count].y = pointer.y * mPointerYMovementScale;
5189 }
5190 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005191 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 }
5193
5194 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5195 // to NEUTRAL, then we should not generate tap event.
5196 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5197 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5198 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5199 mPointerGesture.resetTap();
5200 }
5201
5202 // Pick a new active touch id if needed.
5203 // Choose an arbitrary pointer that just went down, if there is one.
5204 // Otherwise choose an arbitrary remaining pointer.
5205 // This guarantees we always have an active touch id when there is at least one pointer.
5206 // We keep the same active touch id for as long as possible.
5207 bool activeTouchChanged = false;
5208 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5209 int32_t activeTouchId = lastActiveTouchId;
5210 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005211 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212 activeTouchChanged = true;
5213 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005214 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 mPointerGesture.firstTouchTime = when;
5216 }
Michael Wright842500e2015-03-13 17:32:02 -07005217 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005218 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005219 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005221 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 } else {
5223 activeTouchId = mPointerGesture.activeTouchId = -1;
5224 }
5225 }
5226
5227 // Determine whether we are in quiet time.
5228 bool isQuietTime = false;
5229 if (activeTouchId < 0) {
5230 mPointerGesture.resetQuietTime();
5231 } else {
5232 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5233 if (!isQuietTime) {
5234 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5235 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5236 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5237 && currentFingerCount < 2) {
5238 // Enter quiet time when exiting swipe or freeform state.
5239 // This is to prevent accidentally entering the hover state and flinging the
5240 // pointer when finishing a swipe and there is still one pointer left onscreen.
5241 isQuietTime = true;
5242 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5243 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005244 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 // Enter quiet time when releasing the button and there are still two or more
5246 // fingers down. This may indicate that one finger was used to press the button
5247 // but it has not gone up yet.
5248 isQuietTime = true;
5249 }
5250 if (isQuietTime) {
5251 mPointerGesture.quietTime = when;
5252 }
5253 }
5254 }
5255
5256 // Switch states based on button and pointer state.
5257 if (isQuietTime) {
5258 // Case 1: Quiet time. (QUIET)
5259#if DEBUG_GESTURES
5260 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5261 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5262#endif
5263 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5264 *outFinishPreviousGesture = true;
5265 }
5266
5267 mPointerGesture.activeGestureId = -1;
5268 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5269 mPointerGesture.currentGestureIdBits.clear();
5270
5271 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005272 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5274 // The pointer follows the active touch point.
5275 // Emit DOWN, MOVE, UP events at the pointer location.
5276 //
5277 // Only the active touch matters; other fingers are ignored. This policy helps
5278 // to handle the case where the user places a second finger on the touch pad
5279 // to apply the necessary force to depress an integrated button below the surface.
5280 // We don't want the second finger to be delivered to applications.
5281 //
5282 // For this to work well, we need to make sure to track the pointer that is really
5283 // active. If the user first puts one finger down to click then adds another
5284 // finger to drag then the active pointer should switch to the finger that is
5285 // being dragged.
5286#if DEBUG_GESTURES
5287 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5288 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5289#endif
5290 // Reset state when just starting.
5291 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5292 *outFinishPreviousGesture = true;
5293 mPointerGesture.activeGestureId = 0;
5294 }
5295
5296 // Switch pointers if needed.
5297 // Find the fastest pointer and follow it.
5298 if (activeTouchId >= 0 && currentFingerCount > 1) {
5299 int32_t bestId = -1;
5300 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005301 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 uint32_t id = idBits.clearFirstMarkedBit();
5303 float vx, vy;
5304 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5305 float speed = hypotf(vx, vy);
5306 if (speed > bestSpeed) {
5307 bestId = id;
5308 bestSpeed = speed;
5309 }
5310 }
5311 }
5312 if (bestId >= 0 && bestId != activeTouchId) {
5313 mPointerGesture.activeTouchId = activeTouchId = bestId;
5314 activeTouchChanged = true;
5315#if DEBUG_GESTURES
5316 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5317 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5318#endif
5319 }
5320 }
5321
Michael Wright842500e2015-03-13 17:32:02 -07005322 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005324 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005326 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5328 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
5329
5330 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5331 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5332
5333 // Move the pointer using a relative motion.
5334 // When using spots, the click will occur at the position of the anchor
5335 // spot and all other spots will move there.
5336 mPointerController->move(deltaX, deltaY);
5337 } else {
5338 mPointerVelocityControl.reset();
5339 }
5340
5341 float x, y;
5342 mPointerController->getPosition(&x, &y);
5343
5344 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5345 mPointerGesture.currentGestureIdBits.clear();
5346 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5347 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5348 mPointerGesture.currentGestureProperties[0].clear();
5349 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5350 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5351 mPointerGesture.currentGestureCoords[0].clear();
5352 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5353 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5354 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5355 } else if (currentFingerCount == 0) {
5356 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5357 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5358 *outFinishPreviousGesture = true;
5359 }
5360
5361 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5362 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5363 bool tapped = false;
5364 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5365 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5366 && lastFingerCount == 1) {
5367 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5368 float x, y;
5369 mPointerController->getPosition(&x, &y);
5370 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5371 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5372#if DEBUG_GESTURES
5373 ALOGD("Gestures: TAP");
5374#endif
5375
5376 mPointerGesture.tapUpTime = when;
5377 getContext()->requestTimeoutAtTime(when
5378 + mConfig.pointerGestureTapDragInterval);
5379
5380 mPointerGesture.activeGestureId = 0;
5381 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5382 mPointerGesture.currentGestureIdBits.clear();
5383 mPointerGesture.currentGestureIdBits.markBit(
5384 mPointerGesture.activeGestureId);
5385 mPointerGesture.currentGestureIdToIndex[
5386 mPointerGesture.activeGestureId] = 0;
5387 mPointerGesture.currentGestureProperties[0].clear();
5388 mPointerGesture.currentGestureProperties[0].id =
5389 mPointerGesture.activeGestureId;
5390 mPointerGesture.currentGestureProperties[0].toolType =
5391 AMOTION_EVENT_TOOL_TYPE_FINGER;
5392 mPointerGesture.currentGestureCoords[0].clear();
5393 mPointerGesture.currentGestureCoords[0].setAxisValue(
5394 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5395 mPointerGesture.currentGestureCoords[0].setAxisValue(
5396 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5397 mPointerGesture.currentGestureCoords[0].setAxisValue(
5398 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5399
5400 tapped = true;
5401 } else {
5402#if DEBUG_GESTURES
5403 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5404 x - mPointerGesture.tapX,
5405 y - mPointerGesture.tapY);
5406#endif
5407 }
5408 } else {
5409#if DEBUG_GESTURES
5410 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5411 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5412 (when - mPointerGesture.tapDownTime) * 0.000001f);
5413 } else {
5414 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5415 }
5416#endif
5417 }
5418 }
5419
5420 mPointerVelocityControl.reset();
5421
5422 if (!tapped) {
5423#if DEBUG_GESTURES
5424 ALOGD("Gestures: NEUTRAL");
5425#endif
5426 mPointerGesture.activeGestureId = -1;
5427 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5428 mPointerGesture.currentGestureIdBits.clear();
5429 }
5430 } else if (currentFingerCount == 1) {
5431 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5432 // The pointer follows the active touch point.
5433 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5434 // When in TAP_DRAG, emit MOVE events at the pointer location.
5435 ALOG_ASSERT(activeTouchId >= 0);
5436
5437 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5438 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5439 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5440 float x, y;
5441 mPointerController->getPosition(&x, &y);
5442 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5443 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5444 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5445 } else {
5446#if DEBUG_GESTURES
5447 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5448 x - mPointerGesture.tapX,
5449 y - mPointerGesture.tapY);
5450#endif
5451 }
5452 } else {
5453#if DEBUG_GESTURES
5454 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5455 (when - mPointerGesture.tapUpTime) * 0.000001f);
5456#endif
5457 }
5458 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5459 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5460 }
5461
Michael Wright842500e2015-03-13 17:32:02 -07005462 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005464 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005466 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 float deltaX = (currentPointer.x - lastPointer.x)
5468 * mPointerXMovementScale;
5469 float deltaY = (currentPointer.y - lastPointer.y)
5470 * mPointerYMovementScale;
5471
5472 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5473 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5474
5475 // Move the pointer using a relative motion.
5476 // When using spots, the hover or drag will occur at the position of the anchor spot.
5477 mPointerController->move(deltaX, deltaY);
5478 } else {
5479 mPointerVelocityControl.reset();
5480 }
5481
5482 bool down;
5483 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5484#if DEBUG_GESTURES
5485 ALOGD("Gestures: TAP_DRAG");
5486#endif
5487 down = true;
5488 } else {
5489#if DEBUG_GESTURES
5490 ALOGD("Gestures: HOVER");
5491#endif
5492 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5493 *outFinishPreviousGesture = true;
5494 }
5495 mPointerGesture.activeGestureId = 0;
5496 down = false;
5497 }
5498
5499 float x, y;
5500 mPointerController->getPosition(&x, &y);
5501
5502 mPointerGesture.currentGestureIdBits.clear();
5503 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5504 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5505 mPointerGesture.currentGestureProperties[0].clear();
5506 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5507 mPointerGesture.currentGestureProperties[0].toolType =
5508 AMOTION_EVENT_TOOL_TYPE_FINGER;
5509 mPointerGesture.currentGestureCoords[0].clear();
5510 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5511 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5512 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5513 down ? 1.0f : 0.0f);
5514
5515 if (lastFingerCount == 0 && currentFingerCount != 0) {
5516 mPointerGesture.resetTap();
5517 mPointerGesture.tapDownTime = when;
5518 mPointerGesture.tapX = x;
5519 mPointerGesture.tapY = y;
5520 }
5521 } else {
5522 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5523 // We need to provide feedback for each finger that goes down so we cannot wait
5524 // for the fingers to move before deciding what to do.
5525 //
5526 // The ambiguous case is deciding what to do when there are two fingers down but they
5527 // have not moved enough to determine whether they are part of a drag or part of a
5528 // freeform gesture, or just a press or long-press at the pointer location.
5529 //
5530 // When there are two fingers we start with the PRESS hypothesis and we generate a
5531 // down at the pointer location.
5532 //
5533 // When the two fingers move enough or when additional fingers are added, we make
5534 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5535 ALOG_ASSERT(activeTouchId >= 0);
5536
5537 bool settled = when >= mPointerGesture.firstTouchTime
5538 + mConfig.pointerGestureMultitouchSettleInterval;
5539 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5540 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5541 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5542 *outFinishPreviousGesture = true;
5543 } else if (!settled && currentFingerCount > lastFingerCount) {
5544 // Additional pointers have gone down but not yet settled.
5545 // Reset the gesture.
5546#if DEBUG_GESTURES
5547 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5548 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5549 + mConfig.pointerGestureMultitouchSettleInterval - when)
5550 * 0.000001f);
5551#endif
5552 *outCancelPreviousGesture = true;
5553 } else {
5554 // Continue previous gesture.
5555 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5556 }
5557
5558 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5559 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5560 mPointerGesture.activeGestureId = 0;
5561 mPointerGesture.referenceIdBits.clear();
5562 mPointerVelocityControl.reset();
5563
5564 // Use the centroid and pointer location as the reference points for the gesture.
5565#if DEBUG_GESTURES
5566 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5567 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5568 + mConfig.pointerGestureMultitouchSettleInterval - when)
5569 * 0.000001f);
5570#endif
Michael Wright842500e2015-03-13 17:32:02 -07005571 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 &mPointerGesture.referenceTouchX,
5573 &mPointerGesture.referenceTouchY);
5574 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5575 &mPointerGesture.referenceGestureY);
5576 }
5577
5578 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005579 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5581 uint32_t id = idBits.clearFirstMarkedBit();
5582 mPointerGesture.referenceDeltas[id].dx = 0;
5583 mPointerGesture.referenceDeltas[id].dy = 0;
5584 }
Michael Wright842500e2015-03-13 17:32:02 -07005585 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586
5587 // Add delta for all fingers and calculate a common movement delta.
5588 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005589 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5590 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5592 bool first = (idBits == commonIdBits);
5593 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005594 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5595 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5597 delta.dx += cpd.x - lpd.x;
5598 delta.dy += cpd.y - lpd.y;
5599
5600 if (first) {
5601 commonDeltaX = delta.dx;
5602 commonDeltaY = delta.dy;
5603 } else {
5604 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5605 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5606 }
5607 }
5608
5609 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5610 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5611 float dist[MAX_POINTER_ID + 1];
5612 int32_t distOverThreshold = 0;
5613 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5614 uint32_t id = idBits.clearFirstMarkedBit();
5615 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5616 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5617 delta.dy * mPointerYZoomScale);
5618 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5619 distOverThreshold += 1;
5620 }
5621 }
5622
5623 // Only transition when at least two pointers have moved further than
5624 // the minimum distance threshold.
5625 if (distOverThreshold >= 2) {
5626 if (currentFingerCount > 2) {
5627 // There are more than two pointers, switch to FREEFORM.
5628#if DEBUG_GESTURES
5629 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5630 currentFingerCount);
5631#endif
5632 *outCancelPreviousGesture = true;
5633 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5634 } else {
5635 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005636 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 uint32_t id1 = idBits.clearFirstMarkedBit();
5638 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005639 const RawPointerData::Pointer& p1 =
5640 mCurrentRawState.rawPointerData.pointerForId(id1);
5641 const RawPointerData::Pointer& p2 =
5642 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5644 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5645 // There are two pointers but they are too far apart for a SWIPE,
5646 // switch to FREEFORM.
5647#if DEBUG_GESTURES
5648 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5649 mutualDistance, mPointerGestureMaxSwipeWidth);
5650#endif
5651 *outCancelPreviousGesture = true;
5652 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5653 } else {
5654 // There are two pointers. Wait for both pointers to start moving
5655 // before deciding whether this is a SWIPE or FREEFORM gesture.
5656 float dist1 = dist[id1];
5657 float dist2 = dist[id2];
5658 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5659 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5660 // Calculate the dot product of the displacement vectors.
5661 // When the vectors are oriented in approximately the same direction,
5662 // the angle betweeen them is near zero and the cosine of the angle
5663 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5664 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5665 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5666 float dx1 = delta1.dx * mPointerXZoomScale;
5667 float dy1 = delta1.dy * mPointerYZoomScale;
5668 float dx2 = delta2.dx * mPointerXZoomScale;
5669 float dy2 = delta2.dy * mPointerYZoomScale;
5670 float dot = dx1 * dx2 + dy1 * dy2;
5671 float cosine = dot / (dist1 * dist2); // denominator always > 0
5672 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5673 // Pointers are moving in the same direction. Switch to SWIPE.
5674#if DEBUG_GESTURES
5675 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5676 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5677 "cosine %0.3f >= %0.3f",
5678 dist1, mConfig.pointerGestureMultitouchMinDistance,
5679 dist2, mConfig.pointerGestureMultitouchMinDistance,
5680 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5681#endif
5682 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5683 } else {
5684 // Pointers are moving in different directions. Switch to FREEFORM.
5685#if DEBUG_GESTURES
5686 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5687 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5688 "cosine %0.3f < %0.3f",
5689 dist1, mConfig.pointerGestureMultitouchMinDistance,
5690 dist2, mConfig.pointerGestureMultitouchMinDistance,
5691 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5692#endif
5693 *outCancelPreviousGesture = true;
5694 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5695 }
5696 }
5697 }
5698 }
5699 }
5700 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5701 // Switch from SWIPE to FREEFORM if additional pointers go down.
5702 // Cancel previous gesture.
5703 if (currentFingerCount > 2) {
5704#if DEBUG_GESTURES
5705 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5706 currentFingerCount);
5707#endif
5708 *outCancelPreviousGesture = true;
5709 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5710 }
5711 }
5712
5713 // Move the reference points based on the overall group motion of the fingers
5714 // except in PRESS mode while waiting for a transition to occur.
5715 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5716 && (commonDeltaX || commonDeltaY)) {
5717 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5718 uint32_t id = idBits.clearFirstMarkedBit();
5719 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5720 delta.dx = 0;
5721 delta.dy = 0;
5722 }
5723
5724 mPointerGesture.referenceTouchX += commonDeltaX;
5725 mPointerGesture.referenceTouchY += commonDeltaY;
5726
5727 commonDeltaX *= mPointerXMovementScale;
5728 commonDeltaY *= mPointerYMovementScale;
5729
5730 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5731 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5732
5733 mPointerGesture.referenceGestureX += commonDeltaX;
5734 mPointerGesture.referenceGestureY += commonDeltaY;
5735 }
5736
5737 // Report gestures.
5738 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5739 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5740 // PRESS or SWIPE mode.
5741#if DEBUG_GESTURES
5742 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5743 "activeGestureId=%d, currentTouchPointerCount=%d",
5744 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5745#endif
5746 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5747
5748 mPointerGesture.currentGestureIdBits.clear();
5749 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5750 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5751 mPointerGesture.currentGestureProperties[0].clear();
5752 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5753 mPointerGesture.currentGestureProperties[0].toolType =
5754 AMOTION_EVENT_TOOL_TYPE_FINGER;
5755 mPointerGesture.currentGestureCoords[0].clear();
5756 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5757 mPointerGesture.referenceGestureX);
5758 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5759 mPointerGesture.referenceGestureY);
5760 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5761 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5762 // FREEFORM mode.
5763#if DEBUG_GESTURES
5764 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5765 "activeGestureId=%d, currentTouchPointerCount=%d",
5766 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5767#endif
5768 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5769
5770 mPointerGesture.currentGestureIdBits.clear();
5771
5772 BitSet32 mappedTouchIdBits;
5773 BitSet32 usedGestureIdBits;
5774 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5775 // Initially, assign the active gesture id to the active touch point
5776 // if there is one. No other touch id bits are mapped yet.
5777 if (!*outCancelPreviousGesture) {
5778 mappedTouchIdBits.markBit(activeTouchId);
5779 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5780 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5781 mPointerGesture.activeGestureId;
5782 } else {
5783 mPointerGesture.activeGestureId = -1;
5784 }
5785 } else {
5786 // Otherwise, assume we mapped all touches from the previous frame.
5787 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07005788 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
5789 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5791
5792 // Check whether we need to choose a new active gesture id because the
5793 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07005794 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
5795 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005796 !upTouchIdBits.isEmpty(); ) {
5797 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5798 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5799 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5800 mPointerGesture.activeGestureId = -1;
5801 break;
5802 }
5803 }
5804 }
5805
5806#if DEBUG_GESTURES
5807 ALOGD("Gestures: FREEFORM follow up "
5808 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5809 "activeGestureId=%d",
5810 mappedTouchIdBits.value, usedGestureIdBits.value,
5811 mPointerGesture.activeGestureId);
5812#endif
5813
Michael Wright842500e2015-03-13 17:32:02 -07005814 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 for (uint32_t i = 0; i < currentFingerCount; i++) {
5816 uint32_t touchId = idBits.clearFirstMarkedBit();
5817 uint32_t gestureId;
5818 if (!mappedTouchIdBits.hasBit(touchId)) {
5819 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5820 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5821#if DEBUG_GESTURES
5822 ALOGD("Gestures: FREEFORM "
5823 "new mapping for touch id %d -> gesture id %d",
5824 touchId, gestureId);
5825#endif
5826 } else {
5827 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5828#if DEBUG_GESTURES
5829 ALOGD("Gestures: FREEFORM "
5830 "existing mapping for touch id %d -> gesture id %d",
5831 touchId, gestureId);
5832#endif
5833 }
5834 mPointerGesture.currentGestureIdBits.markBit(gestureId);
5835 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5836
5837 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07005838 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5840 * mPointerXZoomScale;
5841 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5842 * mPointerYZoomScale;
5843 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5844
5845 mPointerGesture.currentGestureProperties[i].clear();
5846 mPointerGesture.currentGestureProperties[i].id = gestureId;
5847 mPointerGesture.currentGestureProperties[i].toolType =
5848 AMOTION_EVENT_TOOL_TYPE_FINGER;
5849 mPointerGesture.currentGestureCoords[i].clear();
5850 mPointerGesture.currentGestureCoords[i].setAxisValue(
5851 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5852 mPointerGesture.currentGestureCoords[i].setAxisValue(
5853 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5854 mPointerGesture.currentGestureCoords[i].setAxisValue(
5855 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5856 }
5857
5858 if (mPointerGesture.activeGestureId < 0) {
5859 mPointerGesture.activeGestureId =
5860 mPointerGesture.currentGestureIdBits.firstMarkedBit();
5861#if DEBUG_GESTURES
5862 ALOGD("Gestures: FREEFORM new "
5863 "activeGestureId=%d", mPointerGesture.activeGestureId);
5864#endif
5865 }
5866 }
5867 }
5868
Michael Wright842500e2015-03-13 17:32:02 -07005869 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870
5871#if DEBUG_GESTURES
5872 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5873 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5874 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5875 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5876 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5877 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5878 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5879 uint32_t id = idBits.clearFirstMarkedBit();
5880 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5881 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5882 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5883 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
5884 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5885 id, index, properties.toolType,
5886 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5887 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5888 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5889 }
5890 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5891 uint32_t id = idBits.clearFirstMarkedBit();
5892 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5893 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5894 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5895 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
5896 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5897 id, index, properties.toolType,
5898 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5899 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5900 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5901 }
5902#endif
5903 return true;
5904}
5905
5906void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
5907 mPointerSimple.currentCoords.clear();
5908 mPointerSimple.currentProperties.clear();
5909
5910 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07005911 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
5912 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
5913 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
5914 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
5915 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916 mPointerController->setPosition(x, y);
5917
Michael Wright842500e2015-03-13 17:32:02 -07005918 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 down = !hovering;
5920
5921 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07005922 mPointerSimple.currentCoords.copyFrom(
5923 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5925 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5926 mPointerSimple.currentProperties.id = 0;
5927 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07005928 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 } else {
5930 down = false;
5931 hovering = false;
5932 }
5933
5934 dispatchPointerSimple(when, policyFlags, down, hovering);
5935}
5936
5937void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
5938 abortPointerSimple(when, policyFlags);
5939}
5940
5941void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
5942 mPointerSimple.currentCoords.clear();
5943 mPointerSimple.currentProperties.clear();
5944
5945 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07005946 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
5947 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
5948 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
5949 if (mLastCookedState.mouseIdBits.hasBit(id)) {
5950 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
5951 float deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
5952 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953 * mPointerXMovementScale;
Michael Wright842500e2015-03-13 17:32:02 -07005954 float deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
5955 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 * mPointerYMovementScale;
5957
5958 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5959 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5960
5961 mPointerController->move(deltaX, deltaY);
5962 } else {
5963 mPointerVelocityControl.reset();
5964 }
5965
Michael Wright842500e2015-03-13 17:32:02 -07005966 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 hovering = !down;
5968
5969 float x, y;
5970 mPointerController->getPosition(&x, &y);
5971 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07005972 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5974 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5975 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5976 hovering ? 0.0f : 1.0f);
5977 mPointerSimple.currentProperties.id = 0;
5978 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07005979 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980 } else {
5981 mPointerVelocityControl.reset();
5982
5983 down = false;
5984 hovering = false;
5985 }
5986
5987 dispatchPointerSimple(when, policyFlags, down, hovering);
5988}
5989
5990void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
5991 abortPointerSimple(when, policyFlags);
5992
5993 mPointerVelocityControl.reset();
5994}
5995
5996void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
5997 bool down, bool hovering) {
5998 int32_t metaState = getContext()->getGlobalMetaState();
5999
6000 if (mPointerController != NULL) {
6001 if (down || hovering) {
6002 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6003 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006004 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006005 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6006 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6007 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6008 }
6009 }
6010
6011 if (mPointerSimple.down && !down) {
6012 mPointerSimple.down = false;
6013
6014 // Send up.
6015 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006016 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017 mViewport.displayId,
6018 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6019 mOrientedXPrecision, mOrientedYPrecision,
6020 mPointerSimple.downTime);
6021 getListener()->notifyMotion(&args);
6022 }
6023
6024 if (mPointerSimple.hovering && !hovering) {
6025 mPointerSimple.hovering = false;
6026
6027 // Send hover exit.
6028 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006029 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030 mViewport.displayId,
6031 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6032 mOrientedXPrecision, mOrientedYPrecision,
6033 mPointerSimple.downTime);
6034 getListener()->notifyMotion(&args);
6035 }
6036
6037 if (down) {
6038 if (!mPointerSimple.down) {
6039 mPointerSimple.down = true;
6040 mPointerSimple.downTime = when;
6041
6042 // Send down.
6043 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006044 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 mViewport.displayId,
6046 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6047 mOrientedXPrecision, mOrientedYPrecision,
6048 mPointerSimple.downTime);
6049 getListener()->notifyMotion(&args);
6050 }
6051
6052 // Send move.
6053 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006054 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055 mViewport.displayId,
6056 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6057 mOrientedXPrecision, mOrientedYPrecision,
6058 mPointerSimple.downTime);
6059 getListener()->notifyMotion(&args);
6060 }
6061
6062 if (hovering) {
6063 if (!mPointerSimple.hovering) {
6064 mPointerSimple.hovering = true;
6065
6066 // Send hover enter.
6067 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006068 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006069 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070 mViewport.displayId,
6071 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6072 mOrientedXPrecision, mOrientedYPrecision,
6073 mPointerSimple.downTime);
6074 getListener()->notifyMotion(&args);
6075 }
6076
6077 // Send hover move.
6078 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006079 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006080 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 mViewport.displayId,
6082 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6083 mOrientedXPrecision, mOrientedYPrecision,
6084 mPointerSimple.downTime);
6085 getListener()->notifyMotion(&args);
6086 }
6087
Michael Wright842500e2015-03-13 17:32:02 -07006088 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6089 float vscroll = mCurrentRawState.rawVScroll;
6090 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 mWheelYVelocityControl.move(when, NULL, &vscroll);
6092 mWheelXVelocityControl.move(when, &hscroll, NULL);
6093
6094 // Send scroll.
6095 PointerCoords pointerCoords;
6096 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6097 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6098 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6099
6100 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006101 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 mViewport.displayId,
6103 1, &mPointerSimple.currentProperties, &pointerCoords,
6104 mOrientedXPrecision, mOrientedYPrecision,
6105 mPointerSimple.downTime);
6106 getListener()->notifyMotion(&args);
6107 }
6108
6109 // Save state.
6110 if (down || hovering) {
6111 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6112 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6113 } else {
6114 mPointerSimple.reset();
6115 }
6116}
6117
6118void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6119 mPointerSimple.currentCoords.clear();
6120 mPointerSimple.currentProperties.clear();
6121
6122 dispatchPointerSimple(when, policyFlags, false, false);
6123}
6124
6125void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006126 int32_t action, int32_t actionButton, int32_t flags,
6127 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006129 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6130 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131 PointerCoords pointerCoords[MAX_POINTERS];
6132 PointerProperties pointerProperties[MAX_POINTERS];
6133 uint32_t pointerCount = 0;
6134 while (!idBits.isEmpty()) {
6135 uint32_t id = idBits.clearFirstMarkedBit();
6136 uint32_t index = idToIndex[id];
6137 pointerProperties[pointerCount].copyFrom(properties[index]);
6138 pointerCoords[pointerCount].copyFrom(coords[index]);
6139
6140 if (changedId >= 0 && id == uint32_t(changedId)) {
6141 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6142 }
6143
6144 pointerCount += 1;
6145 }
6146
6147 ALOG_ASSERT(pointerCount != 0);
6148
6149 if (changedId >= 0 && pointerCount == 1) {
6150 // Replace initial down and final up action.
6151 // We can compare the action without masking off the changed pointer index
6152 // because we know the index is 0.
6153 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6154 action = AMOTION_EVENT_ACTION_DOWN;
6155 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6156 action = AMOTION_EVENT_ACTION_UP;
6157 } else {
6158 // Can't happen.
6159 ALOG_ASSERT(false);
6160 }
6161 }
6162
6163 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006164 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006165 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6166 xPrecision, yPrecision, downTime);
6167 getListener()->notifyMotion(&args);
6168}
6169
6170bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6171 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6172 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6173 BitSet32 idBits) const {
6174 bool changed = false;
6175 while (!idBits.isEmpty()) {
6176 uint32_t id = idBits.clearFirstMarkedBit();
6177 uint32_t inIndex = inIdToIndex[id];
6178 uint32_t outIndex = outIdToIndex[id];
6179
6180 const PointerProperties& curInProperties = inProperties[inIndex];
6181 const PointerCoords& curInCoords = inCoords[inIndex];
6182 PointerProperties& curOutProperties = outProperties[outIndex];
6183 PointerCoords& curOutCoords = outCoords[outIndex];
6184
6185 if (curInProperties != curOutProperties) {
6186 curOutProperties.copyFrom(curInProperties);
6187 changed = true;
6188 }
6189
6190 if (curInCoords != curOutCoords) {
6191 curOutCoords.copyFrom(curInCoords);
6192 changed = true;
6193 }
6194 }
6195 return changed;
6196}
6197
6198void TouchInputMapper::fadePointer() {
6199 if (mPointerController != NULL) {
6200 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6201 }
6202}
6203
Jeff Brownc9aa6282015-02-11 19:03:28 -08006204void TouchInputMapper::cancelTouch(nsecs_t when) {
6205 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wrightfbbaf2e2015-06-22 16:18:21 +01006206 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006207}
6208
Michael Wrightd02c5b62014-02-10 15:10:22 -08006209bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6210 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6211 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6212}
6213
6214const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6215 int32_t x, int32_t y) {
6216 size_t numVirtualKeys = mVirtualKeys.size();
6217 for (size_t i = 0; i < numVirtualKeys; i++) {
6218 const VirtualKey& virtualKey = mVirtualKeys[i];
6219
6220#if DEBUG_VIRTUAL_KEYS
6221 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6222 "left=%d, top=%d, right=%d, bottom=%d",
6223 x, y,
6224 virtualKey.keyCode, virtualKey.scanCode,
6225 virtualKey.hitLeft, virtualKey.hitTop,
6226 virtualKey.hitRight, virtualKey.hitBottom);
6227#endif
6228
6229 if (virtualKey.isHit(x, y)) {
6230 return & virtualKey;
6231 }
6232 }
6233
6234 return NULL;
6235}
6236
Michael Wright842500e2015-03-13 17:32:02 -07006237void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6238 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6239 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240
Michael Wright842500e2015-03-13 17:32:02 -07006241 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006242
6243 if (currentPointerCount == 0) {
6244 // No pointers to assign.
6245 return;
6246 }
6247
6248 if (lastPointerCount == 0) {
6249 // All pointers are new.
6250 for (uint32_t i = 0; i < currentPointerCount; i++) {
6251 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006252 current->rawPointerData.pointers[i].id = id;
6253 current->rawPointerData.idToIndex[id] = i;
6254 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255 }
6256 return;
6257 }
6258
6259 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006260 && current->rawPointerData.pointers[0].toolType
6261 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006263 uint32_t id = last->rawPointerData.pointers[0].id;
6264 current->rawPointerData.pointers[0].id = id;
6265 current->rawPointerData.idToIndex[id] = 0;
6266 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 return;
6268 }
6269
6270 // General case.
6271 // We build a heap of squared euclidean distances between current and last pointers
6272 // associated with the current and last pointer indices. Then, we find the best
6273 // match (by distance) for each current pointer.
6274 // The pointers must have the same tool type but it is possible for them to
6275 // transition from hovering to touching or vice-versa while retaining the same id.
6276 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6277
6278 uint32_t heapSize = 0;
6279 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6280 currentPointerIndex++) {
6281 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6282 lastPointerIndex++) {
6283 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006284 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006286 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287 if (currentPointer.toolType == lastPointer.toolType) {
6288 int64_t deltaX = currentPointer.x - lastPointer.x;
6289 int64_t deltaY = currentPointer.y - lastPointer.y;
6290
6291 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6292
6293 // Insert new element into the heap (sift up).
6294 heap[heapSize].currentPointerIndex = currentPointerIndex;
6295 heap[heapSize].lastPointerIndex = lastPointerIndex;
6296 heap[heapSize].distance = distance;
6297 heapSize += 1;
6298 }
6299 }
6300 }
6301
6302 // Heapify
6303 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6304 startIndex -= 1;
6305 for (uint32_t parentIndex = startIndex; ;) {
6306 uint32_t childIndex = parentIndex * 2 + 1;
6307 if (childIndex >= heapSize) {
6308 break;
6309 }
6310
6311 if (childIndex + 1 < heapSize
6312 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6313 childIndex += 1;
6314 }
6315
6316 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6317 break;
6318 }
6319
6320 swap(heap[parentIndex], heap[childIndex]);
6321 parentIndex = childIndex;
6322 }
6323 }
6324
6325#if DEBUG_POINTER_ASSIGNMENT
6326 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6327 for (size_t i = 0; i < heapSize; i++) {
6328 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6329 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6330 heap[i].distance);
6331 }
6332#endif
6333
6334 // Pull matches out by increasing order of distance.
6335 // To avoid reassigning pointers that have already been matched, the loop keeps track
6336 // of which last and current pointers have been matched using the matchedXXXBits variables.
6337 // It also tracks the used pointer id bits.
6338 BitSet32 matchedLastBits(0);
6339 BitSet32 matchedCurrentBits(0);
6340 BitSet32 usedIdBits(0);
6341 bool first = true;
6342 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6343 while (heapSize > 0) {
6344 if (first) {
6345 // The first time through the loop, we just consume the root element of
6346 // the heap (the one with smallest distance).
6347 first = false;
6348 } else {
6349 // Previous iterations consumed the root element of the heap.
6350 // Pop root element off of the heap (sift down).
6351 heap[0] = heap[heapSize];
6352 for (uint32_t parentIndex = 0; ;) {
6353 uint32_t childIndex = parentIndex * 2 + 1;
6354 if (childIndex >= heapSize) {
6355 break;
6356 }
6357
6358 if (childIndex + 1 < heapSize
6359 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6360 childIndex += 1;
6361 }
6362
6363 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6364 break;
6365 }
6366
6367 swap(heap[parentIndex], heap[childIndex]);
6368 parentIndex = childIndex;
6369 }
6370
6371#if DEBUG_POINTER_ASSIGNMENT
6372 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6373 for (size_t i = 0; i < heapSize; i++) {
6374 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6375 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6376 heap[i].distance);
6377 }
6378#endif
6379 }
6380
6381 heapSize -= 1;
6382
6383 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6384 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6385
6386 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6387 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6388
6389 matchedCurrentBits.markBit(currentPointerIndex);
6390 matchedLastBits.markBit(lastPointerIndex);
6391
Michael Wright842500e2015-03-13 17:32:02 -07006392 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6393 current->rawPointerData.pointers[currentPointerIndex].id = id;
6394 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6395 current->rawPointerData.markIdBit(id,
6396 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397 usedIdBits.markBit(id);
6398
6399#if DEBUG_POINTER_ASSIGNMENT
6400 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6401 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6402#endif
6403 break;
6404 }
6405 }
6406
6407 // Assign fresh ids to pointers that were not matched in the process.
6408 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6409 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6410 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6411
Michael Wright842500e2015-03-13 17:32:02 -07006412 current->rawPointerData.pointers[currentPointerIndex].id = id;
6413 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6414 current->rawPointerData.markIdBit(id,
6415 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416
6417#if DEBUG_POINTER_ASSIGNMENT
6418 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6419 currentPointerIndex, id);
6420#endif
6421 }
6422}
6423
6424int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6425 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6426 return AKEY_STATE_VIRTUAL;
6427 }
6428
6429 size_t numVirtualKeys = mVirtualKeys.size();
6430 for (size_t i = 0; i < numVirtualKeys; i++) {
6431 const VirtualKey& virtualKey = mVirtualKeys[i];
6432 if (virtualKey.keyCode == keyCode) {
6433 return AKEY_STATE_UP;
6434 }
6435 }
6436
6437 return AKEY_STATE_UNKNOWN;
6438}
6439
6440int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6441 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6442 return AKEY_STATE_VIRTUAL;
6443 }
6444
6445 size_t numVirtualKeys = mVirtualKeys.size();
6446 for (size_t i = 0; i < numVirtualKeys; i++) {
6447 const VirtualKey& virtualKey = mVirtualKeys[i];
6448 if (virtualKey.scanCode == scanCode) {
6449 return AKEY_STATE_UP;
6450 }
6451 }
6452
6453 return AKEY_STATE_UNKNOWN;
6454}
6455
6456bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6457 const int32_t* keyCodes, uint8_t* outFlags) {
6458 size_t numVirtualKeys = mVirtualKeys.size();
6459 for (size_t i = 0; i < numVirtualKeys; i++) {
6460 const VirtualKey& virtualKey = mVirtualKeys[i];
6461
6462 for (size_t i = 0; i < numCodes; i++) {
6463 if (virtualKey.keyCode == keyCodes[i]) {
6464 outFlags[i] = 1;
6465 }
6466 }
6467 }
6468
6469 return true;
6470}
6471
6472
6473// --- SingleTouchInputMapper ---
6474
6475SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6476 TouchInputMapper(device) {
6477}
6478
6479SingleTouchInputMapper::~SingleTouchInputMapper() {
6480}
6481
6482void SingleTouchInputMapper::reset(nsecs_t when) {
6483 mSingleTouchMotionAccumulator.reset(getDevice());
6484
6485 TouchInputMapper::reset(when);
6486}
6487
6488void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6489 TouchInputMapper::process(rawEvent);
6490
6491 mSingleTouchMotionAccumulator.process(rawEvent);
6492}
6493
Michael Wright842500e2015-03-13 17:32:02 -07006494void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006496 outState->rawPointerData.pointerCount = 1;
6497 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006498
6499 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6500 && (mTouchButtonAccumulator.isHovering()
6501 || (mRawPointerAxes.pressure.valid
6502 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006503 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006504
Michael Wright842500e2015-03-13 17:32:02 -07006505 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506 outPointer.id = 0;
6507 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6508 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6509 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6510 outPointer.touchMajor = 0;
6511 outPointer.touchMinor = 0;
6512 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6513 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6514 outPointer.orientation = 0;
6515 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6516 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6517 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6518 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6519 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6520 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6521 }
6522 outPointer.isHovering = isHovering;
6523 }
6524}
6525
6526void SingleTouchInputMapper::configureRawPointerAxes() {
6527 TouchInputMapper::configureRawPointerAxes();
6528
6529 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6530 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6531 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6532 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6533 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6534 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6535 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6536}
6537
6538bool SingleTouchInputMapper::hasStylus() const {
6539 return mTouchButtonAccumulator.hasStylus();
6540}
6541
6542
6543// --- MultiTouchInputMapper ---
6544
6545MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6546 TouchInputMapper(device) {
6547}
6548
6549MultiTouchInputMapper::~MultiTouchInputMapper() {
6550}
6551
6552void MultiTouchInputMapper::reset(nsecs_t when) {
6553 mMultiTouchMotionAccumulator.reset(getDevice());
6554
6555 mPointerIdBits.clear();
6556
6557 TouchInputMapper::reset(when);
6558}
6559
6560void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6561 TouchInputMapper::process(rawEvent);
6562
6563 mMultiTouchMotionAccumulator.process(rawEvent);
6564}
6565
Michael Wright842500e2015-03-13 17:32:02 -07006566void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6568 size_t outCount = 0;
6569 BitSet32 newPointerIdBits;
6570
6571 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6572 const MultiTouchMotionAccumulator::Slot* inSlot =
6573 mMultiTouchMotionAccumulator.getSlot(inIndex);
6574 if (!inSlot->isInUse()) {
6575 continue;
6576 }
6577
6578 if (outCount >= MAX_POINTERS) {
6579#if DEBUG_POINTERS
6580 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6581 "ignoring the rest.",
6582 getDeviceName().string(), MAX_POINTERS);
6583#endif
6584 break; // too many fingers!
6585 }
6586
Michael Wright842500e2015-03-13 17:32:02 -07006587 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588 outPointer.x = inSlot->getX();
6589 outPointer.y = inSlot->getY();
6590 outPointer.pressure = inSlot->getPressure();
6591 outPointer.touchMajor = inSlot->getTouchMajor();
6592 outPointer.touchMinor = inSlot->getTouchMinor();
6593 outPointer.toolMajor = inSlot->getToolMajor();
6594 outPointer.toolMinor = inSlot->getToolMinor();
6595 outPointer.orientation = inSlot->getOrientation();
6596 outPointer.distance = inSlot->getDistance();
6597 outPointer.tiltX = 0;
6598 outPointer.tiltY = 0;
6599
6600 outPointer.toolType = inSlot->getToolType();
6601 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6602 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6603 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6604 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6605 }
6606 }
6607
6608 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6609 && (mTouchButtonAccumulator.isHovering()
6610 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6611 outPointer.isHovering = isHovering;
6612
6613 // Assign pointer id using tracking id if available.
Michael Wright842500e2015-03-13 17:32:02 -07006614 mHavePointerIds = true;
6615 int32_t trackingId = inSlot->getTrackingId();
6616 int32_t id = -1;
6617 if (trackingId >= 0) {
6618 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6619 uint32_t n = idBits.clearFirstMarkedBit();
6620 if (mPointerTrackingIdMap[n] == trackingId) {
6621 id = n;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006622 }
Michael Wright842500e2015-03-13 17:32:02 -07006623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006624
Michael Wright842500e2015-03-13 17:32:02 -07006625 if (id < 0 && !mPointerIdBits.isFull()) {
6626 id = mPointerIdBits.markFirstUnmarkedBit();
6627 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628 }
Michael Wright842500e2015-03-13 17:32:02 -07006629 }
6630 if (id < 0) {
6631 mHavePointerIds = false;
6632 outState->rawPointerData.clearIdBits();
6633 newPointerIdBits.clear();
6634 } else {
6635 outPointer.id = id;
6636 outState->rawPointerData.idToIndex[id] = outCount;
6637 outState->rawPointerData.markIdBit(id, isHovering);
6638 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006639 }
6640
6641 outCount += 1;
6642 }
6643
Michael Wright842500e2015-03-13 17:32:02 -07006644 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006645 mPointerIdBits = newPointerIdBits;
6646
6647 mMultiTouchMotionAccumulator.finishSync();
6648}
6649
6650void MultiTouchInputMapper::configureRawPointerAxes() {
6651 TouchInputMapper::configureRawPointerAxes();
6652
6653 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6654 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6655 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6656 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6657 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6658 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6659 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6660 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6661 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6662 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6663 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6664
6665 if (mRawPointerAxes.trackingId.valid
6666 && mRawPointerAxes.slot.valid
6667 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6668 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6669 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006670 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6671 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672 getDeviceName().string(), slotCount, MAX_SLOTS);
6673 slotCount = MAX_SLOTS;
6674 }
6675 mMultiTouchMotionAccumulator.configure(getDevice(),
6676 slotCount, true /*usingSlotsProtocol*/);
6677 } else {
6678 mMultiTouchMotionAccumulator.configure(getDevice(),
6679 MAX_POINTERS, false /*usingSlotsProtocol*/);
6680 }
6681}
6682
6683bool MultiTouchInputMapper::hasStylus() const {
6684 return mMultiTouchMotionAccumulator.hasStylus()
6685 || mTouchButtonAccumulator.hasStylus();
6686}
6687
Michael Wright842500e2015-03-13 17:32:02 -07006688// --- ExternalStylusInputMapper
6689
6690ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6691 InputMapper(device) {
6692
6693}
6694
6695uint32_t ExternalStylusInputMapper::getSources() {
6696 return AINPUT_SOURCE_STYLUS;
6697}
6698
6699void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6700 InputMapper::populateDeviceInfo(info);
6701 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6702 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6703}
6704
6705void ExternalStylusInputMapper::dump(String8& dump) {
6706 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6707 dump.append(INDENT3 "Raw Stylus Axes:\n");
6708 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6709 dump.append(INDENT3 "Stylus State:\n");
6710 dumpStylusState(dump, mStylusState);
6711}
6712
6713void ExternalStylusInputMapper::configure(nsecs_t when,
6714 const InputReaderConfiguration* config, uint32_t changes) {
6715 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6716 mTouchButtonAccumulator.configure(getDevice());
6717}
6718
6719void ExternalStylusInputMapper::reset(nsecs_t when) {
6720 InputDevice* device = getDevice();
6721 mSingleTouchMotionAccumulator.reset(device);
6722 mTouchButtonAccumulator.reset(device);
6723 InputMapper::reset(when);
6724}
6725
6726void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6727 mSingleTouchMotionAccumulator.process(rawEvent);
6728 mTouchButtonAccumulator.process(rawEvent);
6729
6730 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6731 sync(rawEvent->when);
6732 }
6733}
6734
6735void ExternalStylusInputMapper::sync(nsecs_t when) {
6736 mStylusState.clear();
6737
6738 mStylusState.when = when;
6739
Michael Wright45ccacf2015-04-21 19:01:58 +01006740 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6741 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6742 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6743 }
6744
Michael Wright842500e2015-03-13 17:32:02 -07006745 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6746 if (mRawPressureAxis.valid) {
6747 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6748 } else if (mTouchButtonAccumulator.isToolActive()) {
6749 mStylusState.pressure = 1.0f;
6750 } else {
6751 mStylusState.pressure = 0.0f;
6752 }
6753
6754 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07006755
6756 mContext->dispatchExternalStylusState(mStylusState);
6757}
6758
Michael Wrightd02c5b62014-02-10 15:10:22 -08006759
6760// --- JoystickInputMapper ---
6761
6762JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6763 InputMapper(device) {
6764}
6765
6766JoystickInputMapper::~JoystickInputMapper() {
6767}
6768
6769uint32_t JoystickInputMapper::getSources() {
6770 return AINPUT_SOURCE_JOYSTICK;
6771}
6772
6773void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6774 InputMapper::populateDeviceInfo(info);
6775
6776 for (size_t i = 0; i < mAxes.size(); i++) {
6777 const Axis& axis = mAxes.valueAt(i);
6778 addMotionRange(axis.axisInfo.axis, axis, info);
6779
6780 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6781 addMotionRange(axis.axisInfo.highAxis, axis, info);
6782
6783 }
6784 }
6785}
6786
6787void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6788 InputDeviceInfo* info) {
6789 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6790 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6791 /* In order to ease the transition for developers from using the old axes
6792 * to the newer, more semantically correct axes, we'll continue to register
6793 * the old axes as duplicates of their corresponding new ones. */
6794 int32_t compatAxis = getCompatAxis(axisId);
6795 if (compatAxis >= 0) {
6796 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6797 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6798 }
6799}
6800
6801/* A mapping from axes the joystick actually has to the axes that should be
6802 * artificially created for compatibility purposes.
6803 * Returns -1 if no compatibility axis is needed. */
6804int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6805 switch(axis) {
6806 case AMOTION_EVENT_AXIS_LTRIGGER:
6807 return AMOTION_EVENT_AXIS_BRAKE;
6808 case AMOTION_EVENT_AXIS_RTRIGGER:
6809 return AMOTION_EVENT_AXIS_GAS;
6810 }
6811 return -1;
6812}
6813
6814void JoystickInputMapper::dump(String8& dump) {
6815 dump.append(INDENT2 "Joystick Input Mapper:\n");
6816
6817 dump.append(INDENT3 "Axes:\n");
6818 size_t numAxes = mAxes.size();
6819 for (size_t i = 0; i < numAxes; i++) {
6820 const Axis& axis = mAxes.valueAt(i);
6821 const char* label = getAxisLabel(axis.axisInfo.axis);
6822 if (label) {
6823 dump.appendFormat(INDENT4 "%s", label);
6824 } else {
6825 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6826 }
6827 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6828 label = getAxisLabel(axis.axisInfo.highAxis);
6829 if (label) {
6830 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6831 } else {
6832 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6833 axis.axisInfo.splitValue);
6834 }
6835 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6836 dump.append(" (invert)");
6837 }
6838
6839 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6840 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6841 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
6842 "highScale=%0.5f, highOffset=%0.5f\n",
6843 axis.scale, axis.offset, axis.highScale, axis.highOffset);
6844 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
6845 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6846 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6847 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6848 }
6849}
6850
6851void JoystickInputMapper::configure(nsecs_t when,
6852 const InputReaderConfiguration* config, uint32_t changes) {
6853 InputMapper::configure(when, config, changes);
6854
6855 if (!changes) { // first time only
6856 // Collect all axes.
6857 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6858 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6859 & INPUT_DEVICE_CLASS_JOYSTICK)) {
6860 continue; // axis must be claimed by a different device
6861 }
6862
6863 RawAbsoluteAxisInfo rawAxisInfo;
6864 getAbsoluteAxisInfo(abs, &rawAxisInfo);
6865 if (rawAxisInfo.valid) {
6866 // Map axis.
6867 AxisInfo axisInfo;
6868 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6869 if (!explicitlyMapped) {
6870 // Axis is not explicitly mapped, will choose a generic axis later.
6871 axisInfo.mode = AxisInfo::MODE_NORMAL;
6872 axisInfo.axis = -1;
6873 }
6874
6875 // Apply flat override.
6876 int32_t rawFlat = axisInfo.flatOverride < 0
6877 ? rawAxisInfo.flat : axisInfo.flatOverride;
6878
6879 // Calculate scaling factors and limits.
6880 Axis axis;
6881 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6882 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6883 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6884 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6885 scale, 0.0f, highScale, 0.0f,
6886 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6887 rawAxisInfo.resolution * scale);
6888 } else if (isCenteredAxis(axisInfo.axis)) {
6889 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6890 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6891 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6892 scale, offset, scale, offset,
6893 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6894 rawAxisInfo.resolution * scale);
6895 } else {
6896 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6897 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6898 scale, 0.0f, scale, 0.0f,
6899 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6900 rawAxisInfo.resolution * scale);
6901 }
6902
6903 // To eliminate noise while the joystick is at rest, filter out small variations
6904 // in axis values up front.
6905 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
6906
6907 mAxes.add(abs, axis);
6908 }
6909 }
6910
6911 // If there are too many axes, start dropping them.
6912 // Prefer to keep explicitly mapped axes.
6913 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006914 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006915 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
6916 pruneAxes(true);
6917 pruneAxes(false);
6918 }
6919
6920 // Assign generic axis ids to remaining axes.
6921 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
6922 size_t numAxes = mAxes.size();
6923 for (size_t i = 0; i < numAxes; i++) {
6924 Axis& axis = mAxes.editValueAt(i);
6925 if (axis.axisInfo.axis < 0) {
6926 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
6927 && haveAxis(nextGenericAxisId)) {
6928 nextGenericAxisId += 1;
6929 }
6930
6931 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
6932 axis.axisInfo.axis = nextGenericAxisId;
6933 nextGenericAxisId += 1;
6934 } else {
6935 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
6936 "have already been assigned to other axes.",
6937 getDeviceName().string(), mAxes.keyAt(i));
6938 mAxes.removeItemsAt(i--);
6939 numAxes -= 1;
6940 }
6941 }
6942 }
6943 }
6944}
6945
6946bool JoystickInputMapper::haveAxis(int32_t axisId) {
6947 size_t numAxes = mAxes.size();
6948 for (size_t i = 0; i < numAxes; i++) {
6949 const Axis& axis = mAxes.valueAt(i);
6950 if (axis.axisInfo.axis == axisId
6951 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
6952 && axis.axisInfo.highAxis == axisId)) {
6953 return true;
6954 }
6955 }
6956 return false;
6957}
6958
6959void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
6960 size_t i = mAxes.size();
6961 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
6962 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
6963 continue;
6964 }
6965 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
6966 getDeviceName().string(), mAxes.keyAt(i));
6967 mAxes.removeItemsAt(i);
6968 }
6969}
6970
6971bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
6972 switch (axis) {
6973 case AMOTION_EVENT_AXIS_X:
6974 case AMOTION_EVENT_AXIS_Y:
6975 case AMOTION_EVENT_AXIS_Z:
6976 case AMOTION_EVENT_AXIS_RX:
6977 case AMOTION_EVENT_AXIS_RY:
6978 case AMOTION_EVENT_AXIS_RZ:
6979 case AMOTION_EVENT_AXIS_HAT_X:
6980 case AMOTION_EVENT_AXIS_HAT_Y:
6981 case AMOTION_EVENT_AXIS_ORIENTATION:
6982 case AMOTION_EVENT_AXIS_RUDDER:
6983 case AMOTION_EVENT_AXIS_WHEEL:
6984 return true;
6985 default:
6986 return false;
6987 }
6988}
6989
6990void JoystickInputMapper::reset(nsecs_t when) {
6991 // Recenter all axes.
6992 size_t numAxes = mAxes.size();
6993 for (size_t i = 0; i < numAxes; i++) {
6994 Axis& axis = mAxes.editValueAt(i);
6995 axis.resetValue();
6996 }
6997
6998 InputMapper::reset(when);
6999}
7000
7001void JoystickInputMapper::process(const RawEvent* rawEvent) {
7002 switch (rawEvent->type) {
7003 case EV_ABS: {
7004 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7005 if (index >= 0) {
7006 Axis& axis = mAxes.editValueAt(index);
7007 float newValue, highNewValue;
7008 switch (axis.axisInfo.mode) {
7009 case AxisInfo::MODE_INVERT:
7010 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7011 * axis.scale + axis.offset;
7012 highNewValue = 0.0f;
7013 break;
7014 case AxisInfo::MODE_SPLIT:
7015 if (rawEvent->value < axis.axisInfo.splitValue) {
7016 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7017 * axis.scale + axis.offset;
7018 highNewValue = 0.0f;
7019 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7020 newValue = 0.0f;
7021 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7022 * axis.highScale + axis.highOffset;
7023 } else {
7024 newValue = 0.0f;
7025 highNewValue = 0.0f;
7026 }
7027 break;
7028 default:
7029 newValue = rawEvent->value * axis.scale + axis.offset;
7030 highNewValue = 0.0f;
7031 break;
7032 }
7033 axis.newValue = newValue;
7034 axis.highNewValue = highNewValue;
7035 }
7036 break;
7037 }
7038
7039 case EV_SYN:
7040 switch (rawEvent->code) {
7041 case SYN_REPORT:
7042 sync(rawEvent->when, false /*force*/);
7043 break;
7044 }
7045 break;
7046 }
7047}
7048
7049void JoystickInputMapper::sync(nsecs_t when, bool force) {
7050 if (!filterAxes(force)) {
7051 return;
7052 }
7053
7054 int32_t metaState = mContext->getGlobalMetaState();
7055 int32_t buttonState = 0;
7056
7057 PointerProperties pointerProperties;
7058 pointerProperties.clear();
7059 pointerProperties.id = 0;
7060 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7061
7062 PointerCoords pointerCoords;
7063 pointerCoords.clear();
7064
7065 size_t numAxes = mAxes.size();
7066 for (size_t i = 0; i < numAxes; i++) {
7067 const Axis& axis = mAxes.valueAt(i);
7068 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7069 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7070 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7071 axis.highCurrentValue);
7072 }
7073 }
7074
7075 // Moving a joystick axis should not wake the device because joysticks can
7076 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7077 // button will likely wake the device.
7078 // TODO: Use the input device configuration to control this behavior more finely.
7079 uint32_t policyFlags = 0;
7080
7081 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007082 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007083 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7084 getListener()->notifyMotion(&args);
7085}
7086
7087void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7088 int32_t axis, float value) {
7089 pointerCoords->setAxisValue(axis, value);
7090 /* In order to ease the transition for developers from using the old axes
7091 * to the newer, more semantically correct axes, we'll continue to produce
7092 * values for the old axes as mirrors of the value of their corresponding
7093 * new axes. */
7094 int32_t compatAxis = getCompatAxis(axis);
7095 if (compatAxis >= 0) {
7096 pointerCoords->setAxisValue(compatAxis, value);
7097 }
7098}
7099
7100bool JoystickInputMapper::filterAxes(bool force) {
7101 bool atLeastOneSignificantChange = force;
7102 size_t numAxes = mAxes.size();
7103 for (size_t i = 0; i < numAxes; i++) {
7104 Axis& axis = mAxes.editValueAt(i);
7105 if (force || hasValueChangedSignificantly(axis.filter,
7106 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7107 axis.currentValue = axis.newValue;
7108 atLeastOneSignificantChange = true;
7109 }
7110 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7111 if (force || hasValueChangedSignificantly(axis.filter,
7112 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7113 axis.highCurrentValue = axis.highNewValue;
7114 atLeastOneSignificantChange = true;
7115 }
7116 }
7117 }
7118 return atLeastOneSignificantChange;
7119}
7120
7121bool JoystickInputMapper::hasValueChangedSignificantly(
7122 float filter, float newValue, float currentValue, float min, float max) {
7123 if (newValue != currentValue) {
7124 // Filter out small changes in value unless the value is converging on the axis
7125 // bounds or center point. This is intended to reduce the amount of information
7126 // sent to applications by particularly noisy joysticks (such as PS3).
7127 if (fabs(newValue - currentValue) > filter
7128 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7129 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7130 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7131 return true;
7132 }
7133 }
7134 return false;
7135}
7136
7137bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7138 float filter, float newValue, float currentValue, float thresholdValue) {
7139 float newDistance = fabs(newValue - thresholdValue);
7140 if (newDistance < filter) {
7141 float oldDistance = fabs(currentValue - thresholdValue);
7142 if (newDistance < oldDistance) {
7143 return true;
7144 }
7145 }
7146 return false;
7147}
7148
7149} // namespace android