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