blob: 2705e134b71a07291303f9c70397026201411205 [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
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
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 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2326 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002327 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 getListener()->notifyKey(&args);
2329}
2330
2331ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2332 size_t n = mKeyDowns.size();
2333 for (size_t i = 0; i < n; i++) {
2334 if (mKeyDowns[i].scanCode == scanCode) {
2335 return i;
2336 }
2337 }
2338 return -1;
2339}
2340
2341int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2342 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2343}
2344
2345int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2346 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2347}
2348
2349bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2350 const int32_t* keyCodes, uint8_t* outFlags) {
2351 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2352}
2353
2354int32_t KeyboardInputMapper::getMetaState() {
2355 return mMetaState;
2356}
2357
Andrii Kulian763a3a42016-03-08 10:46:16 -08002358void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2359 updateMetaStateIfNeeded(keyCode, false);
2360}
2361
2362bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2363 int32_t oldMetaState = mMetaState;
2364 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2365 bool metaStateChanged = oldMetaState != newMetaState;
2366 if (metaStateChanged) {
2367 mMetaState = newMetaState;
2368 updateLedState(false);
2369
2370 getContext()->updateGlobalMetaState();
2371 }
2372
2373 return metaStateChanged;
2374}
2375
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376void KeyboardInputMapper::resetLedState() {
2377 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2378 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2379 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2380
2381 updateLedState(true);
2382}
2383
2384void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2385 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2386 ledState.on = false;
2387}
2388
2389void KeyboardInputMapper::updateLedState(bool reset) {
2390 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2391 AMETA_CAPS_LOCK_ON, reset);
2392 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2393 AMETA_NUM_LOCK_ON, reset);
2394 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2395 AMETA_SCROLL_LOCK_ON, reset);
2396}
2397
2398void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2399 int32_t led, int32_t modifier, bool reset) {
2400 if (ledState.avail) {
2401 bool desiredState = (mMetaState & modifier) != 0;
2402 if (reset || ledState.on != desiredState) {
2403 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2404 ledState.on = desiredState;
2405 }
2406 }
2407}
2408
2409
2410// --- CursorInputMapper ---
2411
2412CursorInputMapper::CursorInputMapper(InputDevice* device) :
2413 InputMapper(device) {
2414}
2415
2416CursorInputMapper::~CursorInputMapper() {
2417}
2418
2419uint32_t CursorInputMapper::getSources() {
2420 return mSource;
2421}
2422
2423void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2424 InputMapper::populateDeviceInfo(info);
2425
2426 if (mParameters.mode == Parameters::MODE_POINTER) {
2427 float minX, minY, maxX, maxY;
2428 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2429 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2430 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2431 }
2432 } else {
2433 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2434 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2435 }
2436 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2437
2438 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2439 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2440 }
2441 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2442 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2443 }
2444}
2445
2446void CursorInputMapper::dump(String8& dump) {
2447 dump.append(INDENT2 "Cursor Input Mapper:\n");
2448 dumpParameters(dump);
2449 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2450 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2451 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2452 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2453 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2454 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2455 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2456 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2457 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2458 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2459 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2460 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2461 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002462 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463}
2464
2465void CursorInputMapper::configure(nsecs_t when,
2466 const InputReaderConfiguration* config, uint32_t changes) {
2467 InputMapper::configure(when, config, changes);
2468
2469 if (!changes) { // first time only
2470 mCursorScrollAccumulator.configure(getDevice());
2471
2472 // Configure basic parameters.
2473 configureParameters();
2474
2475 // Configure device mode.
2476 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002477 case Parameters::MODE_POINTER_RELATIVE:
2478 // Should not happen during first time configuration.
2479 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2480 mParameters.mode = Parameters::MODE_POINTER;
2481 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 case Parameters::MODE_POINTER:
2483 mSource = AINPUT_SOURCE_MOUSE;
2484 mXPrecision = 1.0f;
2485 mYPrecision = 1.0f;
2486 mXScale = 1.0f;
2487 mYScale = 1.0f;
2488 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2489 break;
2490 case Parameters::MODE_NAVIGATION:
2491 mSource = AINPUT_SOURCE_TRACKBALL;
2492 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2493 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2494 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2495 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2496 break;
2497 }
2498
2499 mVWheelScale = 1.0f;
2500 mHWheelScale = 1.0f;
2501 }
2502
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002503 if ((!changes && config->pointerCapture)
2504 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2505 if (config->pointerCapture) {
2506 if (mParameters.mode == Parameters::MODE_POINTER) {
2507 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2508 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2509 // Keep PointerController around in order to preserve the pointer position.
2510 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2511 } else {
2512 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2513 }
2514 } else {
2515 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2516 mParameters.mode = Parameters::MODE_POINTER;
2517 mSource = AINPUT_SOURCE_MOUSE;
2518 } else {
2519 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2520 }
2521 }
2522 bumpGeneration();
2523 if (changes) {
2524 getDevice()->notifyReset(when);
2525 }
2526 }
2527
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2529 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2530 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2531 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2532 }
2533
2534 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2535 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2536 DisplayViewport v;
2537 if (config->getDisplayInfo(false /*external*/, &v)) {
2538 mOrientation = v.orientation;
2539 } else {
2540 mOrientation = DISPLAY_ORIENTATION_0;
2541 }
2542 } else {
2543 mOrientation = DISPLAY_ORIENTATION_0;
2544 }
2545 bumpGeneration();
2546 }
2547}
2548
2549void CursorInputMapper::configureParameters() {
2550 mParameters.mode = Parameters::MODE_POINTER;
2551 String8 cursorModeString;
2552 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2553 if (cursorModeString == "navigation") {
2554 mParameters.mode = Parameters::MODE_NAVIGATION;
2555 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2556 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2557 }
2558 }
2559
2560 mParameters.orientationAware = false;
2561 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2562 mParameters.orientationAware);
2563
2564 mParameters.hasAssociatedDisplay = false;
2565 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2566 mParameters.hasAssociatedDisplay = true;
2567 }
2568}
2569
2570void CursorInputMapper::dumpParameters(String8& dump) {
2571 dump.append(INDENT3 "Parameters:\n");
2572 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2573 toString(mParameters.hasAssociatedDisplay));
2574
2575 switch (mParameters.mode) {
2576 case Parameters::MODE_POINTER:
2577 dump.append(INDENT4 "Mode: pointer\n");
2578 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002579 case Parameters::MODE_POINTER_RELATIVE:
2580 dump.append(INDENT4 "Mode: relative pointer\n");
2581 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 case Parameters::MODE_NAVIGATION:
2583 dump.append(INDENT4 "Mode: navigation\n");
2584 break;
2585 default:
2586 ALOG_ASSERT(false);
2587 }
2588
2589 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2590 toString(mParameters.orientationAware));
2591}
2592
2593void CursorInputMapper::reset(nsecs_t when) {
2594 mButtonState = 0;
2595 mDownTime = 0;
2596
2597 mPointerVelocityControl.reset();
2598 mWheelXVelocityControl.reset();
2599 mWheelYVelocityControl.reset();
2600
2601 mCursorButtonAccumulator.reset(getDevice());
2602 mCursorMotionAccumulator.reset(getDevice());
2603 mCursorScrollAccumulator.reset(getDevice());
2604
2605 InputMapper::reset(when);
2606}
2607
2608void CursorInputMapper::process(const RawEvent* rawEvent) {
2609 mCursorButtonAccumulator.process(rawEvent);
2610 mCursorMotionAccumulator.process(rawEvent);
2611 mCursorScrollAccumulator.process(rawEvent);
2612
2613 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2614 sync(rawEvent->when);
2615 }
2616}
2617
2618void CursorInputMapper::sync(nsecs_t when) {
2619 int32_t lastButtonState = mButtonState;
2620 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2621 mButtonState = currentButtonState;
2622
2623 bool wasDown = isPointerDown(lastButtonState);
2624 bool down = isPointerDown(currentButtonState);
2625 bool downChanged;
2626 if (!wasDown && down) {
2627 mDownTime = when;
2628 downChanged = true;
2629 } else if (wasDown && !down) {
2630 downChanged = true;
2631 } else {
2632 downChanged = false;
2633 }
2634 nsecs_t downTime = mDownTime;
2635 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002636 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2637 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638
2639 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2640 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2641 bool moved = deltaX != 0 || deltaY != 0;
2642
2643 // Rotate delta according to orientation if needed.
2644 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2645 && (deltaX != 0.0f || deltaY != 0.0f)) {
2646 rotateDelta(mOrientation, &deltaX, &deltaY);
2647 }
2648
2649 // Move the pointer.
2650 PointerProperties pointerProperties;
2651 pointerProperties.clear();
2652 pointerProperties.id = 0;
2653 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2654
2655 PointerCoords pointerCoords;
2656 pointerCoords.clear();
2657
2658 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2659 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2660 bool scrolled = vscroll != 0 || hscroll != 0;
2661
2662 mWheelYVelocityControl.move(when, NULL, &vscroll);
2663 mWheelXVelocityControl.move(when, &hscroll, NULL);
2664
2665 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2666
2667 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002668 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 if (moved || scrolled || buttonsChanged) {
2670 mPointerController->setPresentation(
2671 PointerControllerInterface::PRESENTATION_POINTER);
2672
2673 if (moved) {
2674 mPointerController->move(deltaX, deltaY);
2675 }
2676
2677 if (buttonsChanged) {
2678 mPointerController->setButtonState(currentButtonState);
2679 }
2680
2681 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2682 }
2683
2684 float x, y;
2685 mPointerController->getPosition(&x, &y);
2686 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2687 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002688 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2689 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 displayId = ADISPLAY_ID_DEFAULT;
2691 } else {
2692 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2693 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2694 displayId = ADISPLAY_ID_NONE;
2695 }
2696
2697 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2698
2699 // Moving an external trackball or mouse should wake the device.
2700 // We don't do this for internal cursor devices to prevent them from waking up
2701 // the device in your pocket.
2702 // TODO: Use the input device configuration to control this behavior more finely.
2703 uint32_t policyFlags = 0;
2704 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002705 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 }
2707
2708 // Synthesize key down from buttons if needed.
2709 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2710 policyFlags, lastButtonState, currentButtonState);
2711
2712 // Send motion event.
2713 if (downChanged || moved || scrolled || buttonsChanged) {
2714 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002715 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 int32_t motionEventAction;
2717 if (downChanged) {
2718 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002719 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2721 } else {
2722 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2723 }
2724
Michael Wright7b159c92015-05-14 14:48:03 +01002725 if (buttonsReleased) {
2726 BitSet32 released(buttonsReleased);
2727 while (!released.isEmpty()) {
2728 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2729 buttonState &= ~actionButton;
2730 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2731 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2732 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2733 displayId, 1, &pointerProperties, &pointerCoords,
2734 mXPrecision, mYPrecision, downTime);
2735 getListener()->notifyMotion(&releaseArgs);
2736 }
2737 }
2738
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002740 motionEventAction, 0, 0, metaState, currentButtonState,
2741 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 displayId, 1, &pointerProperties, &pointerCoords,
2743 mXPrecision, mYPrecision, downTime);
2744 getListener()->notifyMotion(&args);
2745
Michael Wright7b159c92015-05-14 14:48:03 +01002746 if (buttonsPressed) {
2747 BitSet32 pressed(buttonsPressed);
2748 while (!pressed.isEmpty()) {
2749 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2750 buttonState |= actionButton;
2751 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2752 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2753 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2754 displayId, 1, &pointerProperties, &pointerCoords,
2755 mXPrecision, mYPrecision, downTime);
2756 getListener()->notifyMotion(&pressArgs);
2757 }
2758 }
2759
2760 ALOG_ASSERT(buttonState == currentButtonState);
2761
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 // Send hover move after UP to tell the application that the mouse is hovering now.
2763 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002764 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002766 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2768 displayId, 1, &pointerProperties, &pointerCoords,
2769 mXPrecision, mYPrecision, downTime);
2770 getListener()->notifyMotion(&hoverArgs);
2771 }
2772
2773 // Send scroll events.
2774 if (scrolled) {
2775 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2776 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2777
2778 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002779 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 AMOTION_EVENT_EDGE_FLAG_NONE,
2781 displayId, 1, &pointerProperties, &pointerCoords,
2782 mXPrecision, mYPrecision, downTime);
2783 getListener()->notifyMotion(&scrollArgs);
2784 }
2785 }
2786
2787 // Synthesize key up from buttons if needed.
2788 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2789 policyFlags, lastButtonState, currentButtonState);
2790
2791 mCursorMotionAccumulator.finishSync();
2792 mCursorScrollAccumulator.finishSync();
2793}
2794
2795int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2796 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2797 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2798 } else {
2799 return AKEY_STATE_UNKNOWN;
2800 }
2801}
2802
2803void CursorInputMapper::fadePointer() {
2804 if (mPointerController != NULL) {
2805 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2806 }
2807}
2808
Prashant Malani1941ff52015-08-11 18:29:28 -07002809// --- RotaryEncoderInputMapper ---
2810
2811RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2812 InputMapper(device) {
2813 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2814}
2815
2816RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2817}
2818
2819uint32_t RotaryEncoderInputMapper::getSources() {
2820 return mSource;
2821}
2822
2823void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2824 InputMapper::populateDeviceInfo(info);
2825
2826 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002827 float res = 0.0f;
2828 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2829 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2830 }
2831 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2832 mScalingFactor)) {
2833 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2834 "default to 1.0!\n");
2835 mScalingFactor = 1.0f;
2836 }
2837 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2838 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002839 }
2840}
2841
2842void RotaryEncoderInputMapper::dump(String8& dump) {
2843 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2844 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2845 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2846}
2847
2848void RotaryEncoderInputMapper::configure(nsecs_t when,
2849 const InputReaderConfiguration* config, uint32_t changes) {
2850 InputMapper::configure(when, config, changes);
2851 if (!changes) {
2852 mRotaryEncoderScrollAccumulator.configure(getDevice());
2853 }
2854}
2855
2856void RotaryEncoderInputMapper::reset(nsecs_t when) {
2857 mRotaryEncoderScrollAccumulator.reset(getDevice());
2858
2859 InputMapper::reset(when);
2860}
2861
2862void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2863 mRotaryEncoderScrollAccumulator.process(rawEvent);
2864
2865 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2866 sync(rawEvent->when);
2867 }
2868}
2869
2870void RotaryEncoderInputMapper::sync(nsecs_t when) {
2871 PointerCoords pointerCoords;
2872 pointerCoords.clear();
2873
2874 PointerProperties pointerProperties;
2875 pointerProperties.clear();
2876 pointerProperties.id = 0;
2877 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2878
2879 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2880 bool scrolled = scroll != 0;
2881
2882 // This is not a pointer, so it's not associated with a display.
2883 int32_t displayId = ADISPLAY_ID_NONE;
2884
2885 // Moving the rotary encoder should wake the device (if specified).
2886 uint32_t policyFlags = 0;
2887 if (scrolled && getDevice()->isExternal()) {
2888 policyFlags |= POLICY_FLAG_WAKE;
2889 }
2890
2891 // Send motion event.
2892 if (scrolled) {
2893 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002894 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002895
2896 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2897 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2898 AMOTION_EVENT_EDGE_FLAG_NONE,
2899 displayId, 1, &pointerProperties, &pointerCoords,
2900 0, 0, 0);
2901 getListener()->notifyMotion(&scrollArgs);
2902 }
2903
2904 mRotaryEncoderScrollAccumulator.finishSync();
2905}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906
2907// --- TouchInputMapper ---
2908
2909TouchInputMapper::TouchInputMapper(InputDevice* device) :
2910 InputMapper(device),
2911 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2912 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2913 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2914}
2915
2916TouchInputMapper::~TouchInputMapper() {
2917}
2918
2919uint32_t TouchInputMapper::getSources() {
2920 return mSource;
2921}
2922
2923void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2924 InputMapper::populateDeviceInfo(info);
2925
2926 if (mDeviceMode != DEVICE_MODE_DISABLED) {
2927 info->addMotionRange(mOrientedRanges.x);
2928 info->addMotionRange(mOrientedRanges.y);
2929 info->addMotionRange(mOrientedRanges.pressure);
2930
2931 if (mOrientedRanges.haveSize) {
2932 info->addMotionRange(mOrientedRanges.size);
2933 }
2934
2935 if (mOrientedRanges.haveTouchSize) {
2936 info->addMotionRange(mOrientedRanges.touchMajor);
2937 info->addMotionRange(mOrientedRanges.touchMinor);
2938 }
2939
2940 if (mOrientedRanges.haveToolSize) {
2941 info->addMotionRange(mOrientedRanges.toolMajor);
2942 info->addMotionRange(mOrientedRanges.toolMinor);
2943 }
2944
2945 if (mOrientedRanges.haveOrientation) {
2946 info->addMotionRange(mOrientedRanges.orientation);
2947 }
2948
2949 if (mOrientedRanges.haveDistance) {
2950 info->addMotionRange(mOrientedRanges.distance);
2951 }
2952
2953 if (mOrientedRanges.haveTilt) {
2954 info->addMotionRange(mOrientedRanges.tilt);
2955 }
2956
2957 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2958 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2959 0.0f);
2960 }
2961 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2962 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2963 0.0f);
2964 }
2965 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2966 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2967 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2968 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2969 x.fuzz, x.resolution);
2970 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2971 y.fuzz, y.resolution);
2972 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2973 x.fuzz, x.resolution);
2974 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2975 y.fuzz, y.resolution);
2976 }
2977 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2978 }
2979}
2980
2981void TouchInputMapper::dump(String8& dump) {
2982 dump.append(INDENT2 "Touch Input Mapper:\n");
2983 dumpParameters(dump);
2984 dumpVirtualKeys(dump);
2985 dumpRawPointerAxes(dump);
2986 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07002987 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 dumpSurface(dump);
2989
2990 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2991 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2992 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2993 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2994 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2995 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
2996 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
2997 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
2998 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
2999 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3000 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3001 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3002 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3003 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3004 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3005 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3006 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3007
Michael Wright7b159c92015-05-14 14:48:03 +01003008 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003010 mLastRawState.rawPointerData.pointerCount);
3011 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3012 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3014 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3015 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3016 "toolType=%d, isHovering=%s\n", i,
3017 pointer.id, pointer.x, pointer.y, pointer.pressure,
3018 pointer.touchMajor, pointer.touchMinor,
3019 pointer.toolMajor, pointer.toolMinor,
3020 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3021 pointer.toolType, toString(pointer.isHovering));
3022 }
3023
Michael Wright7b159c92015-05-14 14:48:03 +01003024 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003026 mLastCookedState.cookedPointerData.pointerCount);
3027 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3028 const PointerProperties& pointerProperties =
3029 mLastCookedState.cookedPointerData.pointerProperties[i];
3030 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3032 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3033 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3034 "toolType=%d, isHovering=%s\n", i,
3035 pointerProperties.id,
3036 pointerCoords.getX(),
3037 pointerCoords.getY(),
3038 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3039 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3040 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3041 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3042 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3043 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3044 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3045 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3046 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003047 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
3049
Michael Wright842500e2015-03-13 17:32:02 -07003050 dump.append(INDENT3 "Stylus Fusion:\n");
3051 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3052 toString(mExternalStylusConnected));
3053 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3054 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003055 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003056 dump.append(INDENT3 "External Stylus State:\n");
3057 dumpStylusState(dump, mExternalStylusState);
3058
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 if (mDeviceMode == DEVICE_MODE_POINTER) {
3060 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3061 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3062 mPointerXMovementScale);
3063 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3064 mPointerYMovementScale);
3065 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3066 mPointerXZoomScale);
3067 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3068 mPointerYZoomScale);
3069 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3070 mPointerGestureMaxSwipeWidth);
3071 }
3072}
3073
3074void TouchInputMapper::configure(nsecs_t when,
3075 const InputReaderConfiguration* config, uint32_t changes) {
3076 InputMapper::configure(when, config, changes);
3077
3078 mConfig = *config;
3079
3080 if (!changes) { // first time only
3081 // Configure basic parameters.
3082 configureParameters();
3083
3084 // Configure common accumulators.
3085 mCursorScrollAccumulator.configure(getDevice());
3086 mTouchButtonAccumulator.configure(getDevice());
3087
3088 // Configure absolute axis information.
3089 configureRawPointerAxes();
3090
3091 // Prepare input device calibration.
3092 parseCalibration();
3093 resolveCalibration();
3094 }
3095
Michael Wright842500e2015-03-13 17:32:02 -07003096 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003097 // Update location calibration to reflect current settings
3098 updateAffineTransformation();
3099 }
3100
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3102 // Update pointer speed.
3103 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3104 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3105 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3106 }
3107
3108 bool resetNeeded = false;
3109 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3110 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003111 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3112 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 // Configure device sources, surface dimensions, orientation and
3114 // scaling factors.
3115 configureSurface(when, &resetNeeded);
3116 }
3117
3118 if (changes && resetNeeded) {
3119 // Send reset, unless this is the first time the device has been configured,
3120 // in which case the reader will call reset itself after all mappers are ready.
3121 getDevice()->notifyReset(when);
3122 }
3123}
3124
Michael Wright842500e2015-03-13 17:32:02 -07003125void TouchInputMapper::resolveExternalStylusPresence() {
3126 Vector<InputDeviceInfo> devices;
3127 mContext->getExternalStylusDevices(devices);
3128 mExternalStylusConnected = !devices.isEmpty();
3129
3130 if (!mExternalStylusConnected) {
3131 resetExternalStylus();
3132 }
3133}
3134
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135void TouchInputMapper::configureParameters() {
3136 // Use the pointer presentation mode for devices that do not support distinct
3137 // multitouch. The spot-based presentation relies on being able to accurately
3138 // locate two or more fingers on the touch pad.
3139 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003140 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141
3142 String8 gestureModeString;
3143 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3144 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003145 if (gestureModeString == "single-touch") {
3146 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3147 } else if (gestureModeString == "multi-touch") {
3148 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 } else if (gestureModeString != "default") {
3150 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3151 }
3152 }
3153
3154 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3155 // The device is a touch screen.
3156 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3157 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3158 // The device is a pointing device like a track pad.
3159 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3160 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3161 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3162 // The device is a cursor device with a touch pad attached.
3163 // By default don't use the touch pad to move the pointer.
3164 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3165 } else {
3166 // The device is a touch pad of unknown purpose.
3167 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3168 }
3169
3170 mParameters.hasButtonUnderPad=
3171 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3172
3173 String8 deviceTypeString;
3174 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3175 deviceTypeString)) {
3176 if (deviceTypeString == "touchScreen") {
3177 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3178 } else if (deviceTypeString == "touchPad") {
3179 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3180 } else if (deviceTypeString == "touchNavigation") {
3181 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3182 } else if (deviceTypeString == "pointer") {
3183 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3184 } else if (deviceTypeString != "default") {
3185 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3186 }
3187 }
3188
3189 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3190 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3191 mParameters.orientationAware);
3192
3193 mParameters.hasAssociatedDisplay = false;
3194 mParameters.associatedDisplayIsExternal = false;
3195 if (mParameters.orientationAware
3196 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3197 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3198 mParameters.hasAssociatedDisplay = true;
3199 mParameters.associatedDisplayIsExternal =
3200 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3201 && getDevice()->isExternal();
3202 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003203
3204 // Initial downs on external touch devices should wake the device.
3205 // Normally we don't do this for internal touch screens to prevent them from waking
3206 // up in your pocket but you can enable it using the input device configuration.
3207 mParameters.wake = getDevice()->isExternal();
3208 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3209 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210}
3211
3212void TouchInputMapper::dumpParameters(String8& dump) {
3213 dump.append(INDENT3 "Parameters:\n");
3214
3215 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003216 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3217 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003219 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3220 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 break;
3222 default:
3223 assert(false);
3224 }
3225
3226 switch (mParameters.deviceType) {
3227 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3228 dump.append(INDENT4 "DeviceType: touchScreen\n");
3229 break;
3230 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3231 dump.append(INDENT4 "DeviceType: touchPad\n");
3232 break;
3233 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3234 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3235 break;
3236 case Parameters::DEVICE_TYPE_POINTER:
3237 dump.append(INDENT4 "DeviceType: pointer\n");
3238 break;
3239 default:
3240 ALOG_ASSERT(false);
3241 }
3242
3243 dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
3244 toString(mParameters.hasAssociatedDisplay),
3245 toString(mParameters.associatedDisplayIsExternal));
3246 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3247 toString(mParameters.orientationAware));
3248}
3249
3250void TouchInputMapper::configureRawPointerAxes() {
3251 mRawPointerAxes.clear();
3252}
3253
3254void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3255 dump.append(INDENT3 "Raw Touch Axes:\n");
3256 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3257 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3258 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3259 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3260 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3261 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3262 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3263 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3264 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3265 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3266 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3267 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3268 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3269}
3270
Michael Wright842500e2015-03-13 17:32:02 -07003271bool TouchInputMapper::hasExternalStylus() const {
3272 return mExternalStylusConnected;
3273}
3274
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3276 int32_t oldDeviceMode = mDeviceMode;
3277
Michael Wright842500e2015-03-13 17:32:02 -07003278 resolveExternalStylusPresence();
3279
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 // Determine device mode.
3281 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3282 && mConfig.pointerGesturesEnabled) {
3283 mSource = AINPUT_SOURCE_MOUSE;
3284 mDeviceMode = DEVICE_MODE_POINTER;
3285 if (hasStylus()) {
3286 mSource |= AINPUT_SOURCE_STYLUS;
3287 }
3288 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3289 && mParameters.hasAssociatedDisplay) {
3290 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3291 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003292 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 mSource |= AINPUT_SOURCE_STYLUS;
3294 }
Michael Wright2f78b682015-06-12 15:25:08 +01003295 if (hasExternalStylus()) {
3296 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3299 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3300 mDeviceMode = DEVICE_MODE_NAVIGATION;
3301 } else {
3302 mSource = AINPUT_SOURCE_TOUCHPAD;
3303 mDeviceMode = DEVICE_MODE_UNSCALED;
3304 }
3305
3306 // Ensure we have valid X and Y axes.
3307 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3308 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3309 "The device will be inoperable.", getDeviceName().string());
3310 mDeviceMode = DEVICE_MODE_DISABLED;
3311 return;
3312 }
3313
3314 // Raw width and height in the natural orientation.
3315 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3316 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3317
3318 // Get associated display dimensions.
3319 DisplayViewport newViewport;
3320 if (mParameters.hasAssociatedDisplay) {
3321 if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
3322 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3323 "display. The device will be inoperable until the display size "
3324 "becomes available.",
3325 getDeviceName().string());
3326 mDeviceMode = DEVICE_MODE_DISABLED;
3327 return;
3328 }
3329 } else {
3330 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3331 }
3332 bool viewportChanged = mViewport != newViewport;
3333 if (viewportChanged) {
3334 mViewport = newViewport;
3335
3336 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3337 // Convert rotated viewport to natural surface coordinates.
3338 int32_t naturalLogicalWidth, naturalLogicalHeight;
3339 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3340 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3341 int32_t naturalDeviceWidth, naturalDeviceHeight;
3342 switch (mViewport.orientation) {
3343 case DISPLAY_ORIENTATION_90:
3344 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3345 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3346 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3347 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3348 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3349 naturalPhysicalTop = mViewport.physicalLeft;
3350 naturalDeviceWidth = mViewport.deviceHeight;
3351 naturalDeviceHeight = mViewport.deviceWidth;
3352 break;
3353 case DISPLAY_ORIENTATION_180:
3354 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3355 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3356 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3357 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3358 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3359 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3360 naturalDeviceWidth = mViewport.deviceWidth;
3361 naturalDeviceHeight = mViewport.deviceHeight;
3362 break;
3363 case DISPLAY_ORIENTATION_270:
3364 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3365 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3366 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3367 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3368 naturalPhysicalLeft = mViewport.physicalTop;
3369 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3370 naturalDeviceWidth = mViewport.deviceHeight;
3371 naturalDeviceHeight = mViewport.deviceWidth;
3372 break;
3373 case DISPLAY_ORIENTATION_0:
3374 default:
3375 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3376 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3377 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3378 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3379 naturalPhysicalLeft = mViewport.physicalLeft;
3380 naturalPhysicalTop = mViewport.physicalTop;
3381 naturalDeviceWidth = mViewport.deviceWidth;
3382 naturalDeviceHeight = mViewport.deviceHeight;
3383 break;
3384 }
3385
3386 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3387 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3388 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3389 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3390
3391 mSurfaceOrientation = mParameters.orientationAware ?
3392 mViewport.orientation : DISPLAY_ORIENTATION_0;
3393 } else {
3394 mSurfaceWidth = rawWidth;
3395 mSurfaceHeight = rawHeight;
3396 mSurfaceLeft = 0;
3397 mSurfaceTop = 0;
3398 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3399 }
3400 }
3401
3402 // If moving between pointer modes, need to reset some state.
3403 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3404 if (deviceModeChanged) {
3405 mOrientedRanges.clear();
3406 }
3407
3408 // Create pointer controller if needed.
3409 if (mDeviceMode == DEVICE_MODE_POINTER ||
3410 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3411 if (mPointerController == NULL) {
3412 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3413 }
3414 } else {
3415 mPointerController.clear();
3416 }
3417
3418 if (viewportChanged || deviceModeChanged) {
3419 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3420 "display id %d",
3421 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3422 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3423
3424 // Configure X and Y factors.
3425 mXScale = float(mSurfaceWidth) / rawWidth;
3426 mYScale = float(mSurfaceHeight) / rawHeight;
3427 mXTranslate = -mSurfaceLeft;
3428 mYTranslate = -mSurfaceTop;
3429 mXPrecision = 1.0f / mXScale;
3430 mYPrecision = 1.0f / mYScale;
3431
3432 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3433 mOrientedRanges.x.source = mSource;
3434 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3435 mOrientedRanges.y.source = mSource;
3436
3437 configureVirtualKeys();
3438
3439 // Scale factor for terms that are not oriented in a particular axis.
3440 // If the pixels are square then xScale == yScale otherwise we fake it
3441 // by choosing an average.
3442 mGeometricScale = avg(mXScale, mYScale);
3443
3444 // Size of diagonal axis.
3445 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3446
3447 // Size factors.
3448 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3449 if (mRawPointerAxes.touchMajor.valid
3450 && mRawPointerAxes.touchMajor.maxValue != 0) {
3451 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3452 } else if (mRawPointerAxes.toolMajor.valid
3453 && mRawPointerAxes.toolMajor.maxValue != 0) {
3454 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3455 } else {
3456 mSizeScale = 0.0f;
3457 }
3458
3459 mOrientedRanges.haveTouchSize = true;
3460 mOrientedRanges.haveToolSize = true;
3461 mOrientedRanges.haveSize = true;
3462
3463 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3464 mOrientedRanges.touchMajor.source = mSource;
3465 mOrientedRanges.touchMajor.min = 0;
3466 mOrientedRanges.touchMajor.max = diagonalSize;
3467 mOrientedRanges.touchMajor.flat = 0;
3468 mOrientedRanges.touchMajor.fuzz = 0;
3469 mOrientedRanges.touchMajor.resolution = 0;
3470
3471 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3472 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3473
3474 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3475 mOrientedRanges.toolMajor.source = mSource;
3476 mOrientedRanges.toolMajor.min = 0;
3477 mOrientedRanges.toolMajor.max = diagonalSize;
3478 mOrientedRanges.toolMajor.flat = 0;
3479 mOrientedRanges.toolMajor.fuzz = 0;
3480 mOrientedRanges.toolMajor.resolution = 0;
3481
3482 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3483 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3484
3485 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3486 mOrientedRanges.size.source = mSource;
3487 mOrientedRanges.size.min = 0;
3488 mOrientedRanges.size.max = 1.0;
3489 mOrientedRanges.size.flat = 0;
3490 mOrientedRanges.size.fuzz = 0;
3491 mOrientedRanges.size.resolution = 0;
3492 } else {
3493 mSizeScale = 0.0f;
3494 }
3495
3496 // Pressure factors.
3497 mPressureScale = 0;
3498 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3499 || mCalibration.pressureCalibration
3500 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3501 if (mCalibration.havePressureScale) {
3502 mPressureScale = mCalibration.pressureScale;
3503 } else if (mRawPointerAxes.pressure.valid
3504 && mRawPointerAxes.pressure.maxValue != 0) {
3505 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3506 }
3507 }
3508
3509 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3510 mOrientedRanges.pressure.source = mSource;
3511 mOrientedRanges.pressure.min = 0;
3512 mOrientedRanges.pressure.max = 1.0;
3513 mOrientedRanges.pressure.flat = 0;
3514 mOrientedRanges.pressure.fuzz = 0;
3515 mOrientedRanges.pressure.resolution = 0;
3516
3517 // Tilt
3518 mTiltXCenter = 0;
3519 mTiltXScale = 0;
3520 mTiltYCenter = 0;
3521 mTiltYScale = 0;
3522 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3523 if (mHaveTilt) {
3524 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3525 mRawPointerAxes.tiltX.maxValue);
3526 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3527 mRawPointerAxes.tiltY.maxValue);
3528 mTiltXScale = M_PI / 180;
3529 mTiltYScale = M_PI / 180;
3530
3531 mOrientedRanges.haveTilt = true;
3532
3533 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3534 mOrientedRanges.tilt.source = mSource;
3535 mOrientedRanges.tilt.min = 0;
3536 mOrientedRanges.tilt.max = M_PI_2;
3537 mOrientedRanges.tilt.flat = 0;
3538 mOrientedRanges.tilt.fuzz = 0;
3539 mOrientedRanges.tilt.resolution = 0;
3540 }
3541
3542 // Orientation
3543 mOrientationScale = 0;
3544 if (mHaveTilt) {
3545 mOrientedRanges.haveOrientation = true;
3546
3547 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3548 mOrientedRanges.orientation.source = mSource;
3549 mOrientedRanges.orientation.min = -M_PI;
3550 mOrientedRanges.orientation.max = M_PI;
3551 mOrientedRanges.orientation.flat = 0;
3552 mOrientedRanges.orientation.fuzz = 0;
3553 mOrientedRanges.orientation.resolution = 0;
3554 } else if (mCalibration.orientationCalibration !=
3555 Calibration::ORIENTATION_CALIBRATION_NONE) {
3556 if (mCalibration.orientationCalibration
3557 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3558 if (mRawPointerAxes.orientation.valid) {
3559 if (mRawPointerAxes.orientation.maxValue > 0) {
3560 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3561 } else if (mRawPointerAxes.orientation.minValue < 0) {
3562 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3563 } else {
3564 mOrientationScale = 0;
3565 }
3566 }
3567 }
3568
3569 mOrientedRanges.haveOrientation = true;
3570
3571 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3572 mOrientedRanges.orientation.source = mSource;
3573 mOrientedRanges.orientation.min = -M_PI_2;
3574 mOrientedRanges.orientation.max = M_PI_2;
3575 mOrientedRanges.orientation.flat = 0;
3576 mOrientedRanges.orientation.fuzz = 0;
3577 mOrientedRanges.orientation.resolution = 0;
3578 }
3579
3580 // Distance
3581 mDistanceScale = 0;
3582 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3583 if (mCalibration.distanceCalibration
3584 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3585 if (mCalibration.haveDistanceScale) {
3586 mDistanceScale = mCalibration.distanceScale;
3587 } else {
3588 mDistanceScale = 1.0f;
3589 }
3590 }
3591
3592 mOrientedRanges.haveDistance = true;
3593
3594 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3595 mOrientedRanges.distance.source = mSource;
3596 mOrientedRanges.distance.min =
3597 mRawPointerAxes.distance.minValue * mDistanceScale;
3598 mOrientedRanges.distance.max =
3599 mRawPointerAxes.distance.maxValue * mDistanceScale;
3600 mOrientedRanges.distance.flat = 0;
3601 mOrientedRanges.distance.fuzz =
3602 mRawPointerAxes.distance.fuzz * mDistanceScale;
3603 mOrientedRanges.distance.resolution = 0;
3604 }
3605
3606 // Compute oriented precision, scales and ranges.
3607 // Note that the maximum value reported is an inclusive maximum value so it is one
3608 // unit less than the total width or height of surface.
3609 switch (mSurfaceOrientation) {
3610 case DISPLAY_ORIENTATION_90:
3611 case DISPLAY_ORIENTATION_270:
3612 mOrientedXPrecision = mYPrecision;
3613 mOrientedYPrecision = mXPrecision;
3614
3615 mOrientedRanges.x.min = mYTranslate;
3616 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3617 mOrientedRanges.x.flat = 0;
3618 mOrientedRanges.x.fuzz = 0;
3619 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3620
3621 mOrientedRanges.y.min = mXTranslate;
3622 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3623 mOrientedRanges.y.flat = 0;
3624 mOrientedRanges.y.fuzz = 0;
3625 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3626 break;
3627
3628 default:
3629 mOrientedXPrecision = mXPrecision;
3630 mOrientedYPrecision = mYPrecision;
3631
3632 mOrientedRanges.x.min = mXTranslate;
3633 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3634 mOrientedRanges.x.flat = 0;
3635 mOrientedRanges.x.fuzz = 0;
3636 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3637
3638 mOrientedRanges.y.min = mYTranslate;
3639 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3640 mOrientedRanges.y.flat = 0;
3641 mOrientedRanges.y.fuzz = 0;
3642 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3643 break;
3644 }
3645
Jason Gerecke71b16e82014-03-10 09:47:59 -07003646 // Location
3647 updateAffineTransformation();
3648
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 if (mDeviceMode == DEVICE_MODE_POINTER) {
3650 // Compute pointer gesture detection parameters.
3651 float rawDiagonal = hypotf(rawWidth, rawHeight);
3652 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3653
3654 // Scale movements such that one whole swipe of the touch pad covers a
3655 // given area relative to the diagonal size of the display when no acceleration
3656 // is applied.
3657 // Assume that the touch pad has a square aspect ratio such that movements in
3658 // X and Y of the same number of raw units cover the same physical distance.
3659 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3660 * displayDiagonal / rawDiagonal;
3661 mPointerYMovementScale = mPointerXMovementScale;
3662
3663 // Scale zooms to cover a smaller range of the display than movements do.
3664 // This value determines the area around the pointer that is affected by freeform
3665 // pointer gestures.
3666 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3667 * displayDiagonal / rawDiagonal;
3668 mPointerYZoomScale = mPointerXZoomScale;
3669
3670 // Max width between pointers to detect a swipe gesture is more than some fraction
3671 // of the diagonal axis of the touch pad. Touches that are wider than this are
3672 // translated into freeform gestures.
3673 mPointerGestureMaxSwipeWidth =
3674 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3675
3676 // Abort current pointer usages because the state has changed.
3677 abortPointerUsage(when, 0 /*policyFlags*/);
3678 }
3679
3680 // Inform the dispatcher about the changes.
3681 *outResetNeeded = true;
3682 bumpGeneration();
3683 }
3684}
3685
3686void TouchInputMapper::dumpSurface(String8& dump) {
3687 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3688 "logicalFrame=[%d, %d, %d, %d], "
3689 "physicalFrame=[%d, %d, %d, %d], "
3690 "deviceSize=[%d, %d]\n",
3691 mViewport.displayId, mViewport.orientation,
3692 mViewport.logicalLeft, mViewport.logicalTop,
3693 mViewport.logicalRight, mViewport.logicalBottom,
3694 mViewport.physicalLeft, mViewport.physicalTop,
3695 mViewport.physicalRight, mViewport.physicalBottom,
3696 mViewport.deviceWidth, mViewport.deviceHeight);
3697
3698 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3699 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3700 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3701 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3702 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3703}
3704
3705void TouchInputMapper::configureVirtualKeys() {
3706 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3707 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3708
3709 mVirtualKeys.clear();
3710
3711 if (virtualKeyDefinitions.size() == 0) {
3712 return;
3713 }
3714
3715 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3716
3717 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3718 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3719 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3720 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3721
3722 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3723 const VirtualKeyDefinition& virtualKeyDefinition =
3724 virtualKeyDefinitions[i];
3725
3726 mVirtualKeys.add();
3727 VirtualKey& virtualKey = mVirtualKeys.editTop();
3728
3729 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3730 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003731 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003733 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3734 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3736 virtualKey.scanCode);
3737 mVirtualKeys.pop(); // drop the key
3738 continue;
3739 }
3740
3741 virtualKey.keyCode = keyCode;
3742 virtualKey.flags = flags;
3743
3744 // convert the key definition's display coordinates into touch coordinates for a hit box
3745 int32_t halfWidth = virtualKeyDefinition.width / 2;
3746 int32_t halfHeight = virtualKeyDefinition.height / 2;
3747
3748 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3749 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3750 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3751 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3752 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3753 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3754 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3755 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3756 }
3757}
3758
3759void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3760 if (!mVirtualKeys.isEmpty()) {
3761 dump.append(INDENT3 "Virtual Keys:\n");
3762
3763 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3764 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003765 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3767 i, virtualKey.scanCode, virtualKey.keyCode,
3768 virtualKey.hitLeft, virtualKey.hitRight,
3769 virtualKey.hitTop, virtualKey.hitBottom);
3770 }
3771 }
3772}
3773
3774void TouchInputMapper::parseCalibration() {
3775 const PropertyMap& in = getDevice()->getConfiguration();
3776 Calibration& out = mCalibration;
3777
3778 // Size
3779 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3780 String8 sizeCalibrationString;
3781 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3782 if (sizeCalibrationString == "none") {
3783 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3784 } else if (sizeCalibrationString == "geometric") {
3785 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3786 } else if (sizeCalibrationString == "diameter") {
3787 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3788 } else if (sizeCalibrationString == "box") {
3789 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3790 } else if (sizeCalibrationString == "area") {
3791 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3792 } else if (sizeCalibrationString != "default") {
3793 ALOGW("Invalid value for touch.size.calibration: '%s'",
3794 sizeCalibrationString.string());
3795 }
3796 }
3797
3798 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3799 out.sizeScale);
3800 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3801 out.sizeBias);
3802 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3803 out.sizeIsSummed);
3804
3805 // Pressure
3806 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3807 String8 pressureCalibrationString;
3808 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3809 if (pressureCalibrationString == "none") {
3810 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3811 } else if (pressureCalibrationString == "physical") {
3812 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3813 } else if (pressureCalibrationString == "amplitude") {
3814 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3815 } else if (pressureCalibrationString != "default") {
3816 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3817 pressureCalibrationString.string());
3818 }
3819 }
3820
3821 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3822 out.pressureScale);
3823
3824 // Orientation
3825 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3826 String8 orientationCalibrationString;
3827 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3828 if (orientationCalibrationString == "none") {
3829 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3830 } else if (orientationCalibrationString == "interpolated") {
3831 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3832 } else if (orientationCalibrationString == "vector") {
3833 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3834 } else if (orientationCalibrationString != "default") {
3835 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3836 orientationCalibrationString.string());
3837 }
3838 }
3839
3840 // Distance
3841 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3842 String8 distanceCalibrationString;
3843 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3844 if (distanceCalibrationString == "none") {
3845 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3846 } else if (distanceCalibrationString == "scaled") {
3847 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3848 } else if (distanceCalibrationString != "default") {
3849 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3850 distanceCalibrationString.string());
3851 }
3852 }
3853
3854 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3855 out.distanceScale);
3856
3857 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3858 String8 coverageCalibrationString;
3859 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3860 if (coverageCalibrationString == "none") {
3861 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3862 } else if (coverageCalibrationString == "box") {
3863 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3864 } else if (coverageCalibrationString != "default") {
3865 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3866 coverageCalibrationString.string());
3867 }
3868 }
3869}
3870
3871void TouchInputMapper::resolveCalibration() {
3872 // Size
3873 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3874 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3875 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3876 }
3877 } else {
3878 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3879 }
3880
3881 // Pressure
3882 if (mRawPointerAxes.pressure.valid) {
3883 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3884 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3885 }
3886 } else {
3887 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3888 }
3889
3890 // Orientation
3891 if (mRawPointerAxes.orientation.valid) {
3892 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3893 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3894 }
3895 } else {
3896 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3897 }
3898
3899 // Distance
3900 if (mRawPointerAxes.distance.valid) {
3901 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3902 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3903 }
3904 } else {
3905 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3906 }
3907
3908 // Coverage
3909 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3910 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3911 }
3912}
3913
3914void TouchInputMapper::dumpCalibration(String8& dump) {
3915 dump.append(INDENT3 "Calibration:\n");
3916
3917 // Size
3918 switch (mCalibration.sizeCalibration) {
3919 case Calibration::SIZE_CALIBRATION_NONE:
3920 dump.append(INDENT4 "touch.size.calibration: none\n");
3921 break;
3922 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3923 dump.append(INDENT4 "touch.size.calibration: geometric\n");
3924 break;
3925 case Calibration::SIZE_CALIBRATION_DIAMETER:
3926 dump.append(INDENT4 "touch.size.calibration: diameter\n");
3927 break;
3928 case Calibration::SIZE_CALIBRATION_BOX:
3929 dump.append(INDENT4 "touch.size.calibration: box\n");
3930 break;
3931 case Calibration::SIZE_CALIBRATION_AREA:
3932 dump.append(INDENT4 "touch.size.calibration: area\n");
3933 break;
3934 default:
3935 ALOG_ASSERT(false);
3936 }
3937
3938 if (mCalibration.haveSizeScale) {
3939 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3940 mCalibration.sizeScale);
3941 }
3942
3943 if (mCalibration.haveSizeBias) {
3944 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3945 mCalibration.sizeBias);
3946 }
3947
3948 if (mCalibration.haveSizeIsSummed) {
3949 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3950 toString(mCalibration.sizeIsSummed));
3951 }
3952
3953 // Pressure
3954 switch (mCalibration.pressureCalibration) {
3955 case Calibration::PRESSURE_CALIBRATION_NONE:
3956 dump.append(INDENT4 "touch.pressure.calibration: none\n");
3957 break;
3958 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3959 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3960 break;
3961 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3962 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3963 break;
3964 default:
3965 ALOG_ASSERT(false);
3966 }
3967
3968 if (mCalibration.havePressureScale) {
3969 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3970 mCalibration.pressureScale);
3971 }
3972
3973 // Orientation
3974 switch (mCalibration.orientationCalibration) {
3975 case Calibration::ORIENTATION_CALIBRATION_NONE:
3976 dump.append(INDENT4 "touch.orientation.calibration: none\n");
3977 break;
3978 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3979 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3980 break;
3981 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3982 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3983 break;
3984 default:
3985 ALOG_ASSERT(false);
3986 }
3987
3988 // Distance
3989 switch (mCalibration.distanceCalibration) {
3990 case Calibration::DISTANCE_CALIBRATION_NONE:
3991 dump.append(INDENT4 "touch.distance.calibration: none\n");
3992 break;
3993 case Calibration::DISTANCE_CALIBRATION_SCALED:
3994 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3995 break;
3996 default:
3997 ALOG_ASSERT(false);
3998 }
3999
4000 if (mCalibration.haveDistanceScale) {
4001 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4002 mCalibration.distanceScale);
4003 }
4004
4005 switch (mCalibration.coverageCalibration) {
4006 case Calibration::COVERAGE_CALIBRATION_NONE:
4007 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4008 break;
4009 case Calibration::COVERAGE_CALIBRATION_BOX:
4010 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4011 break;
4012 default:
4013 ALOG_ASSERT(false);
4014 }
4015}
4016
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004017void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4018 dump.append(INDENT3 "Affine Transformation:\n");
4019
4020 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4021 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4022 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4023 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4024 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4025 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4026}
4027
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004028void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004029 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4030 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004031}
4032
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033void TouchInputMapper::reset(nsecs_t when) {
4034 mCursorButtonAccumulator.reset(getDevice());
4035 mCursorScrollAccumulator.reset(getDevice());
4036 mTouchButtonAccumulator.reset(getDevice());
4037
4038 mPointerVelocityControl.reset();
4039 mWheelXVelocityControl.reset();
4040 mWheelYVelocityControl.reset();
4041
Michael Wright842500e2015-03-13 17:32:02 -07004042 mRawStatesPending.clear();
4043 mCurrentRawState.clear();
4044 mCurrentCookedState.clear();
4045 mLastRawState.clear();
4046 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 mPointerUsage = POINTER_USAGE_NONE;
4048 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004049 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004050 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 mDownTime = 0;
4052
4053 mCurrentVirtualKey.down = false;
4054
4055 mPointerGesture.reset();
4056 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004057 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
4059 if (mPointerController != NULL) {
4060 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4061 mPointerController->clearSpots();
4062 }
4063
4064 InputMapper::reset(when);
4065}
4066
Michael Wright842500e2015-03-13 17:32:02 -07004067void TouchInputMapper::resetExternalStylus() {
4068 mExternalStylusState.clear();
4069 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004070 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004071 mExternalStylusDataPending = false;
4072}
4073
Michael Wright43fd19f2015-04-21 19:02:58 +01004074void TouchInputMapper::clearStylusDataPendingFlags() {
4075 mExternalStylusDataPending = false;
4076 mExternalStylusFusionTimeout = LLONG_MAX;
4077}
4078
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079void TouchInputMapper::process(const RawEvent* rawEvent) {
4080 mCursorButtonAccumulator.process(rawEvent);
4081 mCursorScrollAccumulator.process(rawEvent);
4082 mTouchButtonAccumulator.process(rawEvent);
4083
4084 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4085 sync(rawEvent->when);
4086 }
4087}
4088
4089void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004090 const RawState* last = mRawStatesPending.isEmpty() ?
4091 &mCurrentRawState : &mRawStatesPending.top();
4092
4093 // Push a new state.
4094 mRawStatesPending.push();
4095 RawState* next = &mRawStatesPending.editTop();
4096 next->clear();
4097 next->when = when;
4098
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004100 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 | mCursorButtonAccumulator.getButtonState();
4102
Michael Wright842500e2015-03-13 17:32:02 -07004103 // Sync scroll
4104 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4105 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 mCursorScrollAccumulator.finishSync();
4107
Michael Wright842500e2015-03-13 17:32:02 -07004108 // Sync touch
4109 syncTouch(when, next);
4110
4111 // Assign pointer ids.
4112 if (!mHavePointerIds) {
4113 assignPointerIds(last, next);
4114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115
4116#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004117 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4118 "hovering ids 0x%08x -> 0x%08x",
4119 last->rawPointerData.pointerCount,
4120 next->rawPointerData.pointerCount,
4121 last->rawPointerData.touchingIdBits.value,
4122 next->rawPointerData.touchingIdBits.value,
4123 last->rawPointerData.hoveringIdBits.value,
4124 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125#endif
4126
Michael Wright842500e2015-03-13 17:32:02 -07004127 processRawTouches(false /*timeout*/);
4128}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129
Michael Wright842500e2015-03-13 17:32:02 -07004130void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4132 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004133 mCurrentRawState.clear();
4134 mRawStatesPending.clear();
4135 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 }
4137
Michael Wright842500e2015-03-13 17:32:02 -07004138 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4139 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4140 // touching the current state will only observe the events that have been dispatched to the
4141 // rest of the pipeline.
4142 const size_t N = mRawStatesPending.size();
4143 size_t count;
4144 for(count = 0; count < N; count++) {
4145 const RawState& next = mRawStatesPending[count];
4146
4147 // A failure to assign the stylus id means that we're waiting on stylus data
4148 // and so should defer the rest of the pipeline.
4149 if (assignExternalStylusId(next, timeout)) {
4150 break;
4151 }
4152
4153 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004154 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004155 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004156 if (mCurrentRawState.when < mLastRawState.when) {
4157 mCurrentRawState.when = mLastRawState.when;
4158 }
Michael Wright842500e2015-03-13 17:32:02 -07004159 cookAndDispatch(mCurrentRawState.when);
4160 }
4161 if (count != 0) {
4162 mRawStatesPending.removeItemsAt(0, count);
4163 }
4164
Michael Wright842500e2015-03-13 17:32:02 -07004165 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004166 if (timeout) {
4167 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4168 clearStylusDataPendingFlags();
4169 mCurrentRawState.copyFrom(mLastRawState);
4170#if DEBUG_STYLUS_FUSION
4171 ALOGD("Timeout expired, synthesizing event with new stylus data");
4172#endif
4173 cookAndDispatch(when);
4174 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4175 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4176 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4177 }
Michael Wright842500e2015-03-13 17:32:02 -07004178 }
4179}
4180
4181void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4182 // Always start with a clean state.
4183 mCurrentCookedState.clear();
4184
4185 // Apply stylus buttons to current raw state.
4186 applyExternalStylusButtonState(when);
4187
4188 // Handle policy on initial down or hover events.
4189 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4190 && mCurrentRawState.rawPointerData.pointerCount != 0;
4191
4192 uint32_t policyFlags = 0;
4193 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4194 if (initialDown || buttonsPressed) {
4195 // If this is a touch screen, hide the pointer on an initial down.
4196 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4197 getContext()->fadePointer();
4198 }
4199
4200 if (mParameters.wake) {
4201 policyFlags |= POLICY_FLAG_WAKE;
4202 }
4203 }
4204
4205 // Consume raw off-screen touches before cooking pointer data.
4206 // If touches are consumed, subsequent code will not receive any pointer data.
4207 if (consumeRawTouches(when, policyFlags)) {
4208 mCurrentRawState.rawPointerData.clear();
4209 }
4210
4211 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4212 // with cooked pointer data that has the same ids and indices as the raw data.
4213 // The following code can use either the raw or cooked data, as needed.
4214 cookPointerData();
4215
4216 // Apply stylus pressure to current cooked state.
4217 applyExternalStylusTouchState(when);
4218
4219 // Synthesize key down from raw buttons if needed.
4220 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004221 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004222
4223 // Dispatch the touches either directly or by translation through a pointer on screen.
4224 if (mDeviceMode == DEVICE_MODE_POINTER) {
4225 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4226 !idBits.isEmpty(); ) {
4227 uint32_t id = idBits.clearFirstMarkedBit();
4228 const RawPointerData::Pointer& pointer =
4229 mCurrentRawState.rawPointerData.pointerForId(id);
4230 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4231 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4232 mCurrentCookedState.stylusIdBits.markBit(id);
4233 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4234 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4235 mCurrentCookedState.fingerIdBits.markBit(id);
4236 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4237 mCurrentCookedState.mouseIdBits.markBit(id);
4238 }
4239 }
4240 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4241 !idBits.isEmpty(); ) {
4242 uint32_t id = idBits.clearFirstMarkedBit();
4243 const RawPointerData::Pointer& pointer =
4244 mCurrentRawState.rawPointerData.pointerForId(id);
4245 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4246 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4247 mCurrentCookedState.stylusIdBits.markBit(id);
4248 }
4249 }
4250
4251 // Stylus takes precedence over all tools, then mouse, then finger.
4252 PointerUsage pointerUsage = mPointerUsage;
4253 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4254 mCurrentCookedState.mouseIdBits.clear();
4255 mCurrentCookedState.fingerIdBits.clear();
4256 pointerUsage = POINTER_USAGE_STYLUS;
4257 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4258 mCurrentCookedState.fingerIdBits.clear();
4259 pointerUsage = POINTER_USAGE_MOUSE;
4260 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4261 isPointerDown(mCurrentRawState.buttonState)) {
4262 pointerUsage = POINTER_USAGE_GESTURES;
4263 }
4264
4265 dispatchPointerUsage(when, policyFlags, pointerUsage);
4266 } else {
4267 if (mDeviceMode == DEVICE_MODE_DIRECT
4268 && mConfig.showTouches && mPointerController != NULL) {
4269 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4270 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4271
4272 mPointerController->setButtonState(mCurrentRawState.buttonState);
4273 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4274 mCurrentCookedState.cookedPointerData.idToIndex,
4275 mCurrentCookedState.cookedPointerData.touchingIdBits);
4276 }
4277
Michael Wright8e812822015-06-22 16:18:21 +01004278 if (!mCurrentMotionAborted) {
4279 dispatchButtonRelease(when, policyFlags);
4280 dispatchHoverExit(when, policyFlags);
4281 dispatchTouches(when, policyFlags);
4282 dispatchHoverEnterAndMove(when, policyFlags);
4283 dispatchButtonPress(when, policyFlags);
4284 }
4285
4286 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4287 mCurrentMotionAborted = false;
4288 }
Michael Wright842500e2015-03-13 17:32:02 -07004289 }
4290
4291 // Synthesize key up from raw buttons if needed.
4292 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004293 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
4295 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004296 mCurrentRawState.rawVScroll = 0;
4297 mCurrentRawState.rawHScroll = 0;
4298
4299 // Copy current touch to last touch in preparation for the next cycle.
4300 mLastRawState.copyFrom(mCurrentRawState);
4301 mLastCookedState.copyFrom(mCurrentCookedState);
4302}
4303
4304void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004305 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004306 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4307 }
4308}
4309
4310void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004311 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4312 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004313
Michael Wright53dca3a2015-04-23 17:39:53 +01004314 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4315 float pressure = mExternalStylusState.pressure;
4316 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4317 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4318 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4319 }
4320 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4321 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4322
4323 PointerProperties& properties =
4324 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004325 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4326 properties.toolType = mExternalStylusState.toolType;
4327 }
4328 }
4329}
4330
4331bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4332 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4333 return false;
4334 }
4335
4336 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4337 && state.rawPointerData.pointerCount != 0;
4338 if (initialDown) {
4339 if (mExternalStylusState.pressure != 0.0f) {
4340#if DEBUG_STYLUS_FUSION
4341 ALOGD("Have both stylus and touch data, beginning fusion");
4342#endif
4343 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4344 } else if (timeout) {
4345#if DEBUG_STYLUS_FUSION
4346 ALOGD("Timeout expired, assuming touch is not a stylus.");
4347#endif
4348 resetExternalStylus();
4349 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004350 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4351 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004352 }
4353#if DEBUG_STYLUS_FUSION
4354 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004355 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004356#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004357 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004358 return true;
4359 }
4360 }
4361
4362 // Check if the stylus pointer has gone up.
4363 if (mExternalStylusId != -1 &&
4364 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4365#if DEBUG_STYLUS_FUSION
4366 ALOGD("Stylus pointer is going up");
4367#endif
4368 mExternalStylusId = -1;
4369 }
4370
4371 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372}
4373
4374void TouchInputMapper::timeoutExpired(nsecs_t when) {
4375 if (mDeviceMode == DEVICE_MODE_POINTER) {
4376 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4377 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4378 }
Michael Wright842500e2015-03-13 17:32:02 -07004379 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004380 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004381 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004382 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4383 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004384 }
4385 }
4386}
4387
4388void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004389 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004390 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004391 // We're either in the middle of a fused stream of data or we're waiting on data before
4392 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4393 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004394 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004395 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 }
4397}
4398
4399bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4400 // Check for release of a virtual key.
4401 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004402 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 // Pointer went up while virtual key was down.
4404 mCurrentVirtualKey.down = false;
4405 if (!mCurrentVirtualKey.ignored) {
4406#if DEBUG_VIRTUAL_KEYS
4407 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4408 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4409#endif
4410 dispatchVirtualKey(when, policyFlags,
4411 AKEY_EVENT_ACTION_UP,
4412 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4413 }
4414 return true;
4415 }
4416
Michael Wright842500e2015-03-13 17:32:02 -07004417 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4418 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4419 const RawPointerData::Pointer& pointer =
4420 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4422 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4423 // Pointer is still within the space of the virtual key.
4424 return true;
4425 }
4426 }
4427
4428 // Pointer left virtual key area or another pointer also went down.
4429 // Send key cancellation but do not consume the touch yet.
4430 // This is useful when the user swipes through from the virtual key area
4431 // into the main display surface.
4432 mCurrentVirtualKey.down = false;
4433 if (!mCurrentVirtualKey.ignored) {
4434#if DEBUG_VIRTUAL_KEYS
4435 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4436 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4437#endif
4438 dispatchVirtualKey(when, policyFlags,
4439 AKEY_EVENT_ACTION_UP,
4440 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4441 | AKEY_EVENT_FLAG_CANCELED);
4442 }
4443 }
4444
Michael Wright842500e2015-03-13 17:32:02 -07004445 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4446 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004448 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4449 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4451 // If exactly one pointer went down, check for virtual key hit.
4452 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004453 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4455 if (virtualKey) {
4456 mCurrentVirtualKey.down = true;
4457 mCurrentVirtualKey.downTime = when;
4458 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4459 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4460 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4461 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4462
4463 if (!mCurrentVirtualKey.ignored) {
4464#if DEBUG_VIRTUAL_KEYS
4465 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4466 mCurrentVirtualKey.keyCode,
4467 mCurrentVirtualKey.scanCode);
4468#endif
4469 dispatchVirtualKey(when, policyFlags,
4470 AKEY_EVENT_ACTION_DOWN,
4471 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4472 }
4473 }
4474 }
4475 return true;
4476 }
4477 }
4478
4479 // Disable all virtual key touches that happen within a short time interval of the
4480 // most recent touch within the screen area. The idea is to filter out stray
4481 // virtual key presses when interacting with the touch screen.
4482 //
4483 // Problems we're trying to solve:
4484 //
4485 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4486 // virtual key area that is implemented by a separate touch panel and accidentally
4487 // triggers a virtual key.
4488 //
4489 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4490 // area and accidentally triggers a virtual key. This often happens when virtual keys
4491 // are layed out below the screen near to where the on screen keyboard's space bar
4492 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004493 if (mConfig.virtualKeyQuietTime > 0 &&
4494 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4496 }
4497 return false;
4498}
4499
4500void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4501 int32_t keyEventAction, int32_t keyEventFlags) {
4502 int32_t keyCode = mCurrentVirtualKey.keyCode;
4503 int32_t scanCode = mCurrentVirtualKey.scanCode;
4504 nsecs_t downTime = mCurrentVirtualKey.downTime;
4505 int32_t metaState = mContext->getGlobalMetaState();
4506 policyFlags |= POLICY_FLAG_VIRTUAL;
4507
4508 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4509 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4510 getListener()->notifyKey(&args);
4511}
4512
Michael Wright8e812822015-06-22 16:18:21 +01004513void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4514 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4515 if (!currentIdBits.isEmpty()) {
4516 int32_t metaState = getContext()->getGlobalMetaState();
4517 int32_t buttonState = mCurrentCookedState.buttonState;
4518 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4519 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4520 mCurrentCookedState.cookedPointerData.pointerProperties,
4521 mCurrentCookedState.cookedPointerData.pointerCoords,
4522 mCurrentCookedState.cookedPointerData.idToIndex,
4523 currentIdBits, -1,
4524 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4525 mCurrentMotionAborted = true;
4526 }
4527}
4528
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004530 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4531 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004533 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534
4535 if (currentIdBits == lastIdBits) {
4536 if (!currentIdBits.isEmpty()) {
4537 // No pointer id changes so this is a move event.
4538 // The listener takes care of batching moves so we don't have to deal with that here.
4539 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004540 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004542 mCurrentCookedState.cookedPointerData.pointerProperties,
4543 mCurrentCookedState.cookedPointerData.pointerCoords,
4544 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 currentIdBits, -1,
4546 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4547 }
4548 } else {
4549 // There may be pointers going up and pointers going down and pointers moving
4550 // all at the same time.
4551 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4552 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4553 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4554 BitSet32 dispatchedIdBits(lastIdBits.value);
4555
4556 // Update last coordinates of pointers that have moved so that we observe the new
4557 // pointer positions at the same time as other pointers that have just gone up.
4558 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004559 mCurrentCookedState.cookedPointerData.pointerProperties,
4560 mCurrentCookedState.cookedPointerData.pointerCoords,
4561 mCurrentCookedState.cookedPointerData.idToIndex,
4562 mLastCookedState.cookedPointerData.pointerProperties,
4563 mLastCookedState.cookedPointerData.pointerCoords,
4564 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004566 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 moveNeeded = true;
4568 }
4569
4570 // Dispatch pointer up events.
4571 while (!upIdBits.isEmpty()) {
4572 uint32_t upId = upIdBits.clearFirstMarkedBit();
4573
4574 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004575 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004576 mLastCookedState.cookedPointerData.pointerProperties,
4577 mLastCookedState.cookedPointerData.pointerCoords,
4578 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004579 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 dispatchedIdBits.clearBit(upId);
4581 }
4582
4583 // Dispatch move events if any of the remaining pointers moved from their old locations.
4584 // Although applications receive new locations as part of individual pointer up
4585 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004586 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4588 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004589 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004590 mCurrentCookedState.cookedPointerData.pointerProperties,
4591 mCurrentCookedState.cookedPointerData.pointerCoords,
4592 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004593 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 }
4595
4596 // Dispatch pointer down events using the new pointer locations.
4597 while (!downIdBits.isEmpty()) {
4598 uint32_t downId = downIdBits.clearFirstMarkedBit();
4599 dispatchedIdBits.markBit(downId);
4600
4601 if (dispatchedIdBits.count() == 1) {
4602 // First pointer is going down. Set down time.
4603 mDownTime = when;
4604 }
4605
4606 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004607 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004608 mCurrentCookedState.cookedPointerData.pointerProperties,
4609 mCurrentCookedState.cookedPointerData.pointerCoords,
4610 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004611 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612 }
4613 }
4614}
4615
4616void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4617 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004618 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4619 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 int32_t metaState = getContext()->getGlobalMetaState();
4621 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004622 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004623 mLastCookedState.cookedPointerData.pointerProperties,
4624 mLastCookedState.cookedPointerData.pointerCoords,
4625 mLastCookedState.cookedPointerData.idToIndex,
4626 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4628 mSentHoverEnter = false;
4629 }
4630}
4631
4632void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004633 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4634 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 int32_t metaState = getContext()->getGlobalMetaState();
4636 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004637 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004638 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004639 mCurrentCookedState.cookedPointerData.pointerProperties,
4640 mCurrentCookedState.cookedPointerData.pointerCoords,
4641 mCurrentCookedState.cookedPointerData.idToIndex,
4642 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4644 mSentHoverEnter = true;
4645 }
4646
4647 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004648 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004649 mCurrentRawState.buttonState, 0,
4650 mCurrentCookedState.cookedPointerData.pointerProperties,
4651 mCurrentCookedState.cookedPointerData.pointerCoords,
4652 mCurrentCookedState.cookedPointerData.idToIndex,
4653 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4655 }
4656}
4657
Michael Wright7b159c92015-05-14 14:48:03 +01004658void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4659 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4660 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4661 const int32_t metaState = getContext()->getGlobalMetaState();
4662 int32_t buttonState = mLastCookedState.buttonState;
4663 while (!releasedButtons.isEmpty()) {
4664 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4665 buttonState &= ~actionButton;
4666 dispatchMotion(when, policyFlags, mSource,
4667 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4668 0, metaState, buttonState, 0,
4669 mCurrentCookedState.cookedPointerData.pointerProperties,
4670 mCurrentCookedState.cookedPointerData.pointerCoords,
4671 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4672 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4673 }
4674}
4675
4676void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4677 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4678 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4679 const int32_t metaState = getContext()->getGlobalMetaState();
4680 int32_t buttonState = mLastCookedState.buttonState;
4681 while (!pressedButtons.isEmpty()) {
4682 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4683 buttonState |= actionButton;
4684 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4685 0, metaState, buttonState, 0,
4686 mCurrentCookedState.cookedPointerData.pointerProperties,
4687 mCurrentCookedState.cookedPointerData.pointerCoords,
4688 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4689 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4690 }
4691}
4692
4693const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4694 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4695 return cookedPointerData.touchingIdBits;
4696 }
4697 return cookedPointerData.hoveringIdBits;
4698}
4699
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004701 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702
Michael Wright842500e2015-03-13 17:32:02 -07004703 mCurrentCookedState.cookedPointerData.clear();
4704 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4705 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4706 mCurrentRawState.rawPointerData.hoveringIdBits;
4707 mCurrentCookedState.cookedPointerData.touchingIdBits =
4708 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709
Michael Wright7b159c92015-05-14 14:48:03 +01004710 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4711 mCurrentCookedState.buttonState = 0;
4712 } else {
4713 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4714 }
4715
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 // Walk through the the active pointers and map device coordinates onto
4717 // surface coordinates and adjust for display orientation.
4718 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004719 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720
4721 // Size
4722 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4723 switch (mCalibration.sizeCalibration) {
4724 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4725 case Calibration::SIZE_CALIBRATION_DIAMETER:
4726 case Calibration::SIZE_CALIBRATION_BOX:
4727 case Calibration::SIZE_CALIBRATION_AREA:
4728 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4729 touchMajor = in.touchMajor;
4730 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4731 toolMajor = in.toolMajor;
4732 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4733 size = mRawPointerAxes.touchMinor.valid
4734 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4735 } else if (mRawPointerAxes.touchMajor.valid) {
4736 toolMajor = touchMajor = in.touchMajor;
4737 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4738 ? in.touchMinor : in.touchMajor;
4739 size = mRawPointerAxes.touchMinor.valid
4740 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4741 } else if (mRawPointerAxes.toolMajor.valid) {
4742 touchMajor = toolMajor = in.toolMajor;
4743 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4744 ? in.toolMinor : in.toolMajor;
4745 size = mRawPointerAxes.toolMinor.valid
4746 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4747 } else {
4748 ALOG_ASSERT(false, "No touch or tool axes. "
4749 "Size calibration should have been resolved to NONE.");
4750 touchMajor = 0;
4751 touchMinor = 0;
4752 toolMajor = 0;
4753 toolMinor = 0;
4754 size = 0;
4755 }
4756
4757 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004758 uint32_t touchingCount =
4759 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 if (touchingCount > 1) {
4761 touchMajor /= touchingCount;
4762 touchMinor /= touchingCount;
4763 toolMajor /= touchingCount;
4764 toolMinor /= touchingCount;
4765 size /= touchingCount;
4766 }
4767 }
4768
4769 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4770 touchMajor *= mGeometricScale;
4771 touchMinor *= mGeometricScale;
4772 toolMajor *= mGeometricScale;
4773 toolMinor *= mGeometricScale;
4774 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4775 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4776 touchMinor = touchMajor;
4777 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4778 toolMinor = toolMajor;
4779 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4780 touchMinor = touchMajor;
4781 toolMinor = toolMajor;
4782 }
4783
4784 mCalibration.applySizeScaleAndBias(&touchMajor);
4785 mCalibration.applySizeScaleAndBias(&touchMinor);
4786 mCalibration.applySizeScaleAndBias(&toolMajor);
4787 mCalibration.applySizeScaleAndBias(&toolMinor);
4788 size *= mSizeScale;
4789 break;
4790 default:
4791 touchMajor = 0;
4792 touchMinor = 0;
4793 toolMajor = 0;
4794 toolMinor = 0;
4795 size = 0;
4796 break;
4797 }
4798
4799 // Pressure
4800 float pressure;
4801 switch (mCalibration.pressureCalibration) {
4802 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4803 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4804 pressure = in.pressure * mPressureScale;
4805 break;
4806 default:
4807 pressure = in.isHovering ? 0 : 1;
4808 break;
4809 }
4810
4811 // Tilt and Orientation
4812 float tilt;
4813 float orientation;
4814 if (mHaveTilt) {
4815 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4816 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4817 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4818 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4819 } else {
4820 tilt = 0;
4821
4822 switch (mCalibration.orientationCalibration) {
4823 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4824 orientation = in.orientation * mOrientationScale;
4825 break;
4826 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4827 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4828 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4829 if (c1 != 0 || c2 != 0) {
4830 orientation = atan2f(c1, c2) * 0.5f;
4831 float confidence = hypotf(c1, c2);
4832 float scale = 1.0f + confidence / 16.0f;
4833 touchMajor *= scale;
4834 touchMinor /= scale;
4835 toolMajor *= scale;
4836 toolMinor /= scale;
4837 } else {
4838 orientation = 0;
4839 }
4840 break;
4841 }
4842 default:
4843 orientation = 0;
4844 }
4845 }
4846
4847 // Distance
4848 float distance;
4849 switch (mCalibration.distanceCalibration) {
4850 case Calibration::DISTANCE_CALIBRATION_SCALED:
4851 distance = in.distance * mDistanceScale;
4852 break;
4853 default:
4854 distance = 0;
4855 }
4856
4857 // Coverage
4858 int32_t rawLeft, rawTop, rawRight, rawBottom;
4859 switch (mCalibration.coverageCalibration) {
4860 case Calibration::COVERAGE_CALIBRATION_BOX:
4861 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4862 rawRight = in.toolMinor & 0x0000ffff;
4863 rawBottom = in.toolMajor & 0x0000ffff;
4864 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4865 break;
4866 default:
4867 rawLeft = rawTop = rawRight = rawBottom = 0;
4868 break;
4869 }
4870
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004871 // Adjust X,Y coords for device calibration
4872 // TODO: Adjust coverage coords?
4873 float xTransformed = in.x, yTransformed = in.y;
4874 mAffineTransform.applyTo(xTransformed, yTransformed);
4875
4876 // Adjust X, Y, and coverage coords for surface orientation.
4877 float x, y;
4878 float left, top, right, bottom;
4879
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 switch (mSurfaceOrientation) {
4881 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004882 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4883 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4885 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4886 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4887 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4888 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004889 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4891 }
4892 break;
4893 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004894 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4895 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4897 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4898 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4899 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4900 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09004901 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4903 }
4904 break;
4905 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004906 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4907 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4909 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4910 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4911 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4912 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004913 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4915 }
4916 break;
4917 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004918 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4919 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4921 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4922 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4923 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4924 break;
4925 }
4926
4927 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07004928 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 out.clear();
4930 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4931 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4932 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4933 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4934 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4935 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4936 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4937 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4938 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4939 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4940 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4941 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4942 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4943 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4944 } else {
4945 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4946 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4947 }
4948
4949 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07004950 PointerProperties& properties =
4951 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 uint32_t id = in.id;
4953 properties.clear();
4954 properties.id = id;
4955 properties.toolType = in.toolType;
4956
4957 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07004958 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
4960}
4961
4962void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4963 PointerUsage pointerUsage) {
4964 if (pointerUsage != mPointerUsage) {
4965 abortPointerUsage(when, policyFlags);
4966 mPointerUsage = pointerUsage;
4967 }
4968
4969 switch (mPointerUsage) {
4970 case POINTER_USAGE_GESTURES:
4971 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4972 break;
4973 case POINTER_USAGE_STYLUS:
4974 dispatchPointerStylus(when, policyFlags);
4975 break;
4976 case POINTER_USAGE_MOUSE:
4977 dispatchPointerMouse(when, policyFlags);
4978 break;
4979 default:
4980 break;
4981 }
4982}
4983
4984void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4985 switch (mPointerUsage) {
4986 case POINTER_USAGE_GESTURES:
4987 abortPointerGestures(when, policyFlags);
4988 break;
4989 case POINTER_USAGE_STYLUS:
4990 abortPointerStylus(when, policyFlags);
4991 break;
4992 case POINTER_USAGE_MOUSE:
4993 abortPointerMouse(when, policyFlags);
4994 break;
4995 default:
4996 break;
4997 }
4998
4999 mPointerUsage = POINTER_USAGE_NONE;
5000}
5001
5002void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5003 bool isTimeout) {
5004 // Update current gesture coordinates.
5005 bool cancelPreviousGesture, finishPreviousGesture;
5006 bool sendEvents = preparePointerGestures(when,
5007 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5008 if (!sendEvents) {
5009 return;
5010 }
5011 if (finishPreviousGesture) {
5012 cancelPreviousGesture = false;
5013 }
5014
5015 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005016 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5017 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 if (finishPreviousGesture || cancelPreviousGesture) {
5019 mPointerController->clearSpots();
5020 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005021
5022 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5023 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5024 mPointerGesture.currentGestureIdToIndex,
5025 mPointerGesture.currentGestureIdBits);
5026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 } else {
5028 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5029 }
5030
5031 // Show or hide the pointer if needed.
5032 switch (mPointerGesture.currentGestureMode) {
5033 case PointerGesture::NEUTRAL:
5034 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005035 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5036 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 // Remind the user of where the pointer is after finishing a gesture with spots.
5038 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5039 }
5040 break;
5041 case PointerGesture::TAP:
5042 case PointerGesture::TAP_DRAG:
5043 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5044 case PointerGesture::HOVER:
5045 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005046 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 // Unfade the pointer when the current gesture manipulates the
5048 // area directly under the pointer.
5049 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5050 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 case PointerGesture::FREEFORM:
5052 // Fade the pointer when the current gesture manipulates a different
5053 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005054 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5056 } else {
5057 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5058 }
5059 break;
5060 }
5061
5062 // Send events!
5063 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005064 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065
5066 // Update last coordinates of pointers that have moved so that we observe the new
5067 // pointer positions at the same time as other pointers that have just gone up.
5068 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5069 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5070 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5071 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5072 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5073 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5074 bool moveNeeded = false;
5075 if (down && !cancelPreviousGesture && !finishPreviousGesture
5076 && !mPointerGesture.lastGestureIdBits.isEmpty()
5077 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5078 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5079 & mPointerGesture.lastGestureIdBits.value);
5080 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5081 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5082 mPointerGesture.lastGestureProperties,
5083 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5084 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005085 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 moveNeeded = true;
5087 }
5088 }
5089
5090 // Send motion events for all pointers that went up or were canceled.
5091 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5092 if (!dispatchedGestureIdBits.isEmpty()) {
5093 if (cancelPreviousGesture) {
5094 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005095 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 AMOTION_EVENT_EDGE_FLAG_NONE,
5097 mPointerGesture.lastGestureProperties,
5098 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005099 dispatchedGestureIdBits, -1, 0,
5100 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101
5102 dispatchedGestureIdBits.clear();
5103 } else {
5104 BitSet32 upGestureIdBits;
5105 if (finishPreviousGesture) {
5106 upGestureIdBits = dispatchedGestureIdBits;
5107 } else {
5108 upGestureIdBits.value = dispatchedGestureIdBits.value
5109 & ~mPointerGesture.currentGestureIdBits.value;
5110 }
5111 while (!upGestureIdBits.isEmpty()) {
5112 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5113
5114 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005115 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5117 mPointerGesture.lastGestureProperties,
5118 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5119 dispatchedGestureIdBits, id,
5120 0, 0, mPointerGesture.downTime);
5121
5122 dispatchedGestureIdBits.clearBit(id);
5123 }
5124 }
5125 }
5126
5127 // Send motion events for all pointers that moved.
5128 if (moveNeeded) {
5129 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005130 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5131 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 mPointerGesture.currentGestureProperties,
5133 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5134 dispatchedGestureIdBits, -1,
5135 0, 0, mPointerGesture.downTime);
5136 }
5137
5138 // Send motion events for all pointers that went down.
5139 if (down) {
5140 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5141 & ~dispatchedGestureIdBits.value);
5142 while (!downGestureIdBits.isEmpty()) {
5143 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5144 dispatchedGestureIdBits.markBit(id);
5145
5146 if (dispatchedGestureIdBits.count() == 1) {
5147 mPointerGesture.downTime = when;
5148 }
5149
5150 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005151 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 mPointerGesture.currentGestureProperties,
5153 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5154 dispatchedGestureIdBits, id,
5155 0, 0, mPointerGesture.downTime);
5156 }
5157 }
5158
5159 // Send motion events for hover.
5160 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5161 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005162 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5164 mPointerGesture.currentGestureProperties,
5165 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5166 mPointerGesture.currentGestureIdBits, -1,
5167 0, 0, mPointerGesture.downTime);
5168 } else if (dispatchedGestureIdBits.isEmpty()
5169 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5170 // Synthesize a hover move event after all pointers go up to indicate that
5171 // the pointer is hovering again even if the user is not currently touching
5172 // the touch pad. This ensures that a view will receive a fresh hover enter
5173 // event after a tap.
5174 float x, y;
5175 mPointerController->getPosition(&x, &y);
5176
5177 PointerProperties pointerProperties;
5178 pointerProperties.clear();
5179 pointerProperties.id = 0;
5180 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5181
5182 PointerCoords pointerCoords;
5183 pointerCoords.clear();
5184 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5185 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5186
5187 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005188 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5190 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5191 0, 0, mPointerGesture.downTime);
5192 getListener()->notifyMotion(&args);
5193 }
5194
5195 // Update state.
5196 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5197 if (!down) {
5198 mPointerGesture.lastGestureIdBits.clear();
5199 } else {
5200 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5201 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5202 uint32_t id = idBits.clearFirstMarkedBit();
5203 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5204 mPointerGesture.lastGestureProperties[index].copyFrom(
5205 mPointerGesture.currentGestureProperties[index]);
5206 mPointerGesture.lastGestureCoords[index].copyFrom(
5207 mPointerGesture.currentGestureCoords[index]);
5208 mPointerGesture.lastGestureIdToIndex[id] = index;
5209 }
5210 }
5211}
5212
5213void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5214 // Cancel previously dispatches pointers.
5215 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5216 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005217 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005218 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005219 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 AMOTION_EVENT_EDGE_FLAG_NONE,
5221 mPointerGesture.lastGestureProperties,
5222 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5223 mPointerGesture.lastGestureIdBits, -1,
5224 0, 0, mPointerGesture.downTime);
5225 }
5226
5227 // Reset the current pointer gesture.
5228 mPointerGesture.reset();
5229 mPointerVelocityControl.reset();
5230
5231 // Remove any current spots.
5232 if (mPointerController != NULL) {
5233 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5234 mPointerController->clearSpots();
5235 }
5236}
5237
5238bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5239 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5240 *outCancelPreviousGesture = false;
5241 *outFinishPreviousGesture = false;
5242
5243 // Handle TAP timeout.
5244 if (isTimeout) {
5245#if DEBUG_GESTURES
5246 ALOGD("Gestures: Processing timeout");
5247#endif
5248
5249 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5250 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5251 // The tap/drag timeout has not yet expired.
5252 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5253 + mConfig.pointerGestureTapDragInterval);
5254 } else {
5255 // The tap is finished.
5256#if DEBUG_GESTURES
5257 ALOGD("Gestures: TAP finished");
5258#endif
5259 *outFinishPreviousGesture = true;
5260
5261 mPointerGesture.activeGestureId = -1;
5262 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5263 mPointerGesture.currentGestureIdBits.clear();
5264
5265 mPointerVelocityControl.reset();
5266 return true;
5267 }
5268 }
5269
5270 // We did not handle this timeout.
5271 return false;
5272 }
5273
Michael Wright842500e2015-03-13 17:32:02 -07005274 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5275 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276
5277 // Update the velocity tracker.
5278 {
5279 VelocityTracker::Position positions[MAX_POINTERS];
5280 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005281 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005283 const RawPointerData::Pointer& pointer =
5284 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 positions[count].x = pointer.x * mPointerXMovementScale;
5286 positions[count].y = pointer.y * mPointerYMovementScale;
5287 }
5288 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005289 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 }
5291
5292 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5293 // to NEUTRAL, then we should not generate tap event.
5294 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5295 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5296 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5297 mPointerGesture.resetTap();
5298 }
5299
5300 // Pick a new active touch id if needed.
5301 // Choose an arbitrary pointer that just went down, if there is one.
5302 // Otherwise choose an arbitrary remaining pointer.
5303 // This guarantees we always have an active touch id when there is at least one pointer.
5304 // We keep the same active touch id for as long as possible.
5305 bool activeTouchChanged = false;
5306 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5307 int32_t activeTouchId = lastActiveTouchId;
5308 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005309 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 activeTouchChanged = true;
5311 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005312 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 mPointerGesture.firstTouchTime = when;
5314 }
Michael Wright842500e2015-03-13 17:32:02 -07005315 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005317 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005319 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 } else {
5321 activeTouchId = mPointerGesture.activeTouchId = -1;
5322 }
5323 }
5324
5325 // Determine whether we are in quiet time.
5326 bool isQuietTime = false;
5327 if (activeTouchId < 0) {
5328 mPointerGesture.resetQuietTime();
5329 } else {
5330 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5331 if (!isQuietTime) {
5332 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5333 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5334 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5335 && currentFingerCount < 2) {
5336 // Enter quiet time when exiting swipe or freeform state.
5337 // This is to prevent accidentally entering the hover state and flinging the
5338 // pointer when finishing a swipe and there is still one pointer left onscreen.
5339 isQuietTime = true;
5340 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5341 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005342 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 // Enter quiet time when releasing the button and there are still two or more
5344 // fingers down. This may indicate that one finger was used to press the button
5345 // but it has not gone up yet.
5346 isQuietTime = true;
5347 }
5348 if (isQuietTime) {
5349 mPointerGesture.quietTime = when;
5350 }
5351 }
5352 }
5353
5354 // Switch states based on button and pointer state.
5355 if (isQuietTime) {
5356 // Case 1: Quiet time. (QUIET)
5357#if DEBUG_GESTURES
5358 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5359 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5360#endif
5361 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5362 *outFinishPreviousGesture = true;
5363 }
5364
5365 mPointerGesture.activeGestureId = -1;
5366 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5367 mPointerGesture.currentGestureIdBits.clear();
5368
5369 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005370 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5372 // The pointer follows the active touch point.
5373 // Emit DOWN, MOVE, UP events at the pointer location.
5374 //
5375 // Only the active touch matters; other fingers are ignored. This policy helps
5376 // to handle the case where the user places a second finger on the touch pad
5377 // to apply the necessary force to depress an integrated button below the surface.
5378 // We don't want the second finger to be delivered to applications.
5379 //
5380 // For this to work well, we need to make sure to track the pointer that is really
5381 // active. If the user first puts one finger down to click then adds another
5382 // finger to drag then the active pointer should switch to the finger that is
5383 // being dragged.
5384#if DEBUG_GESTURES
5385 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5386 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5387#endif
5388 // Reset state when just starting.
5389 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5390 *outFinishPreviousGesture = true;
5391 mPointerGesture.activeGestureId = 0;
5392 }
5393
5394 // Switch pointers if needed.
5395 // Find the fastest pointer and follow it.
5396 if (activeTouchId >= 0 && currentFingerCount > 1) {
5397 int32_t bestId = -1;
5398 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005399 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 uint32_t id = idBits.clearFirstMarkedBit();
5401 float vx, vy;
5402 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5403 float speed = hypotf(vx, vy);
5404 if (speed > bestSpeed) {
5405 bestId = id;
5406 bestSpeed = speed;
5407 }
5408 }
5409 }
5410 if (bestId >= 0 && bestId != activeTouchId) {
5411 mPointerGesture.activeTouchId = activeTouchId = bestId;
5412 activeTouchChanged = true;
5413#if DEBUG_GESTURES
5414 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5415 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5416#endif
5417 }
5418 }
5419
Jun Mukaifa1706a2015-12-03 01:14:46 -08005420 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005421 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005423 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005425 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005426 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5427 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428
5429 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5430 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5431
5432 // Move the pointer using a relative motion.
5433 // When using spots, the click will occur at the position of the anchor
5434 // spot and all other spots will move there.
5435 mPointerController->move(deltaX, deltaY);
5436 } else {
5437 mPointerVelocityControl.reset();
5438 }
5439
5440 float x, y;
5441 mPointerController->getPosition(&x, &y);
5442
5443 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5444 mPointerGesture.currentGestureIdBits.clear();
5445 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5446 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5447 mPointerGesture.currentGestureProperties[0].clear();
5448 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5449 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5450 mPointerGesture.currentGestureCoords[0].clear();
5451 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5452 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5453 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5454 } else if (currentFingerCount == 0) {
5455 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5456 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5457 *outFinishPreviousGesture = true;
5458 }
5459
5460 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5461 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5462 bool tapped = false;
5463 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5464 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5465 && lastFingerCount == 1) {
5466 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5467 float x, y;
5468 mPointerController->getPosition(&x, &y);
5469 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5470 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5471#if DEBUG_GESTURES
5472 ALOGD("Gestures: TAP");
5473#endif
5474
5475 mPointerGesture.tapUpTime = when;
5476 getContext()->requestTimeoutAtTime(when
5477 + mConfig.pointerGestureTapDragInterval);
5478
5479 mPointerGesture.activeGestureId = 0;
5480 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5481 mPointerGesture.currentGestureIdBits.clear();
5482 mPointerGesture.currentGestureIdBits.markBit(
5483 mPointerGesture.activeGestureId);
5484 mPointerGesture.currentGestureIdToIndex[
5485 mPointerGesture.activeGestureId] = 0;
5486 mPointerGesture.currentGestureProperties[0].clear();
5487 mPointerGesture.currentGestureProperties[0].id =
5488 mPointerGesture.activeGestureId;
5489 mPointerGesture.currentGestureProperties[0].toolType =
5490 AMOTION_EVENT_TOOL_TYPE_FINGER;
5491 mPointerGesture.currentGestureCoords[0].clear();
5492 mPointerGesture.currentGestureCoords[0].setAxisValue(
5493 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5494 mPointerGesture.currentGestureCoords[0].setAxisValue(
5495 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5496 mPointerGesture.currentGestureCoords[0].setAxisValue(
5497 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5498
5499 tapped = true;
5500 } else {
5501#if DEBUG_GESTURES
5502 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5503 x - mPointerGesture.tapX,
5504 y - mPointerGesture.tapY);
5505#endif
5506 }
5507 } else {
5508#if DEBUG_GESTURES
5509 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5510 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5511 (when - mPointerGesture.tapDownTime) * 0.000001f);
5512 } else {
5513 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5514 }
5515#endif
5516 }
5517 }
5518
5519 mPointerVelocityControl.reset();
5520
5521 if (!tapped) {
5522#if DEBUG_GESTURES
5523 ALOGD("Gestures: NEUTRAL");
5524#endif
5525 mPointerGesture.activeGestureId = -1;
5526 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5527 mPointerGesture.currentGestureIdBits.clear();
5528 }
5529 } else if (currentFingerCount == 1) {
5530 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5531 // The pointer follows the active touch point.
5532 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5533 // When in TAP_DRAG, emit MOVE events at the pointer location.
5534 ALOG_ASSERT(activeTouchId >= 0);
5535
5536 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5537 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5538 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5539 float x, y;
5540 mPointerController->getPosition(&x, &y);
5541 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5542 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5543 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5544 } else {
5545#if DEBUG_GESTURES
5546 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5547 x - mPointerGesture.tapX,
5548 y - mPointerGesture.tapY);
5549#endif
5550 }
5551 } else {
5552#if DEBUG_GESTURES
5553 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5554 (when - mPointerGesture.tapUpTime) * 0.000001f);
5555#endif
5556 }
5557 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5558 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5559 }
5560
Jun Mukaifa1706a2015-12-03 01:14:46 -08005561 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005562 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005564 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005566 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005567 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5568 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569
5570 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5571 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5572
5573 // Move the pointer using a relative motion.
5574 // When using spots, the hover or drag will occur at the position of the anchor spot.
5575 mPointerController->move(deltaX, deltaY);
5576 } else {
5577 mPointerVelocityControl.reset();
5578 }
5579
5580 bool down;
5581 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5582#if DEBUG_GESTURES
5583 ALOGD("Gestures: TAP_DRAG");
5584#endif
5585 down = true;
5586 } else {
5587#if DEBUG_GESTURES
5588 ALOGD("Gestures: HOVER");
5589#endif
5590 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5591 *outFinishPreviousGesture = true;
5592 }
5593 mPointerGesture.activeGestureId = 0;
5594 down = false;
5595 }
5596
5597 float x, y;
5598 mPointerController->getPosition(&x, &y);
5599
5600 mPointerGesture.currentGestureIdBits.clear();
5601 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5602 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5603 mPointerGesture.currentGestureProperties[0].clear();
5604 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5605 mPointerGesture.currentGestureProperties[0].toolType =
5606 AMOTION_EVENT_TOOL_TYPE_FINGER;
5607 mPointerGesture.currentGestureCoords[0].clear();
5608 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5609 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5610 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5611 down ? 1.0f : 0.0f);
5612
5613 if (lastFingerCount == 0 && currentFingerCount != 0) {
5614 mPointerGesture.resetTap();
5615 mPointerGesture.tapDownTime = when;
5616 mPointerGesture.tapX = x;
5617 mPointerGesture.tapY = y;
5618 }
5619 } else {
5620 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5621 // We need to provide feedback for each finger that goes down so we cannot wait
5622 // for the fingers to move before deciding what to do.
5623 //
5624 // The ambiguous case is deciding what to do when there are two fingers down but they
5625 // have not moved enough to determine whether they are part of a drag or part of a
5626 // freeform gesture, or just a press or long-press at the pointer location.
5627 //
5628 // When there are two fingers we start with the PRESS hypothesis and we generate a
5629 // down at the pointer location.
5630 //
5631 // When the two fingers move enough or when additional fingers are added, we make
5632 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5633 ALOG_ASSERT(activeTouchId >= 0);
5634
5635 bool settled = when >= mPointerGesture.firstTouchTime
5636 + mConfig.pointerGestureMultitouchSettleInterval;
5637 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5638 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5639 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5640 *outFinishPreviousGesture = true;
5641 } else if (!settled && currentFingerCount > lastFingerCount) {
5642 // Additional pointers have gone down but not yet settled.
5643 // Reset the gesture.
5644#if DEBUG_GESTURES
5645 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5646 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5647 + mConfig.pointerGestureMultitouchSettleInterval - when)
5648 * 0.000001f);
5649#endif
5650 *outCancelPreviousGesture = true;
5651 } else {
5652 // Continue previous gesture.
5653 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5654 }
5655
5656 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5657 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5658 mPointerGesture.activeGestureId = 0;
5659 mPointerGesture.referenceIdBits.clear();
5660 mPointerVelocityControl.reset();
5661
5662 // Use the centroid and pointer location as the reference points for the gesture.
5663#if DEBUG_GESTURES
5664 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5665 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5666 + mConfig.pointerGestureMultitouchSettleInterval - when)
5667 * 0.000001f);
5668#endif
Michael Wright842500e2015-03-13 17:32:02 -07005669 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 &mPointerGesture.referenceTouchX,
5671 &mPointerGesture.referenceTouchY);
5672 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5673 &mPointerGesture.referenceGestureY);
5674 }
5675
5676 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005677 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5679 uint32_t id = idBits.clearFirstMarkedBit();
5680 mPointerGesture.referenceDeltas[id].dx = 0;
5681 mPointerGesture.referenceDeltas[id].dy = 0;
5682 }
Michael Wright842500e2015-03-13 17:32:02 -07005683 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684
5685 // Add delta for all fingers and calculate a common movement delta.
5686 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005687 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5688 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5690 bool first = (idBits == commonIdBits);
5691 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005692 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5693 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5695 delta.dx += cpd.x - lpd.x;
5696 delta.dy += cpd.y - lpd.y;
5697
5698 if (first) {
5699 commonDeltaX = delta.dx;
5700 commonDeltaY = delta.dy;
5701 } else {
5702 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5703 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5704 }
5705 }
5706
5707 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5708 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5709 float dist[MAX_POINTER_ID + 1];
5710 int32_t distOverThreshold = 0;
5711 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5712 uint32_t id = idBits.clearFirstMarkedBit();
5713 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5714 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5715 delta.dy * mPointerYZoomScale);
5716 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5717 distOverThreshold += 1;
5718 }
5719 }
5720
5721 // Only transition when at least two pointers have moved further than
5722 // the minimum distance threshold.
5723 if (distOverThreshold >= 2) {
5724 if (currentFingerCount > 2) {
5725 // There are more than two pointers, switch to FREEFORM.
5726#if DEBUG_GESTURES
5727 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5728 currentFingerCount);
5729#endif
5730 *outCancelPreviousGesture = true;
5731 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5732 } else {
5733 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005734 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 uint32_t id1 = idBits.clearFirstMarkedBit();
5736 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005737 const RawPointerData::Pointer& p1 =
5738 mCurrentRawState.rawPointerData.pointerForId(id1);
5739 const RawPointerData::Pointer& p2 =
5740 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5742 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5743 // There are two pointers but they are too far apart for a SWIPE,
5744 // switch to FREEFORM.
5745#if DEBUG_GESTURES
5746 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5747 mutualDistance, mPointerGestureMaxSwipeWidth);
5748#endif
5749 *outCancelPreviousGesture = true;
5750 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5751 } else {
5752 // There are two pointers. Wait for both pointers to start moving
5753 // before deciding whether this is a SWIPE or FREEFORM gesture.
5754 float dist1 = dist[id1];
5755 float dist2 = dist[id2];
5756 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5757 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5758 // Calculate the dot product of the displacement vectors.
5759 // When the vectors are oriented in approximately the same direction,
5760 // the angle betweeen them is near zero and the cosine of the angle
5761 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5762 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5763 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5764 float dx1 = delta1.dx * mPointerXZoomScale;
5765 float dy1 = delta1.dy * mPointerYZoomScale;
5766 float dx2 = delta2.dx * mPointerXZoomScale;
5767 float dy2 = delta2.dy * mPointerYZoomScale;
5768 float dot = dx1 * dx2 + dy1 * dy2;
5769 float cosine = dot / (dist1 * dist2); // denominator always > 0
5770 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5771 // Pointers are moving in the same direction. Switch to SWIPE.
5772#if DEBUG_GESTURES
5773 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5774 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5775 "cosine %0.3f >= %0.3f",
5776 dist1, mConfig.pointerGestureMultitouchMinDistance,
5777 dist2, mConfig.pointerGestureMultitouchMinDistance,
5778 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5779#endif
5780 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5781 } else {
5782 // Pointers are moving in different directions. Switch to FREEFORM.
5783#if DEBUG_GESTURES
5784 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5785 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5786 "cosine %0.3f < %0.3f",
5787 dist1, mConfig.pointerGestureMultitouchMinDistance,
5788 dist2, mConfig.pointerGestureMultitouchMinDistance,
5789 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5790#endif
5791 *outCancelPreviousGesture = true;
5792 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5793 }
5794 }
5795 }
5796 }
5797 }
5798 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5799 // Switch from SWIPE to FREEFORM if additional pointers go down.
5800 // Cancel previous gesture.
5801 if (currentFingerCount > 2) {
5802#if DEBUG_GESTURES
5803 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5804 currentFingerCount);
5805#endif
5806 *outCancelPreviousGesture = true;
5807 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5808 }
5809 }
5810
5811 // Move the reference points based on the overall group motion of the fingers
5812 // except in PRESS mode while waiting for a transition to occur.
5813 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5814 && (commonDeltaX || commonDeltaY)) {
5815 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5816 uint32_t id = idBits.clearFirstMarkedBit();
5817 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5818 delta.dx = 0;
5819 delta.dy = 0;
5820 }
5821
5822 mPointerGesture.referenceTouchX += commonDeltaX;
5823 mPointerGesture.referenceTouchY += commonDeltaY;
5824
5825 commonDeltaX *= mPointerXMovementScale;
5826 commonDeltaY *= mPointerYMovementScale;
5827
5828 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5829 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5830
5831 mPointerGesture.referenceGestureX += commonDeltaX;
5832 mPointerGesture.referenceGestureY += commonDeltaY;
5833 }
5834
5835 // Report gestures.
5836 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5837 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5838 // PRESS or SWIPE mode.
5839#if DEBUG_GESTURES
5840 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5841 "activeGestureId=%d, currentTouchPointerCount=%d",
5842 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5843#endif
5844 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5845
5846 mPointerGesture.currentGestureIdBits.clear();
5847 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5848 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5849 mPointerGesture.currentGestureProperties[0].clear();
5850 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5851 mPointerGesture.currentGestureProperties[0].toolType =
5852 AMOTION_EVENT_TOOL_TYPE_FINGER;
5853 mPointerGesture.currentGestureCoords[0].clear();
5854 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5855 mPointerGesture.referenceGestureX);
5856 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5857 mPointerGesture.referenceGestureY);
5858 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5859 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5860 // FREEFORM mode.
5861#if DEBUG_GESTURES
5862 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5863 "activeGestureId=%d, currentTouchPointerCount=%d",
5864 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5865#endif
5866 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5867
5868 mPointerGesture.currentGestureIdBits.clear();
5869
5870 BitSet32 mappedTouchIdBits;
5871 BitSet32 usedGestureIdBits;
5872 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5873 // Initially, assign the active gesture id to the active touch point
5874 // if there is one. No other touch id bits are mapped yet.
5875 if (!*outCancelPreviousGesture) {
5876 mappedTouchIdBits.markBit(activeTouchId);
5877 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5878 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5879 mPointerGesture.activeGestureId;
5880 } else {
5881 mPointerGesture.activeGestureId = -1;
5882 }
5883 } else {
5884 // Otherwise, assume we mapped all touches from the previous frame.
5885 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07005886 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
5887 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5889
5890 // Check whether we need to choose a new active gesture id because the
5891 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07005892 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
5893 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 !upTouchIdBits.isEmpty(); ) {
5895 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5896 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5897 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5898 mPointerGesture.activeGestureId = -1;
5899 break;
5900 }
5901 }
5902 }
5903
5904#if DEBUG_GESTURES
5905 ALOGD("Gestures: FREEFORM follow up "
5906 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5907 "activeGestureId=%d",
5908 mappedTouchIdBits.value, usedGestureIdBits.value,
5909 mPointerGesture.activeGestureId);
5910#endif
5911
Michael Wright842500e2015-03-13 17:32:02 -07005912 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 for (uint32_t i = 0; i < currentFingerCount; i++) {
5914 uint32_t touchId = idBits.clearFirstMarkedBit();
5915 uint32_t gestureId;
5916 if (!mappedTouchIdBits.hasBit(touchId)) {
5917 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5918 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5919#if DEBUG_GESTURES
5920 ALOGD("Gestures: FREEFORM "
5921 "new mapping for touch id %d -> gesture id %d",
5922 touchId, gestureId);
5923#endif
5924 } else {
5925 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5926#if DEBUG_GESTURES
5927 ALOGD("Gestures: FREEFORM "
5928 "existing mapping for touch id %d -> gesture id %d",
5929 touchId, gestureId);
5930#endif
5931 }
5932 mPointerGesture.currentGestureIdBits.markBit(gestureId);
5933 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5934
5935 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07005936 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5938 * mPointerXZoomScale;
5939 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5940 * mPointerYZoomScale;
5941 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5942
5943 mPointerGesture.currentGestureProperties[i].clear();
5944 mPointerGesture.currentGestureProperties[i].id = gestureId;
5945 mPointerGesture.currentGestureProperties[i].toolType =
5946 AMOTION_EVENT_TOOL_TYPE_FINGER;
5947 mPointerGesture.currentGestureCoords[i].clear();
5948 mPointerGesture.currentGestureCoords[i].setAxisValue(
5949 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5950 mPointerGesture.currentGestureCoords[i].setAxisValue(
5951 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5952 mPointerGesture.currentGestureCoords[i].setAxisValue(
5953 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5954 }
5955
5956 if (mPointerGesture.activeGestureId < 0) {
5957 mPointerGesture.activeGestureId =
5958 mPointerGesture.currentGestureIdBits.firstMarkedBit();
5959#if DEBUG_GESTURES
5960 ALOGD("Gestures: FREEFORM new "
5961 "activeGestureId=%d", mPointerGesture.activeGestureId);
5962#endif
5963 }
5964 }
5965 }
5966
Michael Wright842500e2015-03-13 17:32:02 -07005967 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968
5969#if DEBUG_GESTURES
5970 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5971 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5972 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5973 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5974 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5975 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5976 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5977 uint32_t id = idBits.clearFirstMarkedBit();
5978 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5979 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5980 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5981 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
5982 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5983 id, index, properties.toolType,
5984 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5985 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5986 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5987 }
5988 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5989 uint32_t id = idBits.clearFirstMarkedBit();
5990 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5991 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5992 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5993 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
5994 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5995 id, index, properties.toolType,
5996 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5997 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5998 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5999 }
6000#endif
6001 return true;
6002}
6003
6004void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6005 mPointerSimple.currentCoords.clear();
6006 mPointerSimple.currentProperties.clear();
6007
6008 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006009 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6010 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6011 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6012 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6013 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006014 mPointerController->setPosition(x, y);
6015
Michael Wright842500e2015-03-13 17:32:02 -07006016 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017 down = !hovering;
6018
6019 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006020 mPointerSimple.currentCoords.copyFrom(
6021 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6023 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6024 mPointerSimple.currentProperties.id = 0;
6025 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006026 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027 } else {
6028 down = false;
6029 hovering = false;
6030 }
6031
6032 dispatchPointerSimple(when, policyFlags, down, hovering);
6033}
6034
6035void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6036 abortPointerSimple(when, policyFlags);
6037}
6038
6039void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6040 mPointerSimple.currentCoords.clear();
6041 mPointerSimple.currentProperties.clear();
6042
6043 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006044 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6045 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6046 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006047 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006048 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6049 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006050 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006051 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006053 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006054 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055 * mPointerYMovementScale;
6056
6057 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6058 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6059
6060 mPointerController->move(deltaX, deltaY);
6061 } else {
6062 mPointerVelocityControl.reset();
6063 }
6064
Michael Wright842500e2015-03-13 17:32:02 -07006065 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 hovering = !down;
6067
6068 float x, y;
6069 mPointerController->getPosition(&x, &y);
6070 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006071 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6073 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6074 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6075 hovering ? 0.0f : 1.0f);
6076 mPointerSimple.currentProperties.id = 0;
6077 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006078 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 } else {
6080 mPointerVelocityControl.reset();
6081
6082 down = false;
6083 hovering = false;
6084 }
6085
6086 dispatchPointerSimple(when, policyFlags, down, hovering);
6087}
6088
6089void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6090 abortPointerSimple(when, policyFlags);
6091
6092 mPointerVelocityControl.reset();
6093}
6094
6095void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6096 bool down, bool hovering) {
6097 int32_t metaState = getContext()->getGlobalMetaState();
6098
6099 if (mPointerController != NULL) {
6100 if (down || hovering) {
6101 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6102 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006103 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006104 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6105 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6106 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6107 }
6108 }
6109
6110 if (mPointerSimple.down && !down) {
6111 mPointerSimple.down = false;
6112
6113 // Send up.
6114 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006115 AMOTION_EVENT_ACTION_UP, 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 (mPointerSimple.hovering && !hovering) {
6124 mPointerSimple.hovering = false;
6125
6126 // Send hover exit.
6127 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006128 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006129 mViewport.displayId,
6130 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6131 mOrientedXPrecision, mOrientedYPrecision,
6132 mPointerSimple.downTime);
6133 getListener()->notifyMotion(&args);
6134 }
6135
6136 if (down) {
6137 if (!mPointerSimple.down) {
6138 mPointerSimple.down = true;
6139 mPointerSimple.downTime = when;
6140
6141 // Send down.
6142 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006143 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006144 mViewport.displayId,
6145 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6146 mOrientedXPrecision, mOrientedYPrecision,
6147 mPointerSimple.downTime);
6148 getListener()->notifyMotion(&args);
6149 }
6150
6151 // Send move.
6152 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006153 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006154 mViewport.displayId,
6155 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6156 mOrientedXPrecision, mOrientedYPrecision,
6157 mPointerSimple.downTime);
6158 getListener()->notifyMotion(&args);
6159 }
6160
6161 if (hovering) {
6162 if (!mPointerSimple.hovering) {
6163 mPointerSimple.hovering = true;
6164
6165 // Send hover enter.
6166 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006167 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006168 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006169 mViewport.displayId,
6170 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6171 mOrientedXPrecision, mOrientedYPrecision,
6172 mPointerSimple.downTime);
6173 getListener()->notifyMotion(&args);
6174 }
6175
6176 // Send hover move.
6177 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006178 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006179 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180 mViewport.displayId,
6181 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6182 mOrientedXPrecision, mOrientedYPrecision,
6183 mPointerSimple.downTime);
6184 getListener()->notifyMotion(&args);
6185 }
6186
Michael Wright842500e2015-03-13 17:32:02 -07006187 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6188 float vscroll = mCurrentRawState.rawVScroll;
6189 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006190 mWheelYVelocityControl.move(when, NULL, &vscroll);
6191 mWheelXVelocityControl.move(when, &hscroll, NULL);
6192
6193 // Send scroll.
6194 PointerCoords pointerCoords;
6195 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6196 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6197 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6198
6199 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006200 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006201 mViewport.displayId,
6202 1, &mPointerSimple.currentProperties, &pointerCoords,
6203 mOrientedXPrecision, mOrientedYPrecision,
6204 mPointerSimple.downTime);
6205 getListener()->notifyMotion(&args);
6206 }
6207
6208 // Save state.
6209 if (down || hovering) {
6210 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6211 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6212 } else {
6213 mPointerSimple.reset();
6214 }
6215}
6216
6217void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6218 mPointerSimple.currentCoords.clear();
6219 mPointerSimple.currentProperties.clear();
6220
6221 dispatchPointerSimple(when, policyFlags, false, false);
6222}
6223
6224void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006225 int32_t action, int32_t actionButton, int32_t flags,
6226 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006227 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006228 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6229 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 PointerCoords pointerCoords[MAX_POINTERS];
6231 PointerProperties pointerProperties[MAX_POINTERS];
6232 uint32_t pointerCount = 0;
6233 while (!idBits.isEmpty()) {
6234 uint32_t id = idBits.clearFirstMarkedBit();
6235 uint32_t index = idToIndex[id];
6236 pointerProperties[pointerCount].copyFrom(properties[index]);
6237 pointerCoords[pointerCount].copyFrom(coords[index]);
6238
6239 if (changedId >= 0 && id == uint32_t(changedId)) {
6240 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6241 }
6242
6243 pointerCount += 1;
6244 }
6245
6246 ALOG_ASSERT(pointerCount != 0);
6247
6248 if (changedId >= 0 && pointerCount == 1) {
6249 // Replace initial down and final up action.
6250 // We can compare the action without masking off the changed pointer index
6251 // because we know the index is 0.
6252 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6253 action = AMOTION_EVENT_ACTION_DOWN;
6254 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6255 action = AMOTION_EVENT_ACTION_UP;
6256 } else {
6257 // Can't happen.
6258 ALOG_ASSERT(false);
6259 }
6260 }
6261
6262 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006263 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6265 xPrecision, yPrecision, downTime);
6266 getListener()->notifyMotion(&args);
6267}
6268
6269bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6270 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6271 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6272 BitSet32 idBits) const {
6273 bool changed = false;
6274 while (!idBits.isEmpty()) {
6275 uint32_t id = idBits.clearFirstMarkedBit();
6276 uint32_t inIndex = inIdToIndex[id];
6277 uint32_t outIndex = outIdToIndex[id];
6278
6279 const PointerProperties& curInProperties = inProperties[inIndex];
6280 const PointerCoords& curInCoords = inCoords[inIndex];
6281 PointerProperties& curOutProperties = outProperties[outIndex];
6282 PointerCoords& curOutCoords = outCoords[outIndex];
6283
6284 if (curInProperties != curOutProperties) {
6285 curOutProperties.copyFrom(curInProperties);
6286 changed = true;
6287 }
6288
6289 if (curInCoords != curOutCoords) {
6290 curOutCoords.copyFrom(curInCoords);
6291 changed = true;
6292 }
6293 }
6294 return changed;
6295}
6296
6297void TouchInputMapper::fadePointer() {
6298 if (mPointerController != NULL) {
6299 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6300 }
6301}
6302
Jeff Brownc9aa6282015-02-11 19:03:28 -08006303void TouchInputMapper::cancelTouch(nsecs_t when) {
6304 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006305 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006306}
6307
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6309 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6310 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6311}
6312
6313const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6314 int32_t x, int32_t y) {
6315 size_t numVirtualKeys = mVirtualKeys.size();
6316 for (size_t i = 0; i < numVirtualKeys; i++) {
6317 const VirtualKey& virtualKey = mVirtualKeys[i];
6318
6319#if DEBUG_VIRTUAL_KEYS
6320 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6321 "left=%d, top=%d, right=%d, bottom=%d",
6322 x, y,
6323 virtualKey.keyCode, virtualKey.scanCode,
6324 virtualKey.hitLeft, virtualKey.hitTop,
6325 virtualKey.hitRight, virtualKey.hitBottom);
6326#endif
6327
6328 if (virtualKey.isHit(x, y)) {
6329 return & virtualKey;
6330 }
6331 }
6332
6333 return NULL;
6334}
6335
Michael Wright842500e2015-03-13 17:32:02 -07006336void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6337 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6338 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006339
Michael Wright842500e2015-03-13 17:32:02 -07006340 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006341
6342 if (currentPointerCount == 0) {
6343 // No pointers to assign.
6344 return;
6345 }
6346
6347 if (lastPointerCount == 0) {
6348 // All pointers are new.
6349 for (uint32_t i = 0; i < currentPointerCount; i++) {
6350 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006351 current->rawPointerData.pointers[i].id = id;
6352 current->rawPointerData.idToIndex[id] = i;
6353 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354 }
6355 return;
6356 }
6357
6358 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006359 && current->rawPointerData.pointers[0].toolType
6360 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006362 uint32_t id = last->rawPointerData.pointers[0].id;
6363 current->rawPointerData.pointers[0].id = id;
6364 current->rawPointerData.idToIndex[id] = 0;
6365 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 return;
6367 }
6368
6369 // General case.
6370 // We build a heap of squared euclidean distances between current and last pointers
6371 // associated with the current and last pointer indices. Then, we find the best
6372 // match (by distance) for each current pointer.
6373 // The pointers must have the same tool type but it is possible for them to
6374 // transition from hovering to touching or vice-versa while retaining the same id.
6375 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6376
6377 uint32_t heapSize = 0;
6378 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6379 currentPointerIndex++) {
6380 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6381 lastPointerIndex++) {
6382 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006383 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006385 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 if (currentPointer.toolType == lastPointer.toolType) {
6387 int64_t deltaX = currentPointer.x - lastPointer.x;
6388 int64_t deltaY = currentPointer.y - lastPointer.y;
6389
6390 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6391
6392 // Insert new element into the heap (sift up).
6393 heap[heapSize].currentPointerIndex = currentPointerIndex;
6394 heap[heapSize].lastPointerIndex = lastPointerIndex;
6395 heap[heapSize].distance = distance;
6396 heapSize += 1;
6397 }
6398 }
6399 }
6400
6401 // Heapify
6402 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6403 startIndex -= 1;
6404 for (uint32_t parentIndex = startIndex; ;) {
6405 uint32_t childIndex = parentIndex * 2 + 1;
6406 if (childIndex >= heapSize) {
6407 break;
6408 }
6409
6410 if (childIndex + 1 < heapSize
6411 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6412 childIndex += 1;
6413 }
6414
6415 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6416 break;
6417 }
6418
6419 swap(heap[parentIndex], heap[childIndex]);
6420 parentIndex = childIndex;
6421 }
6422 }
6423
6424#if DEBUG_POINTER_ASSIGNMENT
6425 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6426 for (size_t i = 0; i < heapSize; i++) {
6427 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6428 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6429 heap[i].distance);
6430 }
6431#endif
6432
6433 // Pull matches out by increasing order of distance.
6434 // To avoid reassigning pointers that have already been matched, the loop keeps track
6435 // of which last and current pointers have been matched using the matchedXXXBits variables.
6436 // It also tracks the used pointer id bits.
6437 BitSet32 matchedLastBits(0);
6438 BitSet32 matchedCurrentBits(0);
6439 BitSet32 usedIdBits(0);
6440 bool first = true;
6441 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6442 while (heapSize > 0) {
6443 if (first) {
6444 // The first time through the loop, we just consume the root element of
6445 // the heap (the one with smallest distance).
6446 first = false;
6447 } else {
6448 // Previous iterations consumed the root element of the heap.
6449 // Pop root element off of the heap (sift down).
6450 heap[0] = heap[heapSize];
6451 for (uint32_t parentIndex = 0; ;) {
6452 uint32_t childIndex = parentIndex * 2 + 1;
6453 if (childIndex >= heapSize) {
6454 break;
6455 }
6456
6457 if (childIndex + 1 < heapSize
6458 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6459 childIndex += 1;
6460 }
6461
6462 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6463 break;
6464 }
6465
6466 swap(heap[parentIndex], heap[childIndex]);
6467 parentIndex = childIndex;
6468 }
6469
6470#if DEBUG_POINTER_ASSIGNMENT
6471 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6472 for (size_t i = 0; i < heapSize; i++) {
6473 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6474 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6475 heap[i].distance);
6476 }
6477#endif
6478 }
6479
6480 heapSize -= 1;
6481
6482 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6483 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6484
6485 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6486 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6487
6488 matchedCurrentBits.markBit(currentPointerIndex);
6489 matchedLastBits.markBit(lastPointerIndex);
6490
Michael Wright842500e2015-03-13 17:32:02 -07006491 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6492 current->rawPointerData.pointers[currentPointerIndex].id = id;
6493 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6494 current->rawPointerData.markIdBit(id,
6495 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006496 usedIdBits.markBit(id);
6497
6498#if DEBUG_POINTER_ASSIGNMENT
6499 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6500 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6501#endif
6502 break;
6503 }
6504 }
6505
6506 // Assign fresh ids to pointers that were not matched in the process.
6507 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6508 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6509 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6510
Michael Wright842500e2015-03-13 17:32:02 -07006511 current->rawPointerData.pointers[currentPointerIndex].id = id;
6512 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6513 current->rawPointerData.markIdBit(id,
6514 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006515
6516#if DEBUG_POINTER_ASSIGNMENT
6517 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6518 currentPointerIndex, id);
6519#endif
6520 }
6521}
6522
6523int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6524 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6525 return AKEY_STATE_VIRTUAL;
6526 }
6527
6528 size_t numVirtualKeys = mVirtualKeys.size();
6529 for (size_t i = 0; i < numVirtualKeys; i++) {
6530 const VirtualKey& virtualKey = mVirtualKeys[i];
6531 if (virtualKey.keyCode == keyCode) {
6532 return AKEY_STATE_UP;
6533 }
6534 }
6535
6536 return AKEY_STATE_UNKNOWN;
6537}
6538
6539int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6540 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6541 return AKEY_STATE_VIRTUAL;
6542 }
6543
6544 size_t numVirtualKeys = mVirtualKeys.size();
6545 for (size_t i = 0; i < numVirtualKeys; i++) {
6546 const VirtualKey& virtualKey = mVirtualKeys[i];
6547 if (virtualKey.scanCode == scanCode) {
6548 return AKEY_STATE_UP;
6549 }
6550 }
6551
6552 return AKEY_STATE_UNKNOWN;
6553}
6554
6555bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6556 const int32_t* keyCodes, uint8_t* outFlags) {
6557 size_t numVirtualKeys = mVirtualKeys.size();
6558 for (size_t i = 0; i < numVirtualKeys; i++) {
6559 const VirtualKey& virtualKey = mVirtualKeys[i];
6560
6561 for (size_t i = 0; i < numCodes; i++) {
6562 if (virtualKey.keyCode == keyCodes[i]) {
6563 outFlags[i] = 1;
6564 }
6565 }
6566 }
6567
6568 return true;
6569}
6570
6571
6572// --- SingleTouchInputMapper ---
6573
6574SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6575 TouchInputMapper(device) {
6576}
6577
6578SingleTouchInputMapper::~SingleTouchInputMapper() {
6579}
6580
6581void SingleTouchInputMapper::reset(nsecs_t when) {
6582 mSingleTouchMotionAccumulator.reset(getDevice());
6583
6584 TouchInputMapper::reset(when);
6585}
6586
6587void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6588 TouchInputMapper::process(rawEvent);
6589
6590 mSingleTouchMotionAccumulator.process(rawEvent);
6591}
6592
Michael Wright842500e2015-03-13 17:32:02 -07006593void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006594 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006595 outState->rawPointerData.pointerCount = 1;
6596 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597
6598 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6599 && (mTouchButtonAccumulator.isHovering()
6600 || (mRawPointerAxes.pressure.valid
6601 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006602 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603
Michael Wright842500e2015-03-13 17:32:02 -07006604 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006605 outPointer.id = 0;
6606 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6607 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6608 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6609 outPointer.touchMajor = 0;
6610 outPointer.touchMinor = 0;
6611 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6612 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6613 outPointer.orientation = 0;
6614 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6615 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6616 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6617 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6618 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6619 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6620 }
6621 outPointer.isHovering = isHovering;
6622 }
6623}
6624
6625void SingleTouchInputMapper::configureRawPointerAxes() {
6626 TouchInputMapper::configureRawPointerAxes();
6627
6628 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6629 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6630 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6631 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6632 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6633 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6634 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6635}
6636
6637bool SingleTouchInputMapper::hasStylus() const {
6638 return mTouchButtonAccumulator.hasStylus();
6639}
6640
6641
6642// --- MultiTouchInputMapper ---
6643
6644MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6645 TouchInputMapper(device) {
6646}
6647
6648MultiTouchInputMapper::~MultiTouchInputMapper() {
6649}
6650
6651void MultiTouchInputMapper::reset(nsecs_t when) {
6652 mMultiTouchMotionAccumulator.reset(getDevice());
6653
6654 mPointerIdBits.clear();
6655
6656 TouchInputMapper::reset(when);
6657}
6658
6659void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6660 TouchInputMapper::process(rawEvent);
6661
6662 mMultiTouchMotionAccumulator.process(rawEvent);
6663}
6664
Michael Wright842500e2015-03-13 17:32:02 -07006665void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6667 size_t outCount = 0;
6668 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006669 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006670
6671 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6672 const MultiTouchMotionAccumulator::Slot* inSlot =
6673 mMultiTouchMotionAccumulator.getSlot(inIndex);
6674 if (!inSlot->isInUse()) {
6675 continue;
6676 }
6677
6678 if (outCount >= MAX_POINTERS) {
6679#if DEBUG_POINTERS
6680 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6681 "ignoring the rest.",
6682 getDeviceName().string(), MAX_POINTERS);
6683#endif
6684 break; // too many fingers!
6685 }
6686
Michael Wright842500e2015-03-13 17:32:02 -07006687 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006688 outPointer.x = inSlot->getX();
6689 outPointer.y = inSlot->getY();
6690 outPointer.pressure = inSlot->getPressure();
6691 outPointer.touchMajor = inSlot->getTouchMajor();
6692 outPointer.touchMinor = inSlot->getTouchMinor();
6693 outPointer.toolMajor = inSlot->getToolMajor();
6694 outPointer.toolMinor = inSlot->getToolMinor();
6695 outPointer.orientation = inSlot->getOrientation();
6696 outPointer.distance = inSlot->getDistance();
6697 outPointer.tiltX = 0;
6698 outPointer.tiltY = 0;
6699
6700 outPointer.toolType = inSlot->getToolType();
6701 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6702 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6703 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6704 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6705 }
6706 }
6707
6708 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6709 && (mTouchButtonAccumulator.isHovering()
6710 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6711 outPointer.isHovering = isHovering;
6712
6713 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006714 if (mHavePointerIds) {
6715 int32_t trackingId = inSlot->getTrackingId();
6716 int32_t id = -1;
6717 if (trackingId >= 0) {
6718 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6719 uint32_t n = idBits.clearFirstMarkedBit();
6720 if (mPointerTrackingIdMap[n] == trackingId) {
6721 id = n;
6722 }
6723 }
6724
6725 if (id < 0 && !mPointerIdBits.isFull()) {
6726 id = mPointerIdBits.markFirstUnmarkedBit();
6727 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006728 }
Michael Wright842500e2015-03-13 17:32:02 -07006729 }
gaoshang1a632de2016-08-24 10:23:50 +08006730 if (id < 0) {
6731 mHavePointerIds = false;
6732 outState->rawPointerData.clearIdBits();
6733 newPointerIdBits.clear();
6734 } else {
6735 outPointer.id = id;
6736 outState->rawPointerData.idToIndex[id] = outCount;
6737 outState->rawPointerData.markIdBit(id, isHovering);
6738 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006739 }
Michael Wright842500e2015-03-13 17:32:02 -07006740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006741 outCount += 1;
6742 }
6743
Michael Wright842500e2015-03-13 17:32:02 -07006744 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006745 mPointerIdBits = newPointerIdBits;
6746
6747 mMultiTouchMotionAccumulator.finishSync();
6748}
6749
6750void MultiTouchInputMapper::configureRawPointerAxes() {
6751 TouchInputMapper::configureRawPointerAxes();
6752
6753 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6754 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6755 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6756 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6757 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6758 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6759 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6760 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6761 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6762 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6763 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6764
6765 if (mRawPointerAxes.trackingId.valid
6766 && mRawPointerAxes.slot.valid
6767 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6768 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6769 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006770 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6771 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006772 getDeviceName().string(), slotCount, MAX_SLOTS);
6773 slotCount = MAX_SLOTS;
6774 }
6775 mMultiTouchMotionAccumulator.configure(getDevice(),
6776 slotCount, true /*usingSlotsProtocol*/);
6777 } else {
6778 mMultiTouchMotionAccumulator.configure(getDevice(),
6779 MAX_POINTERS, false /*usingSlotsProtocol*/);
6780 }
6781}
6782
6783bool MultiTouchInputMapper::hasStylus() const {
6784 return mMultiTouchMotionAccumulator.hasStylus()
6785 || mTouchButtonAccumulator.hasStylus();
6786}
6787
Michael Wright842500e2015-03-13 17:32:02 -07006788// --- ExternalStylusInputMapper
6789
6790ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6791 InputMapper(device) {
6792
6793}
6794
6795uint32_t ExternalStylusInputMapper::getSources() {
6796 return AINPUT_SOURCE_STYLUS;
6797}
6798
6799void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6800 InputMapper::populateDeviceInfo(info);
6801 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6802 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6803}
6804
6805void ExternalStylusInputMapper::dump(String8& dump) {
6806 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6807 dump.append(INDENT3 "Raw Stylus Axes:\n");
6808 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6809 dump.append(INDENT3 "Stylus State:\n");
6810 dumpStylusState(dump, mStylusState);
6811}
6812
6813void ExternalStylusInputMapper::configure(nsecs_t when,
6814 const InputReaderConfiguration* config, uint32_t changes) {
6815 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6816 mTouchButtonAccumulator.configure(getDevice());
6817}
6818
6819void ExternalStylusInputMapper::reset(nsecs_t when) {
6820 InputDevice* device = getDevice();
6821 mSingleTouchMotionAccumulator.reset(device);
6822 mTouchButtonAccumulator.reset(device);
6823 InputMapper::reset(when);
6824}
6825
6826void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6827 mSingleTouchMotionAccumulator.process(rawEvent);
6828 mTouchButtonAccumulator.process(rawEvent);
6829
6830 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6831 sync(rawEvent->when);
6832 }
6833}
6834
6835void ExternalStylusInputMapper::sync(nsecs_t when) {
6836 mStylusState.clear();
6837
6838 mStylusState.when = when;
6839
Michael Wright45ccacf2015-04-21 19:01:58 +01006840 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6841 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6842 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6843 }
6844
Michael Wright842500e2015-03-13 17:32:02 -07006845 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6846 if (mRawPressureAxis.valid) {
6847 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6848 } else if (mTouchButtonAccumulator.isToolActive()) {
6849 mStylusState.pressure = 1.0f;
6850 } else {
6851 mStylusState.pressure = 0.0f;
6852 }
6853
6854 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07006855
6856 mContext->dispatchExternalStylusState(mStylusState);
6857}
6858
Michael Wrightd02c5b62014-02-10 15:10:22 -08006859
6860// --- JoystickInputMapper ---
6861
6862JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6863 InputMapper(device) {
6864}
6865
6866JoystickInputMapper::~JoystickInputMapper() {
6867}
6868
6869uint32_t JoystickInputMapper::getSources() {
6870 return AINPUT_SOURCE_JOYSTICK;
6871}
6872
6873void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6874 InputMapper::populateDeviceInfo(info);
6875
6876 for (size_t i = 0; i < mAxes.size(); i++) {
6877 const Axis& axis = mAxes.valueAt(i);
6878 addMotionRange(axis.axisInfo.axis, axis, info);
6879
6880 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6881 addMotionRange(axis.axisInfo.highAxis, axis, info);
6882
6883 }
6884 }
6885}
6886
6887void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6888 InputDeviceInfo* info) {
6889 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6890 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6891 /* In order to ease the transition for developers from using the old axes
6892 * to the newer, more semantically correct axes, we'll continue to register
6893 * the old axes as duplicates of their corresponding new ones. */
6894 int32_t compatAxis = getCompatAxis(axisId);
6895 if (compatAxis >= 0) {
6896 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6897 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6898 }
6899}
6900
6901/* A mapping from axes the joystick actually has to the axes that should be
6902 * artificially created for compatibility purposes.
6903 * Returns -1 if no compatibility axis is needed. */
6904int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6905 switch(axis) {
6906 case AMOTION_EVENT_AXIS_LTRIGGER:
6907 return AMOTION_EVENT_AXIS_BRAKE;
6908 case AMOTION_EVENT_AXIS_RTRIGGER:
6909 return AMOTION_EVENT_AXIS_GAS;
6910 }
6911 return -1;
6912}
6913
6914void JoystickInputMapper::dump(String8& dump) {
6915 dump.append(INDENT2 "Joystick Input Mapper:\n");
6916
6917 dump.append(INDENT3 "Axes:\n");
6918 size_t numAxes = mAxes.size();
6919 for (size_t i = 0; i < numAxes; i++) {
6920 const Axis& axis = mAxes.valueAt(i);
6921 const char* label = getAxisLabel(axis.axisInfo.axis);
6922 if (label) {
6923 dump.appendFormat(INDENT4 "%s", label);
6924 } else {
6925 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6926 }
6927 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6928 label = getAxisLabel(axis.axisInfo.highAxis);
6929 if (label) {
6930 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6931 } else {
6932 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6933 axis.axisInfo.splitValue);
6934 }
6935 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6936 dump.append(" (invert)");
6937 }
6938
6939 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6940 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6941 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
6942 "highScale=%0.5f, highOffset=%0.5f\n",
6943 axis.scale, axis.offset, axis.highScale, axis.highOffset);
6944 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
6945 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6946 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6947 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6948 }
6949}
6950
6951void JoystickInputMapper::configure(nsecs_t when,
6952 const InputReaderConfiguration* config, uint32_t changes) {
6953 InputMapper::configure(when, config, changes);
6954
6955 if (!changes) { // first time only
6956 // Collect all axes.
6957 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6958 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6959 & INPUT_DEVICE_CLASS_JOYSTICK)) {
6960 continue; // axis must be claimed by a different device
6961 }
6962
6963 RawAbsoluteAxisInfo rawAxisInfo;
6964 getAbsoluteAxisInfo(abs, &rawAxisInfo);
6965 if (rawAxisInfo.valid) {
6966 // Map axis.
6967 AxisInfo axisInfo;
6968 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6969 if (!explicitlyMapped) {
6970 // Axis is not explicitly mapped, will choose a generic axis later.
6971 axisInfo.mode = AxisInfo::MODE_NORMAL;
6972 axisInfo.axis = -1;
6973 }
6974
6975 // Apply flat override.
6976 int32_t rawFlat = axisInfo.flatOverride < 0
6977 ? rawAxisInfo.flat : axisInfo.flatOverride;
6978
6979 // Calculate scaling factors and limits.
6980 Axis axis;
6981 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6982 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6983 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6984 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6985 scale, 0.0f, highScale, 0.0f,
6986 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6987 rawAxisInfo.resolution * scale);
6988 } else if (isCenteredAxis(axisInfo.axis)) {
6989 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6990 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6991 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6992 scale, offset, scale, offset,
6993 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6994 rawAxisInfo.resolution * scale);
6995 } else {
6996 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6997 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6998 scale, 0.0f, scale, 0.0f,
6999 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7000 rawAxisInfo.resolution * scale);
7001 }
7002
7003 // To eliminate noise while the joystick is at rest, filter out small variations
7004 // in axis values up front.
7005 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7006
7007 mAxes.add(abs, axis);
7008 }
7009 }
7010
7011 // If there are too many axes, start dropping them.
7012 // Prefer to keep explicitly mapped axes.
7013 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007014 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007015 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7016 pruneAxes(true);
7017 pruneAxes(false);
7018 }
7019
7020 // Assign generic axis ids to remaining axes.
7021 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7022 size_t numAxes = mAxes.size();
7023 for (size_t i = 0; i < numAxes; i++) {
7024 Axis& axis = mAxes.editValueAt(i);
7025 if (axis.axisInfo.axis < 0) {
7026 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7027 && haveAxis(nextGenericAxisId)) {
7028 nextGenericAxisId += 1;
7029 }
7030
7031 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7032 axis.axisInfo.axis = nextGenericAxisId;
7033 nextGenericAxisId += 1;
7034 } else {
7035 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7036 "have already been assigned to other axes.",
7037 getDeviceName().string(), mAxes.keyAt(i));
7038 mAxes.removeItemsAt(i--);
7039 numAxes -= 1;
7040 }
7041 }
7042 }
7043 }
7044}
7045
7046bool JoystickInputMapper::haveAxis(int32_t axisId) {
7047 size_t numAxes = mAxes.size();
7048 for (size_t i = 0; i < numAxes; i++) {
7049 const Axis& axis = mAxes.valueAt(i);
7050 if (axis.axisInfo.axis == axisId
7051 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7052 && axis.axisInfo.highAxis == axisId)) {
7053 return true;
7054 }
7055 }
7056 return false;
7057}
7058
7059void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7060 size_t i = mAxes.size();
7061 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7062 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7063 continue;
7064 }
7065 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7066 getDeviceName().string(), mAxes.keyAt(i));
7067 mAxes.removeItemsAt(i);
7068 }
7069}
7070
7071bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7072 switch (axis) {
7073 case AMOTION_EVENT_AXIS_X:
7074 case AMOTION_EVENT_AXIS_Y:
7075 case AMOTION_EVENT_AXIS_Z:
7076 case AMOTION_EVENT_AXIS_RX:
7077 case AMOTION_EVENT_AXIS_RY:
7078 case AMOTION_EVENT_AXIS_RZ:
7079 case AMOTION_EVENT_AXIS_HAT_X:
7080 case AMOTION_EVENT_AXIS_HAT_Y:
7081 case AMOTION_EVENT_AXIS_ORIENTATION:
7082 case AMOTION_EVENT_AXIS_RUDDER:
7083 case AMOTION_EVENT_AXIS_WHEEL:
7084 return true;
7085 default:
7086 return false;
7087 }
7088}
7089
7090void JoystickInputMapper::reset(nsecs_t when) {
7091 // Recenter all axes.
7092 size_t numAxes = mAxes.size();
7093 for (size_t i = 0; i < numAxes; i++) {
7094 Axis& axis = mAxes.editValueAt(i);
7095 axis.resetValue();
7096 }
7097
7098 InputMapper::reset(when);
7099}
7100
7101void JoystickInputMapper::process(const RawEvent* rawEvent) {
7102 switch (rawEvent->type) {
7103 case EV_ABS: {
7104 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7105 if (index >= 0) {
7106 Axis& axis = mAxes.editValueAt(index);
7107 float newValue, highNewValue;
7108 switch (axis.axisInfo.mode) {
7109 case AxisInfo::MODE_INVERT:
7110 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7111 * axis.scale + axis.offset;
7112 highNewValue = 0.0f;
7113 break;
7114 case AxisInfo::MODE_SPLIT:
7115 if (rawEvent->value < axis.axisInfo.splitValue) {
7116 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7117 * axis.scale + axis.offset;
7118 highNewValue = 0.0f;
7119 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7120 newValue = 0.0f;
7121 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7122 * axis.highScale + axis.highOffset;
7123 } else {
7124 newValue = 0.0f;
7125 highNewValue = 0.0f;
7126 }
7127 break;
7128 default:
7129 newValue = rawEvent->value * axis.scale + axis.offset;
7130 highNewValue = 0.0f;
7131 break;
7132 }
7133 axis.newValue = newValue;
7134 axis.highNewValue = highNewValue;
7135 }
7136 break;
7137 }
7138
7139 case EV_SYN:
7140 switch (rawEvent->code) {
7141 case SYN_REPORT:
7142 sync(rawEvent->when, false /*force*/);
7143 break;
7144 }
7145 break;
7146 }
7147}
7148
7149void JoystickInputMapper::sync(nsecs_t when, bool force) {
7150 if (!filterAxes(force)) {
7151 return;
7152 }
7153
7154 int32_t metaState = mContext->getGlobalMetaState();
7155 int32_t buttonState = 0;
7156
7157 PointerProperties pointerProperties;
7158 pointerProperties.clear();
7159 pointerProperties.id = 0;
7160 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7161
7162 PointerCoords pointerCoords;
7163 pointerCoords.clear();
7164
7165 size_t numAxes = mAxes.size();
7166 for (size_t i = 0; i < numAxes; i++) {
7167 const Axis& axis = mAxes.valueAt(i);
7168 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7169 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7170 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7171 axis.highCurrentValue);
7172 }
7173 }
7174
7175 // Moving a joystick axis should not wake the device because joysticks can
7176 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7177 // button will likely wake the device.
7178 // TODO: Use the input device configuration to control this behavior more finely.
7179 uint32_t policyFlags = 0;
7180
7181 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007182 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007183 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7184 getListener()->notifyMotion(&args);
7185}
7186
7187void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7188 int32_t axis, float value) {
7189 pointerCoords->setAxisValue(axis, value);
7190 /* In order to ease the transition for developers from using the old axes
7191 * to the newer, more semantically correct axes, we'll continue to produce
7192 * values for the old axes as mirrors of the value of their corresponding
7193 * new axes. */
7194 int32_t compatAxis = getCompatAxis(axis);
7195 if (compatAxis >= 0) {
7196 pointerCoords->setAxisValue(compatAxis, value);
7197 }
7198}
7199
7200bool JoystickInputMapper::filterAxes(bool force) {
7201 bool atLeastOneSignificantChange = force;
7202 size_t numAxes = mAxes.size();
7203 for (size_t i = 0; i < numAxes; i++) {
7204 Axis& axis = mAxes.editValueAt(i);
7205 if (force || hasValueChangedSignificantly(axis.filter,
7206 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7207 axis.currentValue = axis.newValue;
7208 atLeastOneSignificantChange = true;
7209 }
7210 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7211 if (force || hasValueChangedSignificantly(axis.filter,
7212 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7213 axis.highCurrentValue = axis.highNewValue;
7214 atLeastOneSignificantChange = true;
7215 }
7216 }
7217 }
7218 return atLeastOneSignificantChange;
7219}
7220
7221bool JoystickInputMapper::hasValueChangedSignificantly(
7222 float filter, float newValue, float currentValue, float min, float max) {
7223 if (newValue != currentValue) {
7224 // Filter out small changes in value unless the value is converging on the axis
7225 // bounds or center point. This is intended to reduce the amount of information
7226 // sent to applications by particularly noisy joysticks (such as PS3).
7227 if (fabs(newValue - currentValue) > filter
7228 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7229 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7230 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7231 return true;
7232 }
7233 }
7234 return false;
7235}
7236
7237bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7238 float filter, float newValue, float currentValue, float thresholdValue) {
7239 float newDistance = fabs(newValue - thresholdValue);
7240 if (newDistance < filter) {
7241 float oldDistance = fabs(currentValue - thresholdValue);
7242 if (newDistance < oldDistance) {
7243 return true;
7244 }
7245 }
7246 return false;
7247}
7248
7249} // namespace android