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