blob: e381f63bcc5878305f64495ed04bc78b47e7d6c7 [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 if (down && !isMetaKey(keyCode)) {
2326 getContext()->fadePointer();
2327 }
2328
2329 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2330 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002331 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 getListener()->notifyKey(&args);
2333}
2334
2335ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2336 size_t n = mKeyDowns.size();
2337 for (size_t i = 0; i < n; i++) {
2338 if (mKeyDowns[i].scanCode == scanCode) {
2339 return i;
2340 }
2341 }
2342 return -1;
2343}
2344
2345int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2346 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2347}
2348
2349int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2350 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2351}
2352
2353bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2354 const int32_t* keyCodes, uint8_t* outFlags) {
2355 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2356}
2357
2358int32_t KeyboardInputMapper::getMetaState() {
2359 return mMetaState;
2360}
2361
Andrii Kulian763a3a42016-03-08 10:46:16 -08002362void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2363 updateMetaStateIfNeeded(keyCode, false);
2364}
2365
2366bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2367 int32_t oldMetaState = mMetaState;
2368 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2369 bool metaStateChanged = oldMetaState != newMetaState;
2370 if (metaStateChanged) {
2371 mMetaState = newMetaState;
2372 updateLedState(false);
2373
2374 getContext()->updateGlobalMetaState();
2375 }
2376
2377 return metaStateChanged;
2378}
2379
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380void KeyboardInputMapper::resetLedState() {
2381 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2382 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2383 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2384
2385 updateLedState(true);
2386}
2387
2388void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2389 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2390 ledState.on = false;
2391}
2392
2393void KeyboardInputMapper::updateLedState(bool reset) {
2394 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2395 AMETA_CAPS_LOCK_ON, reset);
2396 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2397 AMETA_NUM_LOCK_ON, reset);
2398 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2399 AMETA_SCROLL_LOCK_ON, reset);
2400}
2401
2402void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2403 int32_t led, int32_t modifier, bool reset) {
2404 if (ledState.avail) {
2405 bool desiredState = (mMetaState & modifier) != 0;
2406 if (reset || ledState.on != desiredState) {
2407 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2408 ledState.on = desiredState;
2409 }
2410 }
2411}
2412
2413
2414// --- CursorInputMapper ---
2415
2416CursorInputMapper::CursorInputMapper(InputDevice* device) :
2417 InputMapper(device) {
2418}
2419
2420CursorInputMapper::~CursorInputMapper() {
2421}
2422
2423uint32_t CursorInputMapper::getSources() {
2424 return mSource;
2425}
2426
2427void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2428 InputMapper::populateDeviceInfo(info);
2429
2430 if (mParameters.mode == Parameters::MODE_POINTER) {
2431 float minX, minY, maxX, maxY;
2432 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2433 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2434 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2435 }
2436 } else {
2437 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2438 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2439 }
2440 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2441
2442 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2443 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2444 }
2445 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2446 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2447 }
2448}
2449
2450void CursorInputMapper::dump(String8& dump) {
2451 dump.append(INDENT2 "Cursor Input Mapper:\n");
2452 dumpParameters(dump);
2453 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2454 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2455 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2456 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2457 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2458 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2459 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2460 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2461 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2462 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2463 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2464 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2465 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002466 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467}
2468
2469void CursorInputMapper::configure(nsecs_t when,
2470 const InputReaderConfiguration* config, uint32_t changes) {
2471 InputMapper::configure(when, config, changes);
2472
2473 if (!changes) { // first time only
2474 mCursorScrollAccumulator.configure(getDevice());
2475
2476 // Configure basic parameters.
2477 configureParameters();
2478
2479 // Configure device mode.
2480 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002481 case Parameters::MODE_POINTER_RELATIVE:
2482 // Should not happen during first time configuration.
2483 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2484 mParameters.mode = Parameters::MODE_POINTER;
2485 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 case Parameters::MODE_POINTER:
2487 mSource = AINPUT_SOURCE_MOUSE;
2488 mXPrecision = 1.0f;
2489 mYPrecision = 1.0f;
2490 mXScale = 1.0f;
2491 mYScale = 1.0f;
2492 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2493 break;
2494 case Parameters::MODE_NAVIGATION:
2495 mSource = AINPUT_SOURCE_TRACKBALL;
2496 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2497 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2498 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2499 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2500 break;
2501 }
2502
2503 mVWheelScale = 1.0f;
2504 mHWheelScale = 1.0f;
2505 }
2506
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002507 if ((!changes && config->pointerCapture)
2508 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2509 if (config->pointerCapture) {
2510 if (mParameters.mode == Parameters::MODE_POINTER) {
2511 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2512 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2513 // Keep PointerController around in order to preserve the pointer position.
2514 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2515 } else {
2516 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2517 }
2518 } else {
2519 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2520 mParameters.mode = Parameters::MODE_POINTER;
2521 mSource = AINPUT_SOURCE_MOUSE;
2522 } else {
2523 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2524 }
2525 }
2526 bumpGeneration();
2527 if (changes) {
2528 getDevice()->notifyReset(when);
2529 }
2530 }
2531
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2533 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2534 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2535 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2536 }
2537
2538 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2539 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2540 DisplayViewport v;
2541 if (config->getDisplayInfo(false /*external*/, &v)) {
2542 mOrientation = v.orientation;
2543 } else {
2544 mOrientation = DISPLAY_ORIENTATION_0;
2545 }
2546 } else {
2547 mOrientation = DISPLAY_ORIENTATION_0;
2548 }
2549 bumpGeneration();
2550 }
2551}
2552
2553void CursorInputMapper::configureParameters() {
2554 mParameters.mode = Parameters::MODE_POINTER;
2555 String8 cursorModeString;
2556 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2557 if (cursorModeString == "navigation") {
2558 mParameters.mode = Parameters::MODE_NAVIGATION;
2559 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2560 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2561 }
2562 }
2563
2564 mParameters.orientationAware = false;
2565 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2566 mParameters.orientationAware);
2567
2568 mParameters.hasAssociatedDisplay = false;
2569 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2570 mParameters.hasAssociatedDisplay = true;
2571 }
2572}
2573
2574void CursorInputMapper::dumpParameters(String8& dump) {
2575 dump.append(INDENT3 "Parameters:\n");
2576 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2577 toString(mParameters.hasAssociatedDisplay));
2578
2579 switch (mParameters.mode) {
2580 case Parameters::MODE_POINTER:
2581 dump.append(INDENT4 "Mode: pointer\n");
2582 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002583 case Parameters::MODE_POINTER_RELATIVE:
2584 dump.append(INDENT4 "Mode: relative pointer\n");
2585 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 case Parameters::MODE_NAVIGATION:
2587 dump.append(INDENT4 "Mode: navigation\n");
2588 break;
2589 default:
2590 ALOG_ASSERT(false);
2591 }
2592
2593 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2594 toString(mParameters.orientationAware));
2595}
2596
2597void CursorInputMapper::reset(nsecs_t when) {
2598 mButtonState = 0;
2599 mDownTime = 0;
2600
2601 mPointerVelocityControl.reset();
2602 mWheelXVelocityControl.reset();
2603 mWheelYVelocityControl.reset();
2604
2605 mCursorButtonAccumulator.reset(getDevice());
2606 mCursorMotionAccumulator.reset(getDevice());
2607 mCursorScrollAccumulator.reset(getDevice());
2608
2609 InputMapper::reset(when);
2610}
2611
2612void CursorInputMapper::process(const RawEvent* rawEvent) {
2613 mCursorButtonAccumulator.process(rawEvent);
2614 mCursorMotionAccumulator.process(rawEvent);
2615 mCursorScrollAccumulator.process(rawEvent);
2616
2617 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2618 sync(rawEvent->when);
2619 }
2620}
2621
2622void CursorInputMapper::sync(nsecs_t when) {
2623 int32_t lastButtonState = mButtonState;
2624 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2625 mButtonState = currentButtonState;
2626
2627 bool wasDown = isPointerDown(lastButtonState);
2628 bool down = isPointerDown(currentButtonState);
2629 bool downChanged;
2630 if (!wasDown && down) {
2631 mDownTime = when;
2632 downChanged = true;
2633 } else if (wasDown && !down) {
2634 downChanged = true;
2635 } else {
2636 downChanged = false;
2637 }
2638 nsecs_t downTime = mDownTime;
2639 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002640 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2641 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642
2643 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2644 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2645 bool moved = deltaX != 0 || deltaY != 0;
2646
2647 // Rotate delta according to orientation if needed.
2648 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2649 && (deltaX != 0.0f || deltaY != 0.0f)) {
2650 rotateDelta(mOrientation, &deltaX, &deltaY);
2651 }
2652
2653 // Move the pointer.
2654 PointerProperties pointerProperties;
2655 pointerProperties.clear();
2656 pointerProperties.id = 0;
2657 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2658
2659 PointerCoords pointerCoords;
2660 pointerCoords.clear();
2661
2662 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2663 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2664 bool scrolled = vscroll != 0 || hscroll != 0;
2665
2666 mWheelYVelocityControl.move(when, NULL, &vscroll);
2667 mWheelXVelocityControl.move(when, &hscroll, NULL);
2668
2669 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2670
2671 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002672 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 if (moved || scrolled || buttonsChanged) {
2674 mPointerController->setPresentation(
2675 PointerControllerInterface::PRESENTATION_POINTER);
2676
2677 if (moved) {
2678 mPointerController->move(deltaX, deltaY);
2679 }
2680
2681 if (buttonsChanged) {
2682 mPointerController->setButtonState(currentButtonState);
2683 }
2684
2685 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2686 }
2687
2688 float x, y;
2689 mPointerController->getPosition(&x, &y);
2690 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2691 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002692 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2693 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 displayId = ADISPLAY_ID_DEFAULT;
2695 } else {
2696 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2697 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2698 displayId = ADISPLAY_ID_NONE;
2699 }
2700
2701 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2702
2703 // Moving an external trackball or mouse should wake the device.
2704 // We don't do this for internal cursor devices to prevent them from waking up
2705 // the device in your pocket.
2706 // TODO: Use the input device configuration to control this behavior more finely.
2707 uint32_t policyFlags = 0;
2708 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002709 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 }
2711
2712 // Synthesize key down from buttons if needed.
2713 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2714 policyFlags, lastButtonState, currentButtonState);
2715
2716 // Send motion event.
2717 if (downChanged || moved || scrolled || buttonsChanged) {
2718 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002719 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 int32_t motionEventAction;
2721 if (downChanged) {
2722 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002723 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2725 } else {
2726 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2727 }
2728
Michael Wright7b159c92015-05-14 14:48:03 +01002729 if (buttonsReleased) {
2730 BitSet32 released(buttonsReleased);
2731 while (!released.isEmpty()) {
2732 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2733 buttonState &= ~actionButton;
2734 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2735 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2736 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2737 displayId, 1, &pointerProperties, &pointerCoords,
2738 mXPrecision, mYPrecision, downTime);
2739 getListener()->notifyMotion(&releaseArgs);
2740 }
2741 }
2742
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002744 motionEventAction, 0, 0, metaState, currentButtonState,
2745 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 displayId, 1, &pointerProperties, &pointerCoords,
2747 mXPrecision, mYPrecision, downTime);
2748 getListener()->notifyMotion(&args);
2749
Michael Wright7b159c92015-05-14 14:48:03 +01002750 if (buttonsPressed) {
2751 BitSet32 pressed(buttonsPressed);
2752 while (!pressed.isEmpty()) {
2753 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2754 buttonState |= actionButton;
2755 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2756 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2757 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2758 displayId, 1, &pointerProperties, &pointerCoords,
2759 mXPrecision, mYPrecision, downTime);
2760 getListener()->notifyMotion(&pressArgs);
2761 }
2762 }
2763
2764 ALOG_ASSERT(buttonState == currentButtonState);
2765
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 // Send hover move after UP to tell the application that the mouse is hovering now.
2767 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002768 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002770 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2772 displayId, 1, &pointerProperties, &pointerCoords,
2773 mXPrecision, mYPrecision, downTime);
2774 getListener()->notifyMotion(&hoverArgs);
2775 }
2776
2777 // Send scroll events.
2778 if (scrolled) {
2779 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2780 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2781
2782 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002783 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 AMOTION_EVENT_EDGE_FLAG_NONE,
2785 displayId, 1, &pointerProperties, &pointerCoords,
2786 mXPrecision, mYPrecision, downTime);
2787 getListener()->notifyMotion(&scrollArgs);
2788 }
2789 }
2790
2791 // Synthesize key up from buttons if needed.
2792 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2793 policyFlags, lastButtonState, currentButtonState);
2794
2795 mCursorMotionAccumulator.finishSync();
2796 mCursorScrollAccumulator.finishSync();
2797}
2798
2799int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2800 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2801 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2802 } else {
2803 return AKEY_STATE_UNKNOWN;
2804 }
2805}
2806
2807void CursorInputMapper::fadePointer() {
2808 if (mPointerController != NULL) {
2809 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2810 }
2811}
2812
Prashant Malani1941ff52015-08-11 18:29:28 -07002813// --- RotaryEncoderInputMapper ---
2814
2815RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2816 InputMapper(device) {
2817 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2818}
2819
2820RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2821}
2822
2823uint32_t RotaryEncoderInputMapper::getSources() {
2824 return mSource;
2825}
2826
2827void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2828 InputMapper::populateDeviceInfo(info);
2829
2830 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002831 float res = 0.0f;
2832 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2833 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2834 }
2835 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2836 mScalingFactor)) {
2837 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2838 "default to 1.0!\n");
2839 mScalingFactor = 1.0f;
2840 }
2841 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2842 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002843 }
2844}
2845
2846void RotaryEncoderInputMapper::dump(String8& dump) {
2847 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2848 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2849 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2850}
2851
2852void RotaryEncoderInputMapper::configure(nsecs_t when,
2853 const InputReaderConfiguration* config, uint32_t changes) {
2854 InputMapper::configure(when, config, changes);
2855 if (!changes) {
2856 mRotaryEncoderScrollAccumulator.configure(getDevice());
2857 }
2858}
2859
2860void RotaryEncoderInputMapper::reset(nsecs_t when) {
2861 mRotaryEncoderScrollAccumulator.reset(getDevice());
2862
2863 InputMapper::reset(when);
2864}
2865
2866void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2867 mRotaryEncoderScrollAccumulator.process(rawEvent);
2868
2869 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2870 sync(rawEvent->when);
2871 }
2872}
2873
2874void RotaryEncoderInputMapper::sync(nsecs_t when) {
2875 PointerCoords pointerCoords;
2876 pointerCoords.clear();
2877
2878 PointerProperties pointerProperties;
2879 pointerProperties.clear();
2880 pointerProperties.id = 0;
2881 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2882
2883 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2884 bool scrolled = scroll != 0;
2885
2886 // This is not a pointer, so it's not associated with a display.
2887 int32_t displayId = ADISPLAY_ID_NONE;
2888
2889 // Moving the rotary encoder should wake the device (if specified).
2890 uint32_t policyFlags = 0;
2891 if (scrolled && getDevice()->isExternal()) {
2892 policyFlags |= POLICY_FLAG_WAKE;
2893 }
2894
2895 // Send motion event.
2896 if (scrolled) {
2897 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002898 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002899
2900 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2901 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2902 AMOTION_EVENT_EDGE_FLAG_NONE,
2903 displayId, 1, &pointerProperties, &pointerCoords,
2904 0, 0, 0);
2905 getListener()->notifyMotion(&scrollArgs);
2906 }
2907
2908 mRotaryEncoderScrollAccumulator.finishSync();
2909}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910
2911// --- TouchInputMapper ---
2912
2913TouchInputMapper::TouchInputMapper(InputDevice* device) :
2914 InputMapper(device),
2915 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2916 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2917 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2918}
2919
2920TouchInputMapper::~TouchInputMapper() {
2921}
2922
2923uint32_t TouchInputMapper::getSources() {
2924 return mSource;
2925}
2926
2927void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2928 InputMapper::populateDeviceInfo(info);
2929
2930 if (mDeviceMode != DEVICE_MODE_DISABLED) {
2931 info->addMotionRange(mOrientedRanges.x);
2932 info->addMotionRange(mOrientedRanges.y);
2933 info->addMotionRange(mOrientedRanges.pressure);
2934
2935 if (mOrientedRanges.haveSize) {
2936 info->addMotionRange(mOrientedRanges.size);
2937 }
2938
2939 if (mOrientedRanges.haveTouchSize) {
2940 info->addMotionRange(mOrientedRanges.touchMajor);
2941 info->addMotionRange(mOrientedRanges.touchMinor);
2942 }
2943
2944 if (mOrientedRanges.haveToolSize) {
2945 info->addMotionRange(mOrientedRanges.toolMajor);
2946 info->addMotionRange(mOrientedRanges.toolMinor);
2947 }
2948
2949 if (mOrientedRanges.haveOrientation) {
2950 info->addMotionRange(mOrientedRanges.orientation);
2951 }
2952
2953 if (mOrientedRanges.haveDistance) {
2954 info->addMotionRange(mOrientedRanges.distance);
2955 }
2956
2957 if (mOrientedRanges.haveTilt) {
2958 info->addMotionRange(mOrientedRanges.tilt);
2959 }
2960
2961 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2962 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2963 0.0f);
2964 }
2965 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2966 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2967 0.0f);
2968 }
2969 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2970 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2971 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2972 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2973 x.fuzz, x.resolution);
2974 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2975 y.fuzz, y.resolution);
2976 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2977 x.fuzz, x.resolution);
2978 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2979 y.fuzz, y.resolution);
2980 }
2981 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2982 }
2983}
2984
2985void TouchInputMapper::dump(String8& dump) {
2986 dump.append(INDENT2 "Touch Input Mapper:\n");
2987 dumpParameters(dump);
2988 dumpVirtualKeys(dump);
2989 dumpRawPointerAxes(dump);
2990 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07002991 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002992 dumpSurface(dump);
2993
2994 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2995 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2996 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2997 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2998 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2999 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3000 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3001 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3002 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3003 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3004 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3005 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3006 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3007 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3008 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3009 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3010 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3011
Michael Wright7b159c92015-05-14 14:48:03 +01003012 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003014 mLastRawState.rawPointerData.pointerCount);
3015 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3016 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3018 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3019 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3020 "toolType=%d, isHovering=%s\n", i,
3021 pointer.id, pointer.x, pointer.y, pointer.pressure,
3022 pointer.touchMajor, pointer.touchMinor,
3023 pointer.toolMajor, pointer.toolMinor,
3024 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3025 pointer.toolType, toString(pointer.isHovering));
3026 }
3027
Michael Wright7b159c92015-05-14 14:48:03 +01003028 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003030 mLastCookedState.cookedPointerData.pointerCount);
3031 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3032 const PointerProperties& pointerProperties =
3033 mLastCookedState.cookedPointerData.pointerProperties[i];
3034 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3036 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3037 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3038 "toolType=%d, isHovering=%s\n", i,
3039 pointerProperties.id,
3040 pointerCoords.getX(),
3041 pointerCoords.getY(),
3042 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3043 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3044 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3045 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3046 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3047 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3048 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3049 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3050 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003051 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
3053
Michael Wright842500e2015-03-13 17:32:02 -07003054 dump.append(INDENT3 "Stylus Fusion:\n");
3055 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3056 toString(mExternalStylusConnected));
3057 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3058 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003059 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003060 dump.append(INDENT3 "External Stylus State:\n");
3061 dumpStylusState(dump, mExternalStylusState);
3062
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 if (mDeviceMode == DEVICE_MODE_POINTER) {
3064 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3065 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3066 mPointerXMovementScale);
3067 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3068 mPointerYMovementScale);
3069 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3070 mPointerXZoomScale);
3071 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3072 mPointerYZoomScale);
3073 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3074 mPointerGestureMaxSwipeWidth);
3075 }
3076}
3077
3078void TouchInputMapper::configure(nsecs_t when,
3079 const InputReaderConfiguration* config, uint32_t changes) {
3080 InputMapper::configure(when, config, changes);
3081
3082 mConfig = *config;
3083
3084 if (!changes) { // first time only
3085 // Configure basic parameters.
3086 configureParameters();
3087
3088 // Configure common accumulators.
3089 mCursorScrollAccumulator.configure(getDevice());
3090 mTouchButtonAccumulator.configure(getDevice());
3091
3092 // Configure absolute axis information.
3093 configureRawPointerAxes();
3094
3095 // Prepare input device calibration.
3096 parseCalibration();
3097 resolveCalibration();
3098 }
3099
Michael Wright842500e2015-03-13 17:32:02 -07003100 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003101 // Update location calibration to reflect current settings
3102 updateAffineTransformation();
3103 }
3104
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3106 // Update pointer speed.
3107 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3108 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3109 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3110 }
3111
3112 bool resetNeeded = false;
3113 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3114 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003115 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3116 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 // Configure device sources, surface dimensions, orientation and
3118 // scaling factors.
3119 configureSurface(when, &resetNeeded);
3120 }
3121
3122 if (changes && resetNeeded) {
3123 // Send reset, unless this is the first time the device has been configured,
3124 // in which case the reader will call reset itself after all mappers are ready.
3125 getDevice()->notifyReset(when);
3126 }
3127}
3128
Michael Wright842500e2015-03-13 17:32:02 -07003129void TouchInputMapper::resolveExternalStylusPresence() {
3130 Vector<InputDeviceInfo> devices;
3131 mContext->getExternalStylusDevices(devices);
3132 mExternalStylusConnected = !devices.isEmpty();
3133
3134 if (!mExternalStylusConnected) {
3135 resetExternalStylus();
3136 }
3137}
3138
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139void TouchInputMapper::configureParameters() {
3140 // Use the pointer presentation mode for devices that do not support distinct
3141 // multitouch. The spot-based presentation relies on being able to accurately
3142 // locate two or more fingers on the touch pad.
3143 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003144 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145
3146 String8 gestureModeString;
3147 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3148 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003149 if (gestureModeString == "single-touch") {
3150 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3151 } else if (gestureModeString == "multi-touch") {
3152 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 } else if (gestureModeString != "default") {
3154 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3155 }
3156 }
3157
3158 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3159 // The device is a touch screen.
3160 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3161 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3162 // The device is a pointing device like a track pad.
3163 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3164 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3165 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3166 // The device is a cursor device with a touch pad attached.
3167 // By default don't use the touch pad to move the pointer.
3168 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3169 } else {
3170 // The device is a touch pad of unknown purpose.
3171 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3172 }
3173
3174 mParameters.hasButtonUnderPad=
3175 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3176
3177 String8 deviceTypeString;
3178 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3179 deviceTypeString)) {
3180 if (deviceTypeString == "touchScreen") {
3181 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3182 } else if (deviceTypeString == "touchPad") {
3183 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3184 } else if (deviceTypeString == "touchNavigation") {
3185 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3186 } else if (deviceTypeString == "pointer") {
3187 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3188 } else if (deviceTypeString != "default") {
3189 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3190 }
3191 }
3192
3193 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3194 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3195 mParameters.orientationAware);
3196
3197 mParameters.hasAssociatedDisplay = false;
3198 mParameters.associatedDisplayIsExternal = false;
3199 if (mParameters.orientationAware
3200 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3201 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3202 mParameters.hasAssociatedDisplay = true;
3203 mParameters.associatedDisplayIsExternal =
3204 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3205 && getDevice()->isExternal();
3206 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003207
3208 // Initial downs on external touch devices should wake the device.
3209 // Normally we don't do this for internal touch screens to prevent them from waking
3210 // up in your pocket but you can enable it using the input device configuration.
3211 mParameters.wake = getDevice()->isExternal();
3212 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3213 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214}
3215
3216void TouchInputMapper::dumpParameters(String8& dump) {
3217 dump.append(INDENT3 "Parameters:\n");
3218
3219 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003220 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3221 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003223 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3224 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 break;
3226 default:
3227 assert(false);
3228 }
3229
3230 switch (mParameters.deviceType) {
3231 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3232 dump.append(INDENT4 "DeviceType: touchScreen\n");
3233 break;
3234 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3235 dump.append(INDENT4 "DeviceType: touchPad\n");
3236 break;
3237 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3238 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3239 break;
3240 case Parameters::DEVICE_TYPE_POINTER:
3241 dump.append(INDENT4 "DeviceType: pointer\n");
3242 break;
3243 default:
3244 ALOG_ASSERT(false);
3245 }
3246
3247 dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
3248 toString(mParameters.hasAssociatedDisplay),
3249 toString(mParameters.associatedDisplayIsExternal));
3250 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3251 toString(mParameters.orientationAware));
3252}
3253
3254void TouchInputMapper::configureRawPointerAxes() {
3255 mRawPointerAxes.clear();
3256}
3257
3258void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3259 dump.append(INDENT3 "Raw Touch Axes:\n");
3260 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3261 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3262 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3263 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3264 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3265 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3266 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3267 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3268 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3269 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3270 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3271 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3272 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3273}
3274
Michael Wright842500e2015-03-13 17:32:02 -07003275bool TouchInputMapper::hasExternalStylus() const {
3276 return mExternalStylusConnected;
3277}
3278
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3280 int32_t oldDeviceMode = mDeviceMode;
3281
Michael Wright842500e2015-03-13 17:32:02 -07003282 resolveExternalStylusPresence();
3283
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 // Determine device mode.
3285 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3286 && mConfig.pointerGesturesEnabled) {
3287 mSource = AINPUT_SOURCE_MOUSE;
3288 mDeviceMode = DEVICE_MODE_POINTER;
3289 if (hasStylus()) {
3290 mSource |= AINPUT_SOURCE_STYLUS;
3291 }
3292 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3293 && mParameters.hasAssociatedDisplay) {
3294 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3295 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003296 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 mSource |= AINPUT_SOURCE_STYLUS;
3298 }
Michael Wright2f78b682015-06-12 15:25:08 +01003299 if (hasExternalStylus()) {
3300 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3303 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3304 mDeviceMode = DEVICE_MODE_NAVIGATION;
3305 } else {
3306 mSource = AINPUT_SOURCE_TOUCHPAD;
3307 mDeviceMode = DEVICE_MODE_UNSCALED;
3308 }
3309
3310 // Ensure we have valid X and Y axes.
3311 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3312 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3313 "The device will be inoperable.", getDeviceName().string());
3314 mDeviceMode = DEVICE_MODE_DISABLED;
3315 return;
3316 }
3317
3318 // Raw width and height in the natural orientation.
3319 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3320 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3321
3322 // Get associated display dimensions.
3323 DisplayViewport newViewport;
3324 if (mParameters.hasAssociatedDisplay) {
3325 if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
3326 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3327 "display. The device will be inoperable until the display size "
3328 "becomes available.",
3329 getDeviceName().string());
3330 mDeviceMode = DEVICE_MODE_DISABLED;
3331 return;
3332 }
3333 } else {
3334 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3335 }
3336 bool viewportChanged = mViewport != newViewport;
3337 if (viewportChanged) {
3338 mViewport = newViewport;
3339
3340 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3341 // Convert rotated viewport to natural surface coordinates.
3342 int32_t naturalLogicalWidth, naturalLogicalHeight;
3343 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3344 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3345 int32_t naturalDeviceWidth, naturalDeviceHeight;
3346 switch (mViewport.orientation) {
3347 case DISPLAY_ORIENTATION_90:
3348 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3349 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3350 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3351 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3352 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3353 naturalPhysicalTop = mViewport.physicalLeft;
3354 naturalDeviceWidth = mViewport.deviceHeight;
3355 naturalDeviceHeight = mViewport.deviceWidth;
3356 break;
3357 case DISPLAY_ORIENTATION_180:
3358 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3359 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3360 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3361 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3362 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3363 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3364 naturalDeviceWidth = mViewport.deviceWidth;
3365 naturalDeviceHeight = mViewport.deviceHeight;
3366 break;
3367 case DISPLAY_ORIENTATION_270:
3368 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3369 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3370 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3371 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3372 naturalPhysicalLeft = mViewport.physicalTop;
3373 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3374 naturalDeviceWidth = mViewport.deviceHeight;
3375 naturalDeviceHeight = mViewport.deviceWidth;
3376 break;
3377 case DISPLAY_ORIENTATION_0:
3378 default:
3379 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3380 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3381 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3382 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3383 naturalPhysicalLeft = mViewport.physicalLeft;
3384 naturalPhysicalTop = mViewport.physicalTop;
3385 naturalDeviceWidth = mViewport.deviceWidth;
3386 naturalDeviceHeight = mViewport.deviceHeight;
3387 break;
3388 }
3389
3390 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3391 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3392 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3393 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3394
3395 mSurfaceOrientation = mParameters.orientationAware ?
3396 mViewport.orientation : DISPLAY_ORIENTATION_0;
3397 } else {
3398 mSurfaceWidth = rawWidth;
3399 mSurfaceHeight = rawHeight;
3400 mSurfaceLeft = 0;
3401 mSurfaceTop = 0;
3402 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3403 }
3404 }
3405
3406 // If moving between pointer modes, need to reset some state.
3407 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3408 if (deviceModeChanged) {
3409 mOrientedRanges.clear();
3410 }
3411
3412 // Create pointer controller if needed.
3413 if (mDeviceMode == DEVICE_MODE_POINTER ||
3414 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3415 if (mPointerController == NULL) {
3416 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3417 }
3418 } else {
3419 mPointerController.clear();
3420 }
3421
3422 if (viewportChanged || deviceModeChanged) {
3423 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3424 "display id %d",
3425 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3426 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3427
3428 // Configure X and Y factors.
3429 mXScale = float(mSurfaceWidth) / rawWidth;
3430 mYScale = float(mSurfaceHeight) / rawHeight;
3431 mXTranslate = -mSurfaceLeft;
3432 mYTranslate = -mSurfaceTop;
3433 mXPrecision = 1.0f / mXScale;
3434 mYPrecision = 1.0f / mYScale;
3435
3436 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3437 mOrientedRanges.x.source = mSource;
3438 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3439 mOrientedRanges.y.source = mSource;
3440
3441 configureVirtualKeys();
3442
3443 // Scale factor for terms that are not oriented in a particular axis.
3444 // If the pixels are square then xScale == yScale otherwise we fake it
3445 // by choosing an average.
3446 mGeometricScale = avg(mXScale, mYScale);
3447
3448 // Size of diagonal axis.
3449 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3450
3451 // Size factors.
3452 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3453 if (mRawPointerAxes.touchMajor.valid
3454 && mRawPointerAxes.touchMajor.maxValue != 0) {
3455 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3456 } else if (mRawPointerAxes.toolMajor.valid
3457 && mRawPointerAxes.toolMajor.maxValue != 0) {
3458 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3459 } else {
3460 mSizeScale = 0.0f;
3461 }
3462
3463 mOrientedRanges.haveTouchSize = true;
3464 mOrientedRanges.haveToolSize = true;
3465 mOrientedRanges.haveSize = true;
3466
3467 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3468 mOrientedRanges.touchMajor.source = mSource;
3469 mOrientedRanges.touchMajor.min = 0;
3470 mOrientedRanges.touchMajor.max = diagonalSize;
3471 mOrientedRanges.touchMajor.flat = 0;
3472 mOrientedRanges.touchMajor.fuzz = 0;
3473 mOrientedRanges.touchMajor.resolution = 0;
3474
3475 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3476 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3477
3478 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3479 mOrientedRanges.toolMajor.source = mSource;
3480 mOrientedRanges.toolMajor.min = 0;
3481 mOrientedRanges.toolMajor.max = diagonalSize;
3482 mOrientedRanges.toolMajor.flat = 0;
3483 mOrientedRanges.toolMajor.fuzz = 0;
3484 mOrientedRanges.toolMajor.resolution = 0;
3485
3486 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3487 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3488
3489 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3490 mOrientedRanges.size.source = mSource;
3491 mOrientedRanges.size.min = 0;
3492 mOrientedRanges.size.max = 1.0;
3493 mOrientedRanges.size.flat = 0;
3494 mOrientedRanges.size.fuzz = 0;
3495 mOrientedRanges.size.resolution = 0;
3496 } else {
3497 mSizeScale = 0.0f;
3498 }
3499
3500 // Pressure factors.
3501 mPressureScale = 0;
3502 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3503 || mCalibration.pressureCalibration
3504 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3505 if (mCalibration.havePressureScale) {
3506 mPressureScale = mCalibration.pressureScale;
3507 } else if (mRawPointerAxes.pressure.valid
3508 && mRawPointerAxes.pressure.maxValue != 0) {
3509 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3510 }
3511 }
3512
3513 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3514 mOrientedRanges.pressure.source = mSource;
3515 mOrientedRanges.pressure.min = 0;
3516 mOrientedRanges.pressure.max = 1.0;
3517 mOrientedRanges.pressure.flat = 0;
3518 mOrientedRanges.pressure.fuzz = 0;
3519 mOrientedRanges.pressure.resolution = 0;
3520
3521 // Tilt
3522 mTiltXCenter = 0;
3523 mTiltXScale = 0;
3524 mTiltYCenter = 0;
3525 mTiltYScale = 0;
3526 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3527 if (mHaveTilt) {
3528 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3529 mRawPointerAxes.tiltX.maxValue);
3530 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3531 mRawPointerAxes.tiltY.maxValue);
3532 mTiltXScale = M_PI / 180;
3533 mTiltYScale = M_PI / 180;
3534
3535 mOrientedRanges.haveTilt = true;
3536
3537 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3538 mOrientedRanges.tilt.source = mSource;
3539 mOrientedRanges.tilt.min = 0;
3540 mOrientedRanges.tilt.max = M_PI_2;
3541 mOrientedRanges.tilt.flat = 0;
3542 mOrientedRanges.tilt.fuzz = 0;
3543 mOrientedRanges.tilt.resolution = 0;
3544 }
3545
3546 // Orientation
3547 mOrientationScale = 0;
3548 if (mHaveTilt) {
3549 mOrientedRanges.haveOrientation = true;
3550
3551 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3552 mOrientedRanges.orientation.source = mSource;
3553 mOrientedRanges.orientation.min = -M_PI;
3554 mOrientedRanges.orientation.max = M_PI;
3555 mOrientedRanges.orientation.flat = 0;
3556 mOrientedRanges.orientation.fuzz = 0;
3557 mOrientedRanges.orientation.resolution = 0;
3558 } else if (mCalibration.orientationCalibration !=
3559 Calibration::ORIENTATION_CALIBRATION_NONE) {
3560 if (mCalibration.orientationCalibration
3561 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3562 if (mRawPointerAxes.orientation.valid) {
3563 if (mRawPointerAxes.orientation.maxValue > 0) {
3564 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3565 } else if (mRawPointerAxes.orientation.minValue < 0) {
3566 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3567 } else {
3568 mOrientationScale = 0;
3569 }
3570 }
3571 }
3572
3573 mOrientedRanges.haveOrientation = true;
3574
3575 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3576 mOrientedRanges.orientation.source = mSource;
3577 mOrientedRanges.orientation.min = -M_PI_2;
3578 mOrientedRanges.orientation.max = M_PI_2;
3579 mOrientedRanges.orientation.flat = 0;
3580 mOrientedRanges.orientation.fuzz = 0;
3581 mOrientedRanges.orientation.resolution = 0;
3582 }
3583
3584 // Distance
3585 mDistanceScale = 0;
3586 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3587 if (mCalibration.distanceCalibration
3588 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3589 if (mCalibration.haveDistanceScale) {
3590 mDistanceScale = mCalibration.distanceScale;
3591 } else {
3592 mDistanceScale = 1.0f;
3593 }
3594 }
3595
3596 mOrientedRanges.haveDistance = true;
3597
3598 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3599 mOrientedRanges.distance.source = mSource;
3600 mOrientedRanges.distance.min =
3601 mRawPointerAxes.distance.minValue * mDistanceScale;
3602 mOrientedRanges.distance.max =
3603 mRawPointerAxes.distance.maxValue * mDistanceScale;
3604 mOrientedRanges.distance.flat = 0;
3605 mOrientedRanges.distance.fuzz =
3606 mRawPointerAxes.distance.fuzz * mDistanceScale;
3607 mOrientedRanges.distance.resolution = 0;
3608 }
3609
3610 // Compute oriented precision, scales and ranges.
3611 // Note that the maximum value reported is an inclusive maximum value so it is one
3612 // unit less than the total width or height of surface.
3613 switch (mSurfaceOrientation) {
3614 case DISPLAY_ORIENTATION_90:
3615 case DISPLAY_ORIENTATION_270:
3616 mOrientedXPrecision = mYPrecision;
3617 mOrientedYPrecision = mXPrecision;
3618
3619 mOrientedRanges.x.min = mYTranslate;
3620 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3621 mOrientedRanges.x.flat = 0;
3622 mOrientedRanges.x.fuzz = 0;
3623 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3624
3625 mOrientedRanges.y.min = mXTranslate;
3626 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3627 mOrientedRanges.y.flat = 0;
3628 mOrientedRanges.y.fuzz = 0;
3629 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3630 break;
3631
3632 default:
3633 mOrientedXPrecision = mXPrecision;
3634 mOrientedYPrecision = mYPrecision;
3635
3636 mOrientedRanges.x.min = mXTranslate;
3637 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3638 mOrientedRanges.x.flat = 0;
3639 mOrientedRanges.x.fuzz = 0;
3640 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3641
3642 mOrientedRanges.y.min = mYTranslate;
3643 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3644 mOrientedRanges.y.flat = 0;
3645 mOrientedRanges.y.fuzz = 0;
3646 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3647 break;
3648 }
3649
Jason Gerecke71b16e82014-03-10 09:47:59 -07003650 // Location
3651 updateAffineTransformation();
3652
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 if (mDeviceMode == DEVICE_MODE_POINTER) {
3654 // Compute pointer gesture detection parameters.
3655 float rawDiagonal = hypotf(rawWidth, rawHeight);
3656 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3657
3658 // Scale movements such that one whole swipe of the touch pad covers a
3659 // given area relative to the diagonal size of the display when no acceleration
3660 // is applied.
3661 // Assume that the touch pad has a square aspect ratio such that movements in
3662 // X and Y of the same number of raw units cover the same physical distance.
3663 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3664 * displayDiagonal / rawDiagonal;
3665 mPointerYMovementScale = mPointerXMovementScale;
3666
3667 // Scale zooms to cover a smaller range of the display than movements do.
3668 // This value determines the area around the pointer that is affected by freeform
3669 // pointer gestures.
3670 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3671 * displayDiagonal / rawDiagonal;
3672 mPointerYZoomScale = mPointerXZoomScale;
3673
3674 // Max width between pointers to detect a swipe gesture is more than some fraction
3675 // of the diagonal axis of the touch pad. Touches that are wider than this are
3676 // translated into freeform gestures.
3677 mPointerGestureMaxSwipeWidth =
3678 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3679
3680 // Abort current pointer usages because the state has changed.
3681 abortPointerUsage(when, 0 /*policyFlags*/);
3682 }
3683
3684 // Inform the dispatcher about the changes.
3685 *outResetNeeded = true;
3686 bumpGeneration();
3687 }
3688}
3689
3690void TouchInputMapper::dumpSurface(String8& dump) {
3691 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3692 "logicalFrame=[%d, %d, %d, %d], "
3693 "physicalFrame=[%d, %d, %d, %d], "
3694 "deviceSize=[%d, %d]\n",
3695 mViewport.displayId, mViewport.orientation,
3696 mViewport.logicalLeft, mViewport.logicalTop,
3697 mViewport.logicalRight, mViewport.logicalBottom,
3698 mViewport.physicalLeft, mViewport.physicalTop,
3699 mViewport.physicalRight, mViewport.physicalBottom,
3700 mViewport.deviceWidth, mViewport.deviceHeight);
3701
3702 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3703 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3704 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3705 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3706 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3707}
3708
3709void TouchInputMapper::configureVirtualKeys() {
3710 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3711 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3712
3713 mVirtualKeys.clear();
3714
3715 if (virtualKeyDefinitions.size() == 0) {
3716 return;
3717 }
3718
3719 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3720
3721 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3722 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3723 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3724 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3725
3726 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3727 const VirtualKeyDefinition& virtualKeyDefinition =
3728 virtualKeyDefinitions[i];
3729
3730 mVirtualKeys.add();
3731 VirtualKey& virtualKey = mVirtualKeys.editTop();
3732
3733 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3734 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003735 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003737 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3738 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3740 virtualKey.scanCode);
3741 mVirtualKeys.pop(); // drop the key
3742 continue;
3743 }
3744
3745 virtualKey.keyCode = keyCode;
3746 virtualKey.flags = flags;
3747
3748 // convert the key definition's display coordinates into touch coordinates for a hit box
3749 int32_t halfWidth = virtualKeyDefinition.width / 2;
3750 int32_t halfHeight = virtualKeyDefinition.height / 2;
3751
3752 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3753 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3754 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3755 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3756 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3757 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3758 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3759 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3760 }
3761}
3762
3763void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3764 if (!mVirtualKeys.isEmpty()) {
3765 dump.append(INDENT3 "Virtual Keys:\n");
3766
3767 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3768 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003769 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3771 i, virtualKey.scanCode, virtualKey.keyCode,
3772 virtualKey.hitLeft, virtualKey.hitRight,
3773 virtualKey.hitTop, virtualKey.hitBottom);
3774 }
3775 }
3776}
3777
3778void TouchInputMapper::parseCalibration() {
3779 const PropertyMap& in = getDevice()->getConfiguration();
3780 Calibration& out = mCalibration;
3781
3782 // Size
3783 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3784 String8 sizeCalibrationString;
3785 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3786 if (sizeCalibrationString == "none") {
3787 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3788 } else if (sizeCalibrationString == "geometric") {
3789 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3790 } else if (sizeCalibrationString == "diameter") {
3791 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3792 } else if (sizeCalibrationString == "box") {
3793 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3794 } else if (sizeCalibrationString == "area") {
3795 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3796 } else if (sizeCalibrationString != "default") {
3797 ALOGW("Invalid value for touch.size.calibration: '%s'",
3798 sizeCalibrationString.string());
3799 }
3800 }
3801
3802 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3803 out.sizeScale);
3804 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3805 out.sizeBias);
3806 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3807 out.sizeIsSummed);
3808
3809 // Pressure
3810 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3811 String8 pressureCalibrationString;
3812 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3813 if (pressureCalibrationString == "none") {
3814 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3815 } else if (pressureCalibrationString == "physical") {
3816 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3817 } else if (pressureCalibrationString == "amplitude") {
3818 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3819 } else if (pressureCalibrationString != "default") {
3820 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3821 pressureCalibrationString.string());
3822 }
3823 }
3824
3825 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3826 out.pressureScale);
3827
3828 // Orientation
3829 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3830 String8 orientationCalibrationString;
3831 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3832 if (orientationCalibrationString == "none") {
3833 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3834 } else if (orientationCalibrationString == "interpolated") {
3835 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3836 } else if (orientationCalibrationString == "vector") {
3837 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3838 } else if (orientationCalibrationString != "default") {
3839 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3840 orientationCalibrationString.string());
3841 }
3842 }
3843
3844 // Distance
3845 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3846 String8 distanceCalibrationString;
3847 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3848 if (distanceCalibrationString == "none") {
3849 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3850 } else if (distanceCalibrationString == "scaled") {
3851 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3852 } else if (distanceCalibrationString != "default") {
3853 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3854 distanceCalibrationString.string());
3855 }
3856 }
3857
3858 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3859 out.distanceScale);
3860
3861 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3862 String8 coverageCalibrationString;
3863 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3864 if (coverageCalibrationString == "none") {
3865 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3866 } else if (coverageCalibrationString == "box") {
3867 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3868 } else if (coverageCalibrationString != "default") {
3869 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3870 coverageCalibrationString.string());
3871 }
3872 }
3873}
3874
3875void TouchInputMapper::resolveCalibration() {
3876 // Size
3877 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3878 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3879 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3880 }
3881 } else {
3882 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3883 }
3884
3885 // Pressure
3886 if (mRawPointerAxes.pressure.valid) {
3887 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3888 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3889 }
3890 } else {
3891 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3892 }
3893
3894 // Orientation
3895 if (mRawPointerAxes.orientation.valid) {
3896 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3897 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3898 }
3899 } else {
3900 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3901 }
3902
3903 // Distance
3904 if (mRawPointerAxes.distance.valid) {
3905 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3906 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3907 }
3908 } else {
3909 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3910 }
3911
3912 // Coverage
3913 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3914 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3915 }
3916}
3917
3918void TouchInputMapper::dumpCalibration(String8& dump) {
3919 dump.append(INDENT3 "Calibration:\n");
3920
3921 // Size
3922 switch (mCalibration.sizeCalibration) {
3923 case Calibration::SIZE_CALIBRATION_NONE:
3924 dump.append(INDENT4 "touch.size.calibration: none\n");
3925 break;
3926 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3927 dump.append(INDENT4 "touch.size.calibration: geometric\n");
3928 break;
3929 case Calibration::SIZE_CALIBRATION_DIAMETER:
3930 dump.append(INDENT4 "touch.size.calibration: diameter\n");
3931 break;
3932 case Calibration::SIZE_CALIBRATION_BOX:
3933 dump.append(INDENT4 "touch.size.calibration: box\n");
3934 break;
3935 case Calibration::SIZE_CALIBRATION_AREA:
3936 dump.append(INDENT4 "touch.size.calibration: area\n");
3937 break;
3938 default:
3939 ALOG_ASSERT(false);
3940 }
3941
3942 if (mCalibration.haveSizeScale) {
3943 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3944 mCalibration.sizeScale);
3945 }
3946
3947 if (mCalibration.haveSizeBias) {
3948 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3949 mCalibration.sizeBias);
3950 }
3951
3952 if (mCalibration.haveSizeIsSummed) {
3953 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3954 toString(mCalibration.sizeIsSummed));
3955 }
3956
3957 // Pressure
3958 switch (mCalibration.pressureCalibration) {
3959 case Calibration::PRESSURE_CALIBRATION_NONE:
3960 dump.append(INDENT4 "touch.pressure.calibration: none\n");
3961 break;
3962 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3963 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3964 break;
3965 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3966 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3967 break;
3968 default:
3969 ALOG_ASSERT(false);
3970 }
3971
3972 if (mCalibration.havePressureScale) {
3973 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3974 mCalibration.pressureScale);
3975 }
3976
3977 // Orientation
3978 switch (mCalibration.orientationCalibration) {
3979 case Calibration::ORIENTATION_CALIBRATION_NONE:
3980 dump.append(INDENT4 "touch.orientation.calibration: none\n");
3981 break;
3982 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3983 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3984 break;
3985 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3986 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3987 break;
3988 default:
3989 ALOG_ASSERT(false);
3990 }
3991
3992 // Distance
3993 switch (mCalibration.distanceCalibration) {
3994 case Calibration::DISTANCE_CALIBRATION_NONE:
3995 dump.append(INDENT4 "touch.distance.calibration: none\n");
3996 break;
3997 case Calibration::DISTANCE_CALIBRATION_SCALED:
3998 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3999 break;
4000 default:
4001 ALOG_ASSERT(false);
4002 }
4003
4004 if (mCalibration.haveDistanceScale) {
4005 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4006 mCalibration.distanceScale);
4007 }
4008
4009 switch (mCalibration.coverageCalibration) {
4010 case Calibration::COVERAGE_CALIBRATION_NONE:
4011 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4012 break;
4013 case Calibration::COVERAGE_CALIBRATION_BOX:
4014 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4015 break;
4016 default:
4017 ALOG_ASSERT(false);
4018 }
4019}
4020
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004021void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4022 dump.append(INDENT3 "Affine Transformation:\n");
4023
4024 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4025 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4026 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4027 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4028 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4029 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4030}
4031
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004032void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004033 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4034 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004035}
4036
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037void TouchInputMapper::reset(nsecs_t when) {
4038 mCursorButtonAccumulator.reset(getDevice());
4039 mCursorScrollAccumulator.reset(getDevice());
4040 mTouchButtonAccumulator.reset(getDevice());
4041
4042 mPointerVelocityControl.reset();
4043 mWheelXVelocityControl.reset();
4044 mWheelYVelocityControl.reset();
4045
Michael Wright842500e2015-03-13 17:32:02 -07004046 mRawStatesPending.clear();
4047 mCurrentRawState.clear();
4048 mCurrentCookedState.clear();
4049 mLastRawState.clear();
4050 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 mPointerUsage = POINTER_USAGE_NONE;
4052 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004053 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004054 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 mDownTime = 0;
4056
4057 mCurrentVirtualKey.down = false;
4058
4059 mPointerGesture.reset();
4060 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004061 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062
4063 if (mPointerController != NULL) {
4064 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4065 mPointerController->clearSpots();
4066 }
4067
4068 InputMapper::reset(when);
4069}
4070
Michael Wright842500e2015-03-13 17:32:02 -07004071void TouchInputMapper::resetExternalStylus() {
4072 mExternalStylusState.clear();
4073 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004074 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004075 mExternalStylusDataPending = false;
4076}
4077
Michael Wright43fd19f2015-04-21 19:02:58 +01004078void TouchInputMapper::clearStylusDataPendingFlags() {
4079 mExternalStylusDataPending = false;
4080 mExternalStylusFusionTimeout = LLONG_MAX;
4081}
4082
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083void TouchInputMapper::process(const RawEvent* rawEvent) {
4084 mCursorButtonAccumulator.process(rawEvent);
4085 mCursorScrollAccumulator.process(rawEvent);
4086 mTouchButtonAccumulator.process(rawEvent);
4087
4088 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4089 sync(rawEvent->when);
4090 }
4091}
4092
4093void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004094 const RawState* last = mRawStatesPending.isEmpty() ?
4095 &mCurrentRawState : &mRawStatesPending.top();
4096
4097 // Push a new state.
4098 mRawStatesPending.push();
4099 RawState* next = &mRawStatesPending.editTop();
4100 next->clear();
4101 next->when = when;
4102
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004104 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 | mCursorButtonAccumulator.getButtonState();
4106
Michael Wright842500e2015-03-13 17:32:02 -07004107 // Sync scroll
4108 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4109 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 mCursorScrollAccumulator.finishSync();
4111
Michael Wright842500e2015-03-13 17:32:02 -07004112 // Sync touch
4113 syncTouch(when, next);
4114
4115 // Assign pointer ids.
4116 if (!mHavePointerIds) {
4117 assignPointerIds(last, next);
4118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119
4120#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004121 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4122 "hovering ids 0x%08x -> 0x%08x",
4123 last->rawPointerData.pointerCount,
4124 next->rawPointerData.pointerCount,
4125 last->rawPointerData.touchingIdBits.value,
4126 next->rawPointerData.touchingIdBits.value,
4127 last->rawPointerData.hoveringIdBits.value,
4128 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129#endif
4130
Michael Wright842500e2015-03-13 17:32:02 -07004131 processRawTouches(false /*timeout*/);
4132}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
Michael Wright842500e2015-03-13 17:32:02 -07004134void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4136 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004137 mCurrentRawState.clear();
4138 mRawStatesPending.clear();
4139 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 }
4141
Michael Wright842500e2015-03-13 17:32:02 -07004142 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4143 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4144 // touching the current state will only observe the events that have been dispatched to the
4145 // rest of the pipeline.
4146 const size_t N = mRawStatesPending.size();
4147 size_t count;
4148 for(count = 0; count < N; count++) {
4149 const RawState& next = mRawStatesPending[count];
4150
4151 // A failure to assign the stylus id means that we're waiting on stylus data
4152 // and so should defer the rest of the pipeline.
4153 if (assignExternalStylusId(next, timeout)) {
4154 break;
4155 }
4156
4157 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004158 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004159 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004160 if (mCurrentRawState.when < mLastRawState.when) {
4161 mCurrentRawState.when = mLastRawState.when;
4162 }
Michael Wright842500e2015-03-13 17:32:02 -07004163 cookAndDispatch(mCurrentRawState.when);
4164 }
4165 if (count != 0) {
4166 mRawStatesPending.removeItemsAt(0, count);
4167 }
4168
Michael Wright842500e2015-03-13 17:32:02 -07004169 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004170 if (timeout) {
4171 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4172 clearStylusDataPendingFlags();
4173 mCurrentRawState.copyFrom(mLastRawState);
4174#if DEBUG_STYLUS_FUSION
4175 ALOGD("Timeout expired, synthesizing event with new stylus data");
4176#endif
4177 cookAndDispatch(when);
4178 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4179 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4180 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4181 }
Michael Wright842500e2015-03-13 17:32:02 -07004182 }
4183}
4184
4185void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4186 // Always start with a clean state.
4187 mCurrentCookedState.clear();
4188
4189 // Apply stylus buttons to current raw state.
4190 applyExternalStylusButtonState(when);
4191
4192 // Handle policy on initial down or hover events.
4193 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4194 && mCurrentRawState.rawPointerData.pointerCount != 0;
4195
4196 uint32_t policyFlags = 0;
4197 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4198 if (initialDown || buttonsPressed) {
4199 // If this is a touch screen, hide the pointer on an initial down.
4200 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4201 getContext()->fadePointer();
4202 }
4203
4204 if (mParameters.wake) {
4205 policyFlags |= POLICY_FLAG_WAKE;
4206 }
4207 }
4208
4209 // Consume raw off-screen touches before cooking pointer data.
4210 // If touches are consumed, subsequent code will not receive any pointer data.
4211 if (consumeRawTouches(when, policyFlags)) {
4212 mCurrentRawState.rawPointerData.clear();
4213 }
4214
4215 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4216 // with cooked pointer data that has the same ids and indices as the raw data.
4217 // The following code can use either the raw or cooked data, as needed.
4218 cookPointerData();
4219
4220 // Apply stylus pressure to current cooked state.
4221 applyExternalStylusTouchState(when);
4222
4223 // Synthesize key down from raw buttons if needed.
4224 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004225 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004226
4227 // Dispatch the touches either directly or by translation through a pointer on screen.
4228 if (mDeviceMode == DEVICE_MODE_POINTER) {
4229 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4230 !idBits.isEmpty(); ) {
4231 uint32_t id = idBits.clearFirstMarkedBit();
4232 const RawPointerData::Pointer& pointer =
4233 mCurrentRawState.rawPointerData.pointerForId(id);
4234 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4235 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4236 mCurrentCookedState.stylusIdBits.markBit(id);
4237 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4238 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4239 mCurrentCookedState.fingerIdBits.markBit(id);
4240 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4241 mCurrentCookedState.mouseIdBits.markBit(id);
4242 }
4243 }
4244 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4245 !idBits.isEmpty(); ) {
4246 uint32_t id = idBits.clearFirstMarkedBit();
4247 const RawPointerData::Pointer& pointer =
4248 mCurrentRawState.rawPointerData.pointerForId(id);
4249 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4250 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4251 mCurrentCookedState.stylusIdBits.markBit(id);
4252 }
4253 }
4254
4255 // Stylus takes precedence over all tools, then mouse, then finger.
4256 PointerUsage pointerUsage = mPointerUsage;
4257 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4258 mCurrentCookedState.mouseIdBits.clear();
4259 mCurrentCookedState.fingerIdBits.clear();
4260 pointerUsage = POINTER_USAGE_STYLUS;
4261 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4262 mCurrentCookedState.fingerIdBits.clear();
4263 pointerUsage = POINTER_USAGE_MOUSE;
4264 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4265 isPointerDown(mCurrentRawState.buttonState)) {
4266 pointerUsage = POINTER_USAGE_GESTURES;
4267 }
4268
4269 dispatchPointerUsage(when, policyFlags, pointerUsage);
4270 } else {
4271 if (mDeviceMode == DEVICE_MODE_DIRECT
4272 && mConfig.showTouches && mPointerController != NULL) {
4273 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4274 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4275
4276 mPointerController->setButtonState(mCurrentRawState.buttonState);
4277 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4278 mCurrentCookedState.cookedPointerData.idToIndex,
4279 mCurrentCookedState.cookedPointerData.touchingIdBits);
4280 }
4281
Michael Wright8e812822015-06-22 16:18:21 +01004282 if (!mCurrentMotionAborted) {
4283 dispatchButtonRelease(when, policyFlags);
4284 dispatchHoverExit(when, policyFlags);
4285 dispatchTouches(when, policyFlags);
4286 dispatchHoverEnterAndMove(when, policyFlags);
4287 dispatchButtonPress(when, policyFlags);
4288 }
4289
4290 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4291 mCurrentMotionAborted = false;
4292 }
Michael Wright842500e2015-03-13 17:32:02 -07004293 }
4294
4295 // Synthesize key up from raw buttons if needed.
4296 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004297 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298
4299 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004300 mCurrentRawState.rawVScroll = 0;
4301 mCurrentRawState.rawHScroll = 0;
4302
4303 // Copy current touch to last touch in preparation for the next cycle.
4304 mLastRawState.copyFrom(mCurrentRawState);
4305 mLastCookedState.copyFrom(mCurrentCookedState);
4306}
4307
4308void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004309 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004310 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4311 }
4312}
4313
4314void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004315 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4316 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004317
Michael Wright53dca3a2015-04-23 17:39:53 +01004318 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4319 float pressure = mExternalStylusState.pressure;
4320 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4321 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4322 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4323 }
4324 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4325 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4326
4327 PointerProperties& properties =
4328 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004329 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4330 properties.toolType = mExternalStylusState.toolType;
4331 }
4332 }
4333}
4334
4335bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4336 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4337 return false;
4338 }
4339
4340 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4341 && state.rawPointerData.pointerCount != 0;
4342 if (initialDown) {
4343 if (mExternalStylusState.pressure != 0.0f) {
4344#if DEBUG_STYLUS_FUSION
4345 ALOGD("Have both stylus and touch data, beginning fusion");
4346#endif
4347 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4348 } else if (timeout) {
4349#if DEBUG_STYLUS_FUSION
4350 ALOGD("Timeout expired, assuming touch is not a stylus.");
4351#endif
4352 resetExternalStylus();
4353 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004354 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4355 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004356 }
4357#if DEBUG_STYLUS_FUSION
4358 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004359 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004360#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004361 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004362 return true;
4363 }
4364 }
4365
4366 // Check if the stylus pointer has gone up.
4367 if (mExternalStylusId != -1 &&
4368 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4369#if DEBUG_STYLUS_FUSION
4370 ALOGD("Stylus pointer is going up");
4371#endif
4372 mExternalStylusId = -1;
4373 }
4374
4375 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376}
4377
4378void TouchInputMapper::timeoutExpired(nsecs_t when) {
4379 if (mDeviceMode == DEVICE_MODE_POINTER) {
4380 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4381 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4382 }
Michael Wright842500e2015-03-13 17:32:02 -07004383 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004384 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004385 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004386 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4387 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004388 }
4389 }
4390}
4391
4392void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004393 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004394 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004395 // We're either in the middle of a fused stream of data or we're waiting on data before
4396 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4397 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004398 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004399 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 }
4401}
4402
4403bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4404 // Check for release of a virtual key.
4405 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004406 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 // Pointer went up while virtual key was down.
4408 mCurrentVirtualKey.down = false;
4409 if (!mCurrentVirtualKey.ignored) {
4410#if DEBUG_VIRTUAL_KEYS
4411 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4412 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4413#endif
4414 dispatchVirtualKey(when, policyFlags,
4415 AKEY_EVENT_ACTION_UP,
4416 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4417 }
4418 return true;
4419 }
4420
Michael Wright842500e2015-03-13 17:32:02 -07004421 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4422 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4423 const RawPointerData::Pointer& pointer =
4424 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4426 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4427 // Pointer is still within the space of the virtual key.
4428 return true;
4429 }
4430 }
4431
4432 // Pointer left virtual key area or another pointer also went down.
4433 // Send key cancellation but do not consume the touch yet.
4434 // This is useful when the user swipes through from the virtual key area
4435 // into the main display surface.
4436 mCurrentVirtualKey.down = false;
4437 if (!mCurrentVirtualKey.ignored) {
4438#if DEBUG_VIRTUAL_KEYS
4439 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4440 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4441#endif
4442 dispatchVirtualKey(when, policyFlags,
4443 AKEY_EVENT_ACTION_UP,
4444 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4445 | AKEY_EVENT_FLAG_CANCELED);
4446 }
4447 }
4448
Michael Wright842500e2015-03-13 17:32:02 -07004449 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4450 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004452 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4453 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4455 // If exactly one pointer went down, check for virtual key hit.
4456 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004457 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4459 if (virtualKey) {
4460 mCurrentVirtualKey.down = true;
4461 mCurrentVirtualKey.downTime = when;
4462 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4463 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4464 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4465 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4466
4467 if (!mCurrentVirtualKey.ignored) {
4468#if DEBUG_VIRTUAL_KEYS
4469 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4470 mCurrentVirtualKey.keyCode,
4471 mCurrentVirtualKey.scanCode);
4472#endif
4473 dispatchVirtualKey(when, policyFlags,
4474 AKEY_EVENT_ACTION_DOWN,
4475 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4476 }
4477 }
4478 }
4479 return true;
4480 }
4481 }
4482
4483 // Disable all virtual key touches that happen within a short time interval of the
4484 // most recent touch within the screen area. The idea is to filter out stray
4485 // virtual key presses when interacting with the touch screen.
4486 //
4487 // Problems we're trying to solve:
4488 //
4489 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4490 // virtual key area that is implemented by a separate touch panel and accidentally
4491 // triggers a virtual key.
4492 //
4493 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4494 // area and accidentally triggers a virtual key. This often happens when virtual keys
4495 // are layed out below the screen near to where the on screen keyboard's space bar
4496 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004497 if (mConfig.virtualKeyQuietTime > 0 &&
4498 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4500 }
4501 return false;
4502}
4503
4504void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4505 int32_t keyEventAction, int32_t keyEventFlags) {
4506 int32_t keyCode = mCurrentVirtualKey.keyCode;
4507 int32_t scanCode = mCurrentVirtualKey.scanCode;
4508 nsecs_t downTime = mCurrentVirtualKey.downTime;
4509 int32_t metaState = mContext->getGlobalMetaState();
4510 policyFlags |= POLICY_FLAG_VIRTUAL;
4511
4512 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4513 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4514 getListener()->notifyKey(&args);
4515}
4516
Michael Wright8e812822015-06-22 16:18:21 +01004517void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4518 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4519 if (!currentIdBits.isEmpty()) {
4520 int32_t metaState = getContext()->getGlobalMetaState();
4521 int32_t buttonState = mCurrentCookedState.buttonState;
4522 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4523 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4524 mCurrentCookedState.cookedPointerData.pointerProperties,
4525 mCurrentCookedState.cookedPointerData.pointerCoords,
4526 mCurrentCookedState.cookedPointerData.idToIndex,
4527 currentIdBits, -1,
4528 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4529 mCurrentMotionAborted = true;
4530 }
4531}
4532
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004534 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4535 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004537 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538
4539 if (currentIdBits == lastIdBits) {
4540 if (!currentIdBits.isEmpty()) {
4541 // No pointer id changes so this is a move event.
4542 // The listener takes care of batching moves so we don't have to deal with that here.
4543 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004544 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004546 mCurrentCookedState.cookedPointerData.pointerProperties,
4547 mCurrentCookedState.cookedPointerData.pointerCoords,
4548 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 currentIdBits, -1,
4550 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4551 }
4552 } else {
4553 // There may be pointers going up and pointers going down and pointers moving
4554 // all at the same time.
4555 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4556 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4557 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4558 BitSet32 dispatchedIdBits(lastIdBits.value);
4559
4560 // Update last coordinates of pointers that have moved so that we observe the new
4561 // pointer positions at the same time as other pointers that have just gone up.
4562 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004563 mCurrentCookedState.cookedPointerData.pointerProperties,
4564 mCurrentCookedState.cookedPointerData.pointerCoords,
4565 mCurrentCookedState.cookedPointerData.idToIndex,
4566 mLastCookedState.cookedPointerData.pointerProperties,
4567 mLastCookedState.cookedPointerData.pointerCoords,
4568 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004570 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 moveNeeded = true;
4572 }
4573
4574 // Dispatch pointer up events.
4575 while (!upIdBits.isEmpty()) {
4576 uint32_t upId = upIdBits.clearFirstMarkedBit();
4577
4578 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004579 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004580 mLastCookedState.cookedPointerData.pointerProperties,
4581 mLastCookedState.cookedPointerData.pointerCoords,
4582 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004583 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 dispatchedIdBits.clearBit(upId);
4585 }
4586
4587 // Dispatch move events if any of the remaining pointers moved from their old locations.
4588 // Although applications receive new locations as part of individual pointer up
4589 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004590 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4592 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004593 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004594 mCurrentCookedState.cookedPointerData.pointerProperties,
4595 mCurrentCookedState.cookedPointerData.pointerCoords,
4596 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004597 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598 }
4599
4600 // Dispatch pointer down events using the new pointer locations.
4601 while (!downIdBits.isEmpty()) {
4602 uint32_t downId = downIdBits.clearFirstMarkedBit();
4603 dispatchedIdBits.markBit(downId);
4604
4605 if (dispatchedIdBits.count() == 1) {
4606 // First pointer is going down. Set down time.
4607 mDownTime = when;
4608 }
4609
4610 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004611 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004612 mCurrentCookedState.cookedPointerData.pointerProperties,
4613 mCurrentCookedState.cookedPointerData.pointerCoords,
4614 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004615 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 }
4617 }
4618}
4619
4620void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4621 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004622 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4623 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 int32_t metaState = getContext()->getGlobalMetaState();
4625 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004626 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004627 mLastCookedState.cookedPointerData.pointerProperties,
4628 mLastCookedState.cookedPointerData.pointerCoords,
4629 mLastCookedState.cookedPointerData.idToIndex,
4630 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4632 mSentHoverEnter = false;
4633 }
4634}
4635
4636void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004637 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4638 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 int32_t metaState = getContext()->getGlobalMetaState();
4640 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004641 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004642 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004643 mCurrentCookedState.cookedPointerData.pointerProperties,
4644 mCurrentCookedState.cookedPointerData.pointerCoords,
4645 mCurrentCookedState.cookedPointerData.idToIndex,
4646 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4648 mSentHoverEnter = true;
4649 }
4650
4651 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004652 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004653 mCurrentRawState.buttonState, 0,
4654 mCurrentCookedState.cookedPointerData.pointerProperties,
4655 mCurrentCookedState.cookedPointerData.pointerCoords,
4656 mCurrentCookedState.cookedPointerData.idToIndex,
4657 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4659 }
4660}
4661
Michael Wright7b159c92015-05-14 14:48:03 +01004662void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4663 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4664 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4665 const int32_t metaState = getContext()->getGlobalMetaState();
4666 int32_t buttonState = mLastCookedState.buttonState;
4667 while (!releasedButtons.isEmpty()) {
4668 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4669 buttonState &= ~actionButton;
4670 dispatchMotion(when, policyFlags, mSource,
4671 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4672 0, metaState, buttonState, 0,
4673 mCurrentCookedState.cookedPointerData.pointerProperties,
4674 mCurrentCookedState.cookedPointerData.pointerCoords,
4675 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4676 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4677 }
4678}
4679
4680void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4681 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4682 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4683 const int32_t metaState = getContext()->getGlobalMetaState();
4684 int32_t buttonState = mLastCookedState.buttonState;
4685 while (!pressedButtons.isEmpty()) {
4686 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4687 buttonState |= actionButton;
4688 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4689 0, metaState, buttonState, 0,
4690 mCurrentCookedState.cookedPointerData.pointerProperties,
4691 mCurrentCookedState.cookedPointerData.pointerCoords,
4692 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4693 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4694 }
4695}
4696
4697const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4698 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4699 return cookedPointerData.touchingIdBits;
4700 }
4701 return cookedPointerData.hoveringIdBits;
4702}
4703
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004705 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706
Michael Wright842500e2015-03-13 17:32:02 -07004707 mCurrentCookedState.cookedPointerData.clear();
4708 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4709 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4710 mCurrentRawState.rawPointerData.hoveringIdBits;
4711 mCurrentCookedState.cookedPointerData.touchingIdBits =
4712 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713
Michael Wright7b159c92015-05-14 14:48:03 +01004714 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4715 mCurrentCookedState.buttonState = 0;
4716 } else {
4717 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4718 }
4719
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 // Walk through the the active pointers and map device coordinates onto
4721 // surface coordinates and adjust for display orientation.
4722 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004723 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
4725 // Size
4726 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4727 switch (mCalibration.sizeCalibration) {
4728 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4729 case Calibration::SIZE_CALIBRATION_DIAMETER:
4730 case Calibration::SIZE_CALIBRATION_BOX:
4731 case Calibration::SIZE_CALIBRATION_AREA:
4732 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4733 touchMajor = in.touchMajor;
4734 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4735 toolMajor = in.toolMajor;
4736 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4737 size = mRawPointerAxes.touchMinor.valid
4738 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4739 } else if (mRawPointerAxes.touchMajor.valid) {
4740 toolMajor = touchMajor = in.touchMajor;
4741 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4742 ? in.touchMinor : in.touchMajor;
4743 size = mRawPointerAxes.touchMinor.valid
4744 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4745 } else if (mRawPointerAxes.toolMajor.valid) {
4746 touchMajor = toolMajor = in.toolMajor;
4747 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4748 ? in.toolMinor : in.toolMajor;
4749 size = mRawPointerAxes.toolMinor.valid
4750 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4751 } else {
4752 ALOG_ASSERT(false, "No touch or tool axes. "
4753 "Size calibration should have been resolved to NONE.");
4754 touchMajor = 0;
4755 touchMinor = 0;
4756 toolMajor = 0;
4757 toolMinor = 0;
4758 size = 0;
4759 }
4760
4761 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004762 uint32_t touchingCount =
4763 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 if (touchingCount > 1) {
4765 touchMajor /= touchingCount;
4766 touchMinor /= touchingCount;
4767 toolMajor /= touchingCount;
4768 toolMinor /= touchingCount;
4769 size /= touchingCount;
4770 }
4771 }
4772
4773 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4774 touchMajor *= mGeometricScale;
4775 touchMinor *= mGeometricScale;
4776 toolMajor *= mGeometricScale;
4777 toolMinor *= mGeometricScale;
4778 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4779 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4780 touchMinor = touchMajor;
4781 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4782 toolMinor = toolMajor;
4783 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4784 touchMinor = touchMajor;
4785 toolMinor = toolMajor;
4786 }
4787
4788 mCalibration.applySizeScaleAndBias(&touchMajor);
4789 mCalibration.applySizeScaleAndBias(&touchMinor);
4790 mCalibration.applySizeScaleAndBias(&toolMajor);
4791 mCalibration.applySizeScaleAndBias(&toolMinor);
4792 size *= mSizeScale;
4793 break;
4794 default:
4795 touchMajor = 0;
4796 touchMinor = 0;
4797 toolMajor = 0;
4798 toolMinor = 0;
4799 size = 0;
4800 break;
4801 }
4802
4803 // Pressure
4804 float pressure;
4805 switch (mCalibration.pressureCalibration) {
4806 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4807 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4808 pressure = in.pressure * mPressureScale;
4809 break;
4810 default:
4811 pressure = in.isHovering ? 0 : 1;
4812 break;
4813 }
4814
4815 // Tilt and Orientation
4816 float tilt;
4817 float orientation;
4818 if (mHaveTilt) {
4819 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4820 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4821 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4822 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4823 } else {
4824 tilt = 0;
4825
4826 switch (mCalibration.orientationCalibration) {
4827 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4828 orientation = in.orientation * mOrientationScale;
4829 break;
4830 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4831 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4832 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4833 if (c1 != 0 || c2 != 0) {
4834 orientation = atan2f(c1, c2) * 0.5f;
4835 float confidence = hypotf(c1, c2);
4836 float scale = 1.0f + confidence / 16.0f;
4837 touchMajor *= scale;
4838 touchMinor /= scale;
4839 toolMajor *= scale;
4840 toolMinor /= scale;
4841 } else {
4842 orientation = 0;
4843 }
4844 break;
4845 }
4846 default:
4847 orientation = 0;
4848 }
4849 }
4850
4851 // Distance
4852 float distance;
4853 switch (mCalibration.distanceCalibration) {
4854 case Calibration::DISTANCE_CALIBRATION_SCALED:
4855 distance = in.distance * mDistanceScale;
4856 break;
4857 default:
4858 distance = 0;
4859 }
4860
4861 // Coverage
4862 int32_t rawLeft, rawTop, rawRight, rawBottom;
4863 switch (mCalibration.coverageCalibration) {
4864 case Calibration::COVERAGE_CALIBRATION_BOX:
4865 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4866 rawRight = in.toolMinor & 0x0000ffff;
4867 rawBottom = in.toolMajor & 0x0000ffff;
4868 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4869 break;
4870 default:
4871 rawLeft = rawTop = rawRight = rawBottom = 0;
4872 break;
4873 }
4874
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004875 // Adjust X,Y coords for device calibration
4876 // TODO: Adjust coverage coords?
4877 float xTransformed = in.x, yTransformed = in.y;
4878 mAffineTransform.applyTo(xTransformed, yTransformed);
4879
4880 // Adjust X, Y, and coverage coords for surface orientation.
4881 float x, y;
4882 float left, top, right, bottom;
4883
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 switch (mSurfaceOrientation) {
4885 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004886 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4887 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4889 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4890 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4891 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4892 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004893 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4895 }
4896 break;
4897 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004898 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4899 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4901 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4902 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4903 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4904 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09004905 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4907 }
4908 break;
4909 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004910 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4911 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4913 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4914 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4915 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4916 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004917 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4919 }
4920 break;
4921 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004922 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4923 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4925 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4926 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4927 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4928 break;
4929 }
4930
4931 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07004932 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 out.clear();
4934 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4935 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4936 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4937 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4938 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4939 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4940 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4941 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4942 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4943 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4944 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4945 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4946 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4947 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4948 } else {
4949 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4950 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4951 }
4952
4953 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07004954 PointerProperties& properties =
4955 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 uint32_t id = in.id;
4957 properties.clear();
4958 properties.id = id;
4959 properties.toolType = in.toolType;
4960
4961 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07004962 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 }
4964}
4965
4966void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4967 PointerUsage pointerUsage) {
4968 if (pointerUsage != mPointerUsage) {
4969 abortPointerUsage(when, policyFlags);
4970 mPointerUsage = pointerUsage;
4971 }
4972
4973 switch (mPointerUsage) {
4974 case POINTER_USAGE_GESTURES:
4975 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4976 break;
4977 case POINTER_USAGE_STYLUS:
4978 dispatchPointerStylus(when, policyFlags);
4979 break;
4980 case POINTER_USAGE_MOUSE:
4981 dispatchPointerMouse(when, policyFlags);
4982 break;
4983 default:
4984 break;
4985 }
4986}
4987
4988void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4989 switch (mPointerUsage) {
4990 case POINTER_USAGE_GESTURES:
4991 abortPointerGestures(when, policyFlags);
4992 break;
4993 case POINTER_USAGE_STYLUS:
4994 abortPointerStylus(when, policyFlags);
4995 break;
4996 case POINTER_USAGE_MOUSE:
4997 abortPointerMouse(when, policyFlags);
4998 break;
4999 default:
5000 break;
5001 }
5002
5003 mPointerUsage = POINTER_USAGE_NONE;
5004}
5005
5006void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5007 bool isTimeout) {
5008 // Update current gesture coordinates.
5009 bool cancelPreviousGesture, finishPreviousGesture;
5010 bool sendEvents = preparePointerGestures(when,
5011 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5012 if (!sendEvents) {
5013 return;
5014 }
5015 if (finishPreviousGesture) {
5016 cancelPreviousGesture = false;
5017 }
5018
5019 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005020 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5021 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 if (finishPreviousGesture || cancelPreviousGesture) {
5023 mPointerController->clearSpots();
5024 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005025
5026 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5027 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5028 mPointerGesture.currentGestureIdToIndex,
5029 mPointerGesture.currentGestureIdBits);
5030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031 } else {
5032 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5033 }
5034
5035 // Show or hide the pointer if needed.
5036 switch (mPointerGesture.currentGestureMode) {
5037 case PointerGesture::NEUTRAL:
5038 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005039 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5040 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 // Remind the user of where the pointer is after finishing a gesture with spots.
5042 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5043 }
5044 break;
5045 case PointerGesture::TAP:
5046 case PointerGesture::TAP_DRAG:
5047 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5048 case PointerGesture::HOVER:
5049 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005050 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 // Unfade the pointer when the current gesture manipulates the
5052 // area directly under the pointer.
5053 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5054 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 case PointerGesture::FREEFORM:
5056 // Fade the pointer when the current gesture manipulates a different
5057 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005058 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5060 } else {
5061 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5062 }
5063 break;
5064 }
5065
5066 // Send events!
5067 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005068 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069
5070 // Update last coordinates of pointers that have moved so that we observe the new
5071 // pointer positions at the same time as other pointers that have just gone up.
5072 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5073 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5074 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5075 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5076 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5077 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5078 bool moveNeeded = false;
5079 if (down && !cancelPreviousGesture && !finishPreviousGesture
5080 && !mPointerGesture.lastGestureIdBits.isEmpty()
5081 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5082 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5083 & mPointerGesture.lastGestureIdBits.value);
5084 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5085 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5086 mPointerGesture.lastGestureProperties,
5087 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5088 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005089 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 moveNeeded = true;
5091 }
5092 }
5093
5094 // Send motion events for all pointers that went up or were canceled.
5095 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5096 if (!dispatchedGestureIdBits.isEmpty()) {
5097 if (cancelPreviousGesture) {
5098 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005099 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 AMOTION_EVENT_EDGE_FLAG_NONE,
5101 mPointerGesture.lastGestureProperties,
5102 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005103 dispatchedGestureIdBits, -1, 0,
5104 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105
5106 dispatchedGestureIdBits.clear();
5107 } else {
5108 BitSet32 upGestureIdBits;
5109 if (finishPreviousGesture) {
5110 upGestureIdBits = dispatchedGestureIdBits;
5111 } else {
5112 upGestureIdBits.value = dispatchedGestureIdBits.value
5113 & ~mPointerGesture.currentGestureIdBits.value;
5114 }
5115 while (!upGestureIdBits.isEmpty()) {
5116 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5117
5118 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005119 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5121 mPointerGesture.lastGestureProperties,
5122 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5123 dispatchedGestureIdBits, id,
5124 0, 0, mPointerGesture.downTime);
5125
5126 dispatchedGestureIdBits.clearBit(id);
5127 }
5128 }
5129 }
5130
5131 // Send motion events for all pointers that moved.
5132 if (moveNeeded) {
5133 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005134 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5135 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 mPointerGesture.currentGestureProperties,
5137 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5138 dispatchedGestureIdBits, -1,
5139 0, 0, mPointerGesture.downTime);
5140 }
5141
5142 // Send motion events for all pointers that went down.
5143 if (down) {
5144 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5145 & ~dispatchedGestureIdBits.value);
5146 while (!downGestureIdBits.isEmpty()) {
5147 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5148 dispatchedGestureIdBits.markBit(id);
5149
5150 if (dispatchedGestureIdBits.count() == 1) {
5151 mPointerGesture.downTime = when;
5152 }
5153
5154 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005155 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 mPointerGesture.currentGestureProperties,
5157 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5158 dispatchedGestureIdBits, id,
5159 0, 0, mPointerGesture.downTime);
5160 }
5161 }
5162
5163 // Send motion events for hover.
5164 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5165 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005166 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5168 mPointerGesture.currentGestureProperties,
5169 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5170 mPointerGesture.currentGestureIdBits, -1,
5171 0, 0, mPointerGesture.downTime);
5172 } else if (dispatchedGestureIdBits.isEmpty()
5173 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5174 // Synthesize a hover move event after all pointers go up to indicate that
5175 // the pointer is hovering again even if the user is not currently touching
5176 // the touch pad. This ensures that a view will receive a fresh hover enter
5177 // event after a tap.
5178 float x, y;
5179 mPointerController->getPosition(&x, &y);
5180
5181 PointerProperties pointerProperties;
5182 pointerProperties.clear();
5183 pointerProperties.id = 0;
5184 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5185
5186 PointerCoords pointerCoords;
5187 pointerCoords.clear();
5188 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5189 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5190
5191 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005192 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5194 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5195 0, 0, mPointerGesture.downTime);
5196 getListener()->notifyMotion(&args);
5197 }
5198
5199 // Update state.
5200 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5201 if (!down) {
5202 mPointerGesture.lastGestureIdBits.clear();
5203 } else {
5204 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5205 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5206 uint32_t id = idBits.clearFirstMarkedBit();
5207 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5208 mPointerGesture.lastGestureProperties[index].copyFrom(
5209 mPointerGesture.currentGestureProperties[index]);
5210 mPointerGesture.lastGestureCoords[index].copyFrom(
5211 mPointerGesture.currentGestureCoords[index]);
5212 mPointerGesture.lastGestureIdToIndex[id] = index;
5213 }
5214 }
5215}
5216
5217void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5218 // Cancel previously dispatches pointers.
5219 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5220 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005221 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005223 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224 AMOTION_EVENT_EDGE_FLAG_NONE,
5225 mPointerGesture.lastGestureProperties,
5226 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5227 mPointerGesture.lastGestureIdBits, -1,
5228 0, 0, mPointerGesture.downTime);
5229 }
5230
5231 // Reset the current pointer gesture.
5232 mPointerGesture.reset();
5233 mPointerVelocityControl.reset();
5234
5235 // Remove any current spots.
5236 if (mPointerController != NULL) {
5237 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5238 mPointerController->clearSpots();
5239 }
5240}
5241
5242bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5243 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5244 *outCancelPreviousGesture = false;
5245 *outFinishPreviousGesture = false;
5246
5247 // Handle TAP timeout.
5248 if (isTimeout) {
5249#if DEBUG_GESTURES
5250 ALOGD("Gestures: Processing timeout");
5251#endif
5252
5253 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5254 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5255 // The tap/drag timeout has not yet expired.
5256 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5257 + mConfig.pointerGestureTapDragInterval);
5258 } else {
5259 // The tap is finished.
5260#if DEBUG_GESTURES
5261 ALOGD("Gestures: TAP finished");
5262#endif
5263 *outFinishPreviousGesture = true;
5264
5265 mPointerGesture.activeGestureId = -1;
5266 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5267 mPointerGesture.currentGestureIdBits.clear();
5268
5269 mPointerVelocityControl.reset();
5270 return true;
5271 }
5272 }
5273
5274 // We did not handle this timeout.
5275 return false;
5276 }
5277
Michael Wright842500e2015-03-13 17:32:02 -07005278 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5279 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280
5281 // Update the velocity tracker.
5282 {
5283 VelocityTracker::Position positions[MAX_POINTERS];
5284 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005285 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005287 const RawPointerData::Pointer& pointer =
5288 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 positions[count].x = pointer.x * mPointerXMovementScale;
5290 positions[count].y = pointer.y * mPointerYMovementScale;
5291 }
5292 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005293 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 }
5295
5296 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5297 // to NEUTRAL, then we should not generate tap event.
5298 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5299 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5300 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5301 mPointerGesture.resetTap();
5302 }
5303
5304 // Pick a new active touch id if needed.
5305 // Choose an arbitrary pointer that just went down, if there is one.
5306 // Otherwise choose an arbitrary remaining pointer.
5307 // This guarantees we always have an active touch id when there is at least one pointer.
5308 // We keep the same active touch id for as long as possible.
5309 bool activeTouchChanged = false;
5310 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5311 int32_t activeTouchId = lastActiveTouchId;
5312 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005313 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 activeTouchChanged = true;
5315 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005316 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 mPointerGesture.firstTouchTime = when;
5318 }
Michael Wright842500e2015-03-13 17:32:02 -07005319 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005321 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005323 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 } else {
5325 activeTouchId = mPointerGesture.activeTouchId = -1;
5326 }
5327 }
5328
5329 // Determine whether we are in quiet time.
5330 bool isQuietTime = false;
5331 if (activeTouchId < 0) {
5332 mPointerGesture.resetQuietTime();
5333 } else {
5334 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5335 if (!isQuietTime) {
5336 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5337 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5338 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5339 && currentFingerCount < 2) {
5340 // Enter quiet time when exiting swipe or freeform state.
5341 // This is to prevent accidentally entering the hover state and flinging the
5342 // pointer when finishing a swipe and there is still one pointer left onscreen.
5343 isQuietTime = true;
5344 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5345 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005346 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 // Enter quiet time when releasing the button and there are still two or more
5348 // fingers down. This may indicate that one finger was used to press the button
5349 // but it has not gone up yet.
5350 isQuietTime = true;
5351 }
5352 if (isQuietTime) {
5353 mPointerGesture.quietTime = when;
5354 }
5355 }
5356 }
5357
5358 // Switch states based on button and pointer state.
5359 if (isQuietTime) {
5360 // Case 1: Quiet time. (QUIET)
5361#if DEBUG_GESTURES
5362 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5363 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5364#endif
5365 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5366 *outFinishPreviousGesture = true;
5367 }
5368
5369 mPointerGesture.activeGestureId = -1;
5370 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5371 mPointerGesture.currentGestureIdBits.clear();
5372
5373 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005374 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5376 // The pointer follows the active touch point.
5377 // Emit DOWN, MOVE, UP events at the pointer location.
5378 //
5379 // Only the active touch matters; other fingers are ignored. This policy helps
5380 // to handle the case where the user places a second finger on the touch pad
5381 // to apply the necessary force to depress an integrated button below the surface.
5382 // We don't want the second finger to be delivered to applications.
5383 //
5384 // For this to work well, we need to make sure to track the pointer that is really
5385 // active. If the user first puts one finger down to click then adds another
5386 // finger to drag then the active pointer should switch to the finger that is
5387 // being dragged.
5388#if DEBUG_GESTURES
5389 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5390 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5391#endif
5392 // Reset state when just starting.
5393 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5394 *outFinishPreviousGesture = true;
5395 mPointerGesture.activeGestureId = 0;
5396 }
5397
5398 // Switch pointers if needed.
5399 // Find the fastest pointer and follow it.
5400 if (activeTouchId >= 0 && currentFingerCount > 1) {
5401 int32_t bestId = -1;
5402 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005403 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 uint32_t id = idBits.clearFirstMarkedBit();
5405 float vx, vy;
5406 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5407 float speed = hypotf(vx, vy);
5408 if (speed > bestSpeed) {
5409 bestId = id;
5410 bestSpeed = speed;
5411 }
5412 }
5413 }
5414 if (bestId >= 0 && bestId != activeTouchId) {
5415 mPointerGesture.activeTouchId = activeTouchId = bestId;
5416 activeTouchChanged = true;
5417#if DEBUG_GESTURES
5418 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5419 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5420#endif
5421 }
5422 }
5423
Jun Mukaifa1706a2015-12-03 01:14:46 -08005424 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005425 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005427 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005429 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005430 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5431 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432
5433 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5434 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5435
5436 // Move the pointer using a relative motion.
5437 // When using spots, the click will occur at the position of the anchor
5438 // spot and all other spots will move there.
5439 mPointerController->move(deltaX, deltaY);
5440 } else {
5441 mPointerVelocityControl.reset();
5442 }
5443
5444 float x, y;
5445 mPointerController->getPosition(&x, &y);
5446
5447 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5448 mPointerGesture.currentGestureIdBits.clear();
5449 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5450 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5451 mPointerGesture.currentGestureProperties[0].clear();
5452 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5453 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5454 mPointerGesture.currentGestureCoords[0].clear();
5455 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5456 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5457 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5458 } else if (currentFingerCount == 0) {
5459 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5460 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5461 *outFinishPreviousGesture = true;
5462 }
5463
5464 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5465 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5466 bool tapped = false;
5467 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5468 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5469 && lastFingerCount == 1) {
5470 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5471 float x, y;
5472 mPointerController->getPosition(&x, &y);
5473 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5474 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5475#if DEBUG_GESTURES
5476 ALOGD("Gestures: TAP");
5477#endif
5478
5479 mPointerGesture.tapUpTime = when;
5480 getContext()->requestTimeoutAtTime(when
5481 + mConfig.pointerGestureTapDragInterval);
5482
5483 mPointerGesture.activeGestureId = 0;
5484 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5485 mPointerGesture.currentGestureIdBits.clear();
5486 mPointerGesture.currentGestureIdBits.markBit(
5487 mPointerGesture.activeGestureId);
5488 mPointerGesture.currentGestureIdToIndex[
5489 mPointerGesture.activeGestureId] = 0;
5490 mPointerGesture.currentGestureProperties[0].clear();
5491 mPointerGesture.currentGestureProperties[0].id =
5492 mPointerGesture.activeGestureId;
5493 mPointerGesture.currentGestureProperties[0].toolType =
5494 AMOTION_EVENT_TOOL_TYPE_FINGER;
5495 mPointerGesture.currentGestureCoords[0].clear();
5496 mPointerGesture.currentGestureCoords[0].setAxisValue(
5497 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5498 mPointerGesture.currentGestureCoords[0].setAxisValue(
5499 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5500 mPointerGesture.currentGestureCoords[0].setAxisValue(
5501 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5502
5503 tapped = true;
5504 } else {
5505#if DEBUG_GESTURES
5506 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5507 x - mPointerGesture.tapX,
5508 y - mPointerGesture.tapY);
5509#endif
5510 }
5511 } else {
5512#if DEBUG_GESTURES
5513 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5514 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5515 (when - mPointerGesture.tapDownTime) * 0.000001f);
5516 } else {
5517 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5518 }
5519#endif
5520 }
5521 }
5522
5523 mPointerVelocityControl.reset();
5524
5525 if (!tapped) {
5526#if DEBUG_GESTURES
5527 ALOGD("Gestures: NEUTRAL");
5528#endif
5529 mPointerGesture.activeGestureId = -1;
5530 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5531 mPointerGesture.currentGestureIdBits.clear();
5532 }
5533 } else if (currentFingerCount == 1) {
5534 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5535 // The pointer follows the active touch point.
5536 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5537 // When in TAP_DRAG, emit MOVE events at the pointer location.
5538 ALOG_ASSERT(activeTouchId >= 0);
5539
5540 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5541 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5542 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5543 float x, y;
5544 mPointerController->getPosition(&x, &y);
5545 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5546 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5547 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5548 } else {
5549#if DEBUG_GESTURES
5550 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5551 x - mPointerGesture.tapX,
5552 y - mPointerGesture.tapY);
5553#endif
5554 }
5555 } else {
5556#if DEBUG_GESTURES
5557 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5558 (when - mPointerGesture.tapUpTime) * 0.000001f);
5559#endif
5560 }
5561 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5562 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5563 }
5564
Jun Mukaifa1706a2015-12-03 01:14:46 -08005565 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005566 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005568 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005570 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005571 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5572 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573
5574 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5575 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5576
5577 // Move the pointer using a relative motion.
5578 // When using spots, the hover or drag will occur at the position of the anchor spot.
5579 mPointerController->move(deltaX, deltaY);
5580 } else {
5581 mPointerVelocityControl.reset();
5582 }
5583
5584 bool down;
5585 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5586#if DEBUG_GESTURES
5587 ALOGD("Gestures: TAP_DRAG");
5588#endif
5589 down = true;
5590 } else {
5591#if DEBUG_GESTURES
5592 ALOGD("Gestures: HOVER");
5593#endif
5594 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5595 *outFinishPreviousGesture = true;
5596 }
5597 mPointerGesture.activeGestureId = 0;
5598 down = false;
5599 }
5600
5601 float x, y;
5602 mPointerController->getPosition(&x, &y);
5603
5604 mPointerGesture.currentGestureIdBits.clear();
5605 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5606 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5607 mPointerGesture.currentGestureProperties[0].clear();
5608 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5609 mPointerGesture.currentGestureProperties[0].toolType =
5610 AMOTION_EVENT_TOOL_TYPE_FINGER;
5611 mPointerGesture.currentGestureCoords[0].clear();
5612 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5613 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5614 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5615 down ? 1.0f : 0.0f);
5616
5617 if (lastFingerCount == 0 && currentFingerCount != 0) {
5618 mPointerGesture.resetTap();
5619 mPointerGesture.tapDownTime = when;
5620 mPointerGesture.tapX = x;
5621 mPointerGesture.tapY = y;
5622 }
5623 } else {
5624 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5625 // We need to provide feedback for each finger that goes down so we cannot wait
5626 // for the fingers to move before deciding what to do.
5627 //
5628 // The ambiguous case is deciding what to do when there are two fingers down but they
5629 // have not moved enough to determine whether they are part of a drag or part of a
5630 // freeform gesture, or just a press or long-press at the pointer location.
5631 //
5632 // When there are two fingers we start with the PRESS hypothesis and we generate a
5633 // down at the pointer location.
5634 //
5635 // When the two fingers move enough or when additional fingers are added, we make
5636 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5637 ALOG_ASSERT(activeTouchId >= 0);
5638
5639 bool settled = when >= mPointerGesture.firstTouchTime
5640 + mConfig.pointerGestureMultitouchSettleInterval;
5641 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5642 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5643 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5644 *outFinishPreviousGesture = true;
5645 } else if (!settled && currentFingerCount > lastFingerCount) {
5646 // Additional pointers have gone down but not yet settled.
5647 // Reset the gesture.
5648#if DEBUG_GESTURES
5649 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5650 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5651 + mConfig.pointerGestureMultitouchSettleInterval - when)
5652 * 0.000001f);
5653#endif
5654 *outCancelPreviousGesture = true;
5655 } else {
5656 // Continue previous gesture.
5657 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5658 }
5659
5660 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5661 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5662 mPointerGesture.activeGestureId = 0;
5663 mPointerGesture.referenceIdBits.clear();
5664 mPointerVelocityControl.reset();
5665
5666 // Use the centroid and pointer location as the reference points for the gesture.
5667#if DEBUG_GESTURES
5668 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5669 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5670 + mConfig.pointerGestureMultitouchSettleInterval - when)
5671 * 0.000001f);
5672#endif
Michael Wright842500e2015-03-13 17:32:02 -07005673 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674 &mPointerGesture.referenceTouchX,
5675 &mPointerGesture.referenceTouchY);
5676 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5677 &mPointerGesture.referenceGestureY);
5678 }
5679
5680 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005681 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5683 uint32_t id = idBits.clearFirstMarkedBit();
5684 mPointerGesture.referenceDeltas[id].dx = 0;
5685 mPointerGesture.referenceDeltas[id].dy = 0;
5686 }
Michael Wright842500e2015-03-13 17:32:02 -07005687 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688
5689 // Add delta for all fingers and calculate a common movement delta.
5690 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005691 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5692 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5694 bool first = (idBits == commonIdBits);
5695 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005696 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5697 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5699 delta.dx += cpd.x - lpd.x;
5700 delta.dy += cpd.y - lpd.y;
5701
5702 if (first) {
5703 commonDeltaX = delta.dx;
5704 commonDeltaY = delta.dy;
5705 } else {
5706 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5707 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5708 }
5709 }
5710
5711 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5712 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5713 float dist[MAX_POINTER_ID + 1];
5714 int32_t distOverThreshold = 0;
5715 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5716 uint32_t id = idBits.clearFirstMarkedBit();
5717 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5718 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5719 delta.dy * mPointerYZoomScale);
5720 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5721 distOverThreshold += 1;
5722 }
5723 }
5724
5725 // Only transition when at least two pointers have moved further than
5726 // the minimum distance threshold.
5727 if (distOverThreshold >= 2) {
5728 if (currentFingerCount > 2) {
5729 // There are more than two pointers, switch to FREEFORM.
5730#if DEBUG_GESTURES
5731 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5732 currentFingerCount);
5733#endif
5734 *outCancelPreviousGesture = true;
5735 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5736 } else {
5737 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005738 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 uint32_t id1 = idBits.clearFirstMarkedBit();
5740 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005741 const RawPointerData::Pointer& p1 =
5742 mCurrentRawState.rawPointerData.pointerForId(id1);
5743 const RawPointerData::Pointer& p2 =
5744 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5746 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5747 // There are two pointers but they are too far apart for a SWIPE,
5748 // switch to FREEFORM.
5749#if DEBUG_GESTURES
5750 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5751 mutualDistance, mPointerGestureMaxSwipeWidth);
5752#endif
5753 *outCancelPreviousGesture = true;
5754 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5755 } else {
5756 // There are two pointers. Wait for both pointers to start moving
5757 // before deciding whether this is a SWIPE or FREEFORM gesture.
5758 float dist1 = dist[id1];
5759 float dist2 = dist[id2];
5760 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5761 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5762 // Calculate the dot product of the displacement vectors.
5763 // When the vectors are oriented in approximately the same direction,
5764 // the angle betweeen them is near zero and the cosine of the angle
5765 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5766 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5767 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5768 float dx1 = delta1.dx * mPointerXZoomScale;
5769 float dy1 = delta1.dy * mPointerYZoomScale;
5770 float dx2 = delta2.dx * mPointerXZoomScale;
5771 float dy2 = delta2.dy * mPointerYZoomScale;
5772 float dot = dx1 * dx2 + dy1 * dy2;
5773 float cosine = dot / (dist1 * dist2); // denominator always > 0
5774 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5775 // Pointers are moving in the same direction. Switch to SWIPE.
5776#if DEBUG_GESTURES
5777 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5778 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5779 "cosine %0.3f >= %0.3f",
5780 dist1, mConfig.pointerGestureMultitouchMinDistance,
5781 dist2, mConfig.pointerGestureMultitouchMinDistance,
5782 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5783#endif
5784 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5785 } else {
5786 // Pointers are moving in different directions. Switch to FREEFORM.
5787#if DEBUG_GESTURES
5788 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5789 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5790 "cosine %0.3f < %0.3f",
5791 dist1, mConfig.pointerGestureMultitouchMinDistance,
5792 dist2, mConfig.pointerGestureMultitouchMinDistance,
5793 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5794#endif
5795 *outCancelPreviousGesture = true;
5796 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5797 }
5798 }
5799 }
5800 }
5801 }
5802 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5803 // Switch from SWIPE to FREEFORM if additional pointers go down.
5804 // Cancel previous gesture.
5805 if (currentFingerCount > 2) {
5806#if DEBUG_GESTURES
5807 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5808 currentFingerCount);
5809#endif
5810 *outCancelPreviousGesture = true;
5811 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5812 }
5813 }
5814
5815 // Move the reference points based on the overall group motion of the fingers
5816 // except in PRESS mode while waiting for a transition to occur.
5817 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5818 && (commonDeltaX || commonDeltaY)) {
5819 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5820 uint32_t id = idBits.clearFirstMarkedBit();
5821 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5822 delta.dx = 0;
5823 delta.dy = 0;
5824 }
5825
5826 mPointerGesture.referenceTouchX += commonDeltaX;
5827 mPointerGesture.referenceTouchY += commonDeltaY;
5828
5829 commonDeltaX *= mPointerXMovementScale;
5830 commonDeltaY *= mPointerYMovementScale;
5831
5832 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5833 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5834
5835 mPointerGesture.referenceGestureX += commonDeltaX;
5836 mPointerGesture.referenceGestureY += commonDeltaY;
5837 }
5838
5839 // Report gestures.
5840 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5841 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5842 // PRESS or SWIPE mode.
5843#if DEBUG_GESTURES
5844 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5845 "activeGestureId=%d, currentTouchPointerCount=%d",
5846 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5847#endif
5848 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5849
5850 mPointerGesture.currentGestureIdBits.clear();
5851 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5852 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5853 mPointerGesture.currentGestureProperties[0].clear();
5854 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5855 mPointerGesture.currentGestureProperties[0].toolType =
5856 AMOTION_EVENT_TOOL_TYPE_FINGER;
5857 mPointerGesture.currentGestureCoords[0].clear();
5858 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5859 mPointerGesture.referenceGestureX);
5860 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5861 mPointerGesture.referenceGestureY);
5862 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5863 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5864 // FREEFORM mode.
5865#if DEBUG_GESTURES
5866 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5867 "activeGestureId=%d, currentTouchPointerCount=%d",
5868 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5869#endif
5870 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5871
5872 mPointerGesture.currentGestureIdBits.clear();
5873
5874 BitSet32 mappedTouchIdBits;
5875 BitSet32 usedGestureIdBits;
5876 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5877 // Initially, assign the active gesture id to the active touch point
5878 // if there is one. No other touch id bits are mapped yet.
5879 if (!*outCancelPreviousGesture) {
5880 mappedTouchIdBits.markBit(activeTouchId);
5881 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5882 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5883 mPointerGesture.activeGestureId;
5884 } else {
5885 mPointerGesture.activeGestureId = -1;
5886 }
5887 } else {
5888 // Otherwise, assume we mapped all touches from the previous frame.
5889 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07005890 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
5891 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5893
5894 // Check whether we need to choose a new active gesture id because the
5895 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07005896 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
5897 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 !upTouchIdBits.isEmpty(); ) {
5899 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5900 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5901 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5902 mPointerGesture.activeGestureId = -1;
5903 break;
5904 }
5905 }
5906 }
5907
5908#if DEBUG_GESTURES
5909 ALOGD("Gestures: FREEFORM follow up "
5910 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5911 "activeGestureId=%d",
5912 mappedTouchIdBits.value, usedGestureIdBits.value,
5913 mPointerGesture.activeGestureId);
5914#endif
5915
Michael Wright842500e2015-03-13 17:32:02 -07005916 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917 for (uint32_t i = 0; i < currentFingerCount; i++) {
5918 uint32_t touchId = idBits.clearFirstMarkedBit();
5919 uint32_t gestureId;
5920 if (!mappedTouchIdBits.hasBit(touchId)) {
5921 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5922 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5923#if DEBUG_GESTURES
5924 ALOGD("Gestures: FREEFORM "
5925 "new mapping for touch id %d -> gesture id %d",
5926 touchId, gestureId);
5927#endif
5928 } else {
5929 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5930#if DEBUG_GESTURES
5931 ALOGD("Gestures: FREEFORM "
5932 "existing mapping for touch id %d -> gesture id %d",
5933 touchId, gestureId);
5934#endif
5935 }
5936 mPointerGesture.currentGestureIdBits.markBit(gestureId);
5937 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5938
5939 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07005940 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5942 * mPointerXZoomScale;
5943 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5944 * mPointerYZoomScale;
5945 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5946
5947 mPointerGesture.currentGestureProperties[i].clear();
5948 mPointerGesture.currentGestureProperties[i].id = gestureId;
5949 mPointerGesture.currentGestureProperties[i].toolType =
5950 AMOTION_EVENT_TOOL_TYPE_FINGER;
5951 mPointerGesture.currentGestureCoords[i].clear();
5952 mPointerGesture.currentGestureCoords[i].setAxisValue(
5953 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5954 mPointerGesture.currentGestureCoords[i].setAxisValue(
5955 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5956 mPointerGesture.currentGestureCoords[i].setAxisValue(
5957 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5958 }
5959
5960 if (mPointerGesture.activeGestureId < 0) {
5961 mPointerGesture.activeGestureId =
5962 mPointerGesture.currentGestureIdBits.firstMarkedBit();
5963#if DEBUG_GESTURES
5964 ALOGD("Gestures: FREEFORM new "
5965 "activeGestureId=%d", mPointerGesture.activeGestureId);
5966#endif
5967 }
5968 }
5969 }
5970
Michael Wright842500e2015-03-13 17:32:02 -07005971 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972
5973#if DEBUG_GESTURES
5974 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5975 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5976 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5977 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5978 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5979 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5980 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5981 uint32_t id = idBits.clearFirstMarkedBit();
5982 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5983 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5984 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5985 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
5986 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5987 id, index, properties.toolType,
5988 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5989 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5990 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5991 }
5992 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5993 uint32_t id = idBits.clearFirstMarkedBit();
5994 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5995 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5996 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5997 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
5998 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5999 id, index, properties.toolType,
6000 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6001 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6002 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6003 }
6004#endif
6005 return true;
6006}
6007
6008void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6009 mPointerSimple.currentCoords.clear();
6010 mPointerSimple.currentProperties.clear();
6011
6012 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006013 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6014 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6015 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6016 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6017 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 mPointerController->setPosition(x, y);
6019
Michael Wright842500e2015-03-13 17:32:02 -07006020 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006021 down = !hovering;
6022
6023 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006024 mPointerSimple.currentCoords.copyFrom(
6025 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6027 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6028 mPointerSimple.currentProperties.id = 0;
6029 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006030 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 } else {
6032 down = false;
6033 hovering = false;
6034 }
6035
6036 dispatchPointerSimple(when, policyFlags, down, hovering);
6037}
6038
6039void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6040 abortPointerSimple(when, policyFlags);
6041}
6042
6043void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6044 mPointerSimple.currentCoords.clear();
6045 mPointerSimple.currentProperties.clear();
6046
6047 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006048 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6049 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6050 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006051 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006052 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6053 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006054 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006055 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006057 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006058 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059 * mPointerYMovementScale;
6060
6061 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6062 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6063
6064 mPointerController->move(deltaX, deltaY);
6065 } else {
6066 mPointerVelocityControl.reset();
6067 }
6068
Michael Wright842500e2015-03-13 17:32:02 -07006069 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070 hovering = !down;
6071
6072 float x, y;
6073 mPointerController->getPosition(&x, &y);
6074 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006075 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6077 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6078 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6079 hovering ? 0.0f : 1.0f);
6080 mPointerSimple.currentProperties.id = 0;
6081 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006082 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 } else {
6084 mPointerVelocityControl.reset();
6085
6086 down = false;
6087 hovering = false;
6088 }
6089
6090 dispatchPointerSimple(when, policyFlags, down, hovering);
6091}
6092
6093void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6094 abortPointerSimple(when, policyFlags);
6095
6096 mPointerVelocityControl.reset();
6097}
6098
6099void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6100 bool down, bool hovering) {
6101 int32_t metaState = getContext()->getGlobalMetaState();
6102
6103 if (mPointerController != NULL) {
6104 if (down || hovering) {
6105 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6106 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006107 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6109 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6110 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6111 }
6112 }
6113
6114 if (mPointerSimple.down && !down) {
6115 mPointerSimple.down = false;
6116
6117 // Send up.
6118 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006119 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120 mViewport.displayId,
6121 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6122 mOrientedXPrecision, mOrientedYPrecision,
6123 mPointerSimple.downTime);
6124 getListener()->notifyMotion(&args);
6125 }
6126
6127 if (mPointerSimple.hovering && !hovering) {
6128 mPointerSimple.hovering = false;
6129
6130 // Send hover exit.
6131 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006132 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133 mViewport.displayId,
6134 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6135 mOrientedXPrecision, mOrientedYPrecision,
6136 mPointerSimple.downTime);
6137 getListener()->notifyMotion(&args);
6138 }
6139
6140 if (down) {
6141 if (!mPointerSimple.down) {
6142 mPointerSimple.down = true;
6143 mPointerSimple.downTime = when;
6144
6145 // Send down.
6146 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006147 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148 mViewport.displayId,
6149 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6150 mOrientedXPrecision, mOrientedYPrecision,
6151 mPointerSimple.downTime);
6152 getListener()->notifyMotion(&args);
6153 }
6154
6155 // Send move.
6156 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006157 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006158 mViewport.displayId,
6159 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6160 mOrientedXPrecision, mOrientedYPrecision,
6161 mPointerSimple.downTime);
6162 getListener()->notifyMotion(&args);
6163 }
6164
6165 if (hovering) {
6166 if (!mPointerSimple.hovering) {
6167 mPointerSimple.hovering = true;
6168
6169 // Send hover enter.
6170 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006171 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006172 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006173 mViewport.displayId,
6174 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6175 mOrientedXPrecision, mOrientedYPrecision,
6176 mPointerSimple.downTime);
6177 getListener()->notifyMotion(&args);
6178 }
6179
6180 // Send hover move.
6181 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006182 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006183 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184 mViewport.displayId,
6185 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6186 mOrientedXPrecision, mOrientedYPrecision,
6187 mPointerSimple.downTime);
6188 getListener()->notifyMotion(&args);
6189 }
6190
Michael Wright842500e2015-03-13 17:32:02 -07006191 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6192 float vscroll = mCurrentRawState.rawVScroll;
6193 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194 mWheelYVelocityControl.move(when, NULL, &vscroll);
6195 mWheelXVelocityControl.move(when, &hscroll, NULL);
6196
6197 // Send scroll.
6198 PointerCoords pointerCoords;
6199 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6200 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6201 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6202
6203 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006204 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205 mViewport.displayId,
6206 1, &mPointerSimple.currentProperties, &pointerCoords,
6207 mOrientedXPrecision, mOrientedYPrecision,
6208 mPointerSimple.downTime);
6209 getListener()->notifyMotion(&args);
6210 }
6211
6212 // Save state.
6213 if (down || hovering) {
6214 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6215 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6216 } else {
6217 mPointerSimple.reset();
6218 }
6219}
6220
6221void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6222 mPointerSimple.currentCoords.clear();
6223 mPointerSimple.currentProperties.clear();
6224
6225 dispatchPointerSimple(when, policyFlags, false, false);
6226}
6227
6228void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006229 int32_t action, int32_t actionButton, int32_t flags,
6230 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006232 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6233 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 PointerCoords pointerCoords[MAX_POINTERS];
6235 PointerProperties pointerProperties[MAX_POINTERS];
6236 uint32_t pointerCount = 0;
6237 while (!idBits.isEmpty()) {
6238 uint32_t id = idBits.clearFirstMarkedBit();
6239 uint32_t index = idToIndex[id];
6240 pointerProperties[pointerCount].copyFrom(properties[index]);
6241 pointerCoords[pointerCount].copyFrom(coords[index]);
6242
6243 if (changedId >= 0 && id == uint32_t(changedId)) {
6244 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6245 }
6246
6247 pointerCount += 1;
6248 }
6249
6250 ALOG_ASSERT(pointerCount != 0);
6251
6252 if (changedId >= 0 && pointerCount == 1) {
6253 // Replace initial down and final up action.
6254 // We can compare the action without masking off the changed pointer index
6255 // because we know the index is 0.
6256 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6257 action = AMOTION_EVENT_ACTION_DOWN;
6258 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6259 action = AMOTION_EVENT_ACTION_UP;
6260 } else {
6261 // Can't happen.
6262 ALOG_ASSERT(false);
6263 }
6264 }
6265
6266 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006267 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6269 xPrecision, yPrecision, downTime);
6270 getListener()->notifyMotion(&args);
6271}
6272
6273bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6274 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6275 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6276 BitSet32 idBits) const {
6277 bool changed = false;
6278 while (!idBits.isEmpty()) {
6279 uint32_t id = idBits.clearFirstMarkedBit();
6280 uint32_t inIndex = inIdToIndex[id];
6281 uint32_t outIndex = outIdToIndex[id];
6282
6283 const PointerProperties& curInProperties = inProperties[inIndex];
6284 const PointerCoords& curInCoords = inCoords[inIndex];
6285 PointerProperties& curOutProperties = outProperties[outIndex];
6286 PointerCoords& curOutCoords = outCoords[outIndex];
6287
6288 if (curInProperties != curOutProperties) {
6289 curOutProperties.copyFrom(curInProperties);
6290 changed = true;
6291 }
6292
6293 if (curInCoords != curOutCoords) {
6294 curOutCoords.copyFrom(curInCoords);
6295 changed = true;
6296 }
6297 }
6298 return changed;
6299}
6300
6301void TouchInputMapper::fadePointer() {
6302 if (mPointerController != NULL) {
6303 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6304 }
6305}
6306
Jeff Brownc9aa6282015-02-11 19:03:28 -08006307void TouchInputMapper::cancelTouch(nsecs_t when) {
6308 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006309 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006310}
6311
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6313 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6314 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6315}
6316
6317const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6318 int32_t x, int32_t y) {
6319 size_t numVirtualKeys = mVirtualKeys.size();
6320 for (size_t i = 0; i < numVirtualKeys; i++) {
6321 const VirtualKey& virtualKey = mVirtualKeys[i];
6322
6323#if DEBUG_VIRTUAL_KEYS
6324 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6325 "left=%d, top=%d, right=%d, bottom=%d",
6326 x, y,
6327 virtualKey.keyCode, virtualKey.scanCode,
6328 virtualKey.hitLeft, virtualKey.hitTop,
6329 virtualKey.hitRight, virtualKey.hitBottom);
6330#endif
6331
6332 if (virtualKey.isHit(x, y)) {
6333 return & virtualKey;
6334 }
6335 }
6336
6337 return NULL;
6338}
6339
Michael Wright842500e2015-03-13 17:32:02 -07006340void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6341 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6342 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343
Michael Wright842500e2015-03-13 17:32:02 -07006344 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345
6346 if (currentPointerCount == 0) {
6347 // No pointers to assign.
6348 return;
6349 }
6350
6351 if (lastPointerCount == 0) {
6352 // All pointers are new.
6353 for (uint32_t i = 0; i < currentPointerCount; i++) {
6354 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006355 current->rawPointerData.pointers[i].id = id;
6356 current->rawPointerData.idToIndex[id] = i;
6357 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358 }
6359 return;
6360 }
6361
6362 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006363 && current->rawPointerData.pointers[0].toolType
6364 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006366 uint32_t id = last->rawPointerData.pointers[0].id;
6367 current->rawPointerData.pointers[0].id = id;
6368 current->rawPointerData.idToIndex[id] = 0;
6369 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370 return;
6371 }
6372
6373 // General case.
6374 // We build a heap of squared euclidean distances between current and last pointers
6375 // associated with the current and last pointer indices. Then, we find the best
6376 // match (by distance) for each current pointer.
6377 // The pointers must have the same tool type but it is possible for them to
6378 // transition from hovering to touching or vice-versa while retaining the same id.
6379 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6380
6381 uint32_t heapSize = 0;
6382 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6383 currentPointerIndex++) {
6384 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6385 lastPointerIndex++) {
6386 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006387 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006389 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 if (currentPointer.toolType == lastPointer.toolType) {
6391 int64_t deltaX = currentPointer.x - lastPointer.x;
6392 int64_t deltaY = currentPointer.y - lastPointer.y;
6393
6394 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6395
6396 // Insert new element into the heap (sift up).
6397 heap[heapSize].currentPointerIndex = currentPointerIndex;
6398 heap[heapSize].lastPointerIndex = lastPointerIndex;
6399 heap[heapSize].distance = distance;
6400 heapSize += 1;
6401 }
6402 }
6403 }
6404
6405 // Heapify
6406 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6407 startIndex -= 1;
6408 for (uint32_t parentIndex = startIndex; ;) {
6409 uint32_t childIndex = parentIndex * 2 + 1;
6410 if (childIndex >= heapSize) {
6411 break;
6412 }
6413
6414 if (childIndex + 1 < heapSize
6415 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6416 childIndex += 1;
6417 }
6418
6419 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6420 break;
6421 }
6422
6423 swap(heap[parentIndex], heap[childIndex]);
6424 parentIndex = childIndex;
6425 }
6426 }
6427
6428#if DEBUG_POINTER_ASSIGNMENT
6429 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6430 for (size_t i = 0; i < heapSize; i++) {
6431 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6432 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6433 heap[i].distance);
6434 }
6435#endif
6436
6437 // Pull matches out by increasing order of distance.
6438 // To avoid reassigning pointers that have already been matched, the loop keeps track
6439 // of which last and current pointers have been matched using the matchedXXXBits variables.
6440 // It also tracks the used pointer id bits.
6441 BitSet32 matchedLastBits(0);
6442 BitSet32 matchedCurrentBits(0);
6443 BitSet32 usedIdBits(0);
6444 bool first = true;
6445 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6446 while (heapSize > 0) {
6447 if (first) {
6448 // The first time through the loop, we just consume the root element of
6449 // the heap (the one with smallest distance).
6450 first = false;
6451 } else {
6452 // Previous iterations consumed the root element of the heap.
6453 // Pop root element off of the heap (sift down).
6454 heap[0] = heap[heapSize];
6455 for (uint32_t parentIndex = 0; ;) {
6456 uint32_t childIndex = parentIndex * 2 + 1;
6457 if (childIndex >= heapSize) {
6458 break;
6459 }
6460
6461 if (childIndex + 1 < heapSize
6462 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6463 childIndex += 1;
6464 }
6465
6466 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6467 break;
6468 }
6469
6470 swap(heap[parentIndex], heap[childIndex]);
6471 parentIndex = childIndex;
6472 }
6473
6474#if DEBUG_POINTER_ASSIGNMENT
6475 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6476 for (size_t i = 0; i < heapSize; i++) {
6477 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6478 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6479 heap[i].distance);
6480 }
6481#endif
6482 }
6483
6484 heapSize -= 1;
6485
6486 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6487 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6488
6489 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6490 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6491
6492 matchedCurrentBits.markBit(currentPointerIndex);
6493 matchedLastBits.markBit(lastPointerIndex);
6494
Michael Wright842500e2015-03-13 17:32:02 -07006495 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6496 current->rawPointerData.pointers[currentPointerIndex].id = id;
6497 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6498 current->rawPointerData.markIdBit(id,
6499 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006500 usedIdBits.markBit(id);
6501
6502#if DEBUG_POINTER_ASSIGNMENT
6503 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6504 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6505#endif
6506 break;
6507 }
6508 }
6509
6510 // Assign fresh ids to pointers that were not matched in the process.
6511 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6512 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6513 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6514
Michael Wright842500e2015-03-13 17:32:02 -07006515 current->rawPointerData.pointers[currentPointerIndex].id = id;
6516 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6517 current->rawPointerData.markIdBit(id,
6518 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006519
6520#if DEBUG_POINTER_ASSIGNMENT
6521 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6522 currentPointerIndex, id);
6523#endif
6524 }
6525}
6526
6527int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6528 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6529 return AKEY_STATE_VIRTUAL;
6530 }
6531
6532 size_t numVirtualKeys = mVirtualKeys.size();
6533 for (size_t i = 0; i < numVirtualKeys; i++) {
6534 const VirtualKey& virtualKey = mVirtualKeys[i];
6535 if (virtualKey.keyCode == keyCode) {
6536 return AKEY_STATE_UP;
6537 }
6538 }
6539
6540 return AKEY_STATE_UNKNOWN;
6541}
6542
6543int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6544 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6545 return AKEY_STATE_VIRTUAL;
6546 }
6547
6548 size_t numVirtualKeys = mVirtualKeys.size();
6549 for (size_t i = 0; i < numVirtualKeys; i++) {
6550 const VirtualKey& virtualKey = mVirtualKeys[i];
6551 if (virtualKey.scanCode == scanCode) {
6552 return AKEY_STATE_UP;
6553 }
6554 }
6555
6556 return AKEY_STATE_UNKNOWN;
6557}
6558
6559bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6560 const int32_t* keyCodes, uint8_t* outFlags) {
6561 size_t numVirtualKeys = mVirtualKeys.size();
6562 for (size_t i = 0; i < numVirtualKeys; i++) {
6563 const VirtualKey& virtualKey = mVirtualKeys[i];
6564
6565 for (size_t i = 0; i < numCodes; i++) {
6566 if (virtualKey.keyCode == keyCodes[i]) {
6567 outFlags[i] = 1;
6568 }
6569 }
6570 }
6571
6572 return true;
6573}
6574
6575
6576// --- SingleTouchInputMapper ---
6577
6578SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6579 TouchInputMapper(device) {
6580}
6581
6582SingleTouchInputMapper::~SingleTouchInputMapper() {
6583}
6584
6585void SingleTouchInputMapper::reset(nsecs_t when) {
6586 mSingleTouchMotionAccumulator.reset(getDevice());
6587
6588 TouchInputMapper::reset(when);
6589}
6590
6591void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6592 TouchInputMapper::process(rawEvent);
6593
6594 mSingleTouchMotionAccumulator.process(rawEvent);
6595}
6596
Michael Wright842500e2015-03-13 17:32:02 -07006597void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006598 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006599 outState->rawPointerData.pointerCount = 1;
6600 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006601
6602 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6603 && (mTouchButtonAccumulator.isHovering()
6604 || (mRawPointerAxes.pressure.valid
6605 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006606 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006607
Michael Wright842500e2015-03-13 17:32:02 -07006608 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006609 outPointer.id = 0;
6610 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6611 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6612 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6613 outPointer.touchMajor = 0;
6614 outPointer.touchMinor = 0;
6615 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6616 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6617 outPointer.orientation = 0;
6618 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6619 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6620 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6621 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6622 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6623 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6624 }
6625 outPointer.isHovering = isHovering;
6626 }
6627}
6628
6629void SingleTouchInputMapper::configureRawPointerAxes() {
6630 TouchInputMapper::configureRawPointerAxes();
6631
6632 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6633 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6634 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6635 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6636 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6637 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6638 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6639}
6640
6641bool SingleTouchInputMapper::hasStylus() const {
6642 return mTouchButtonAccumulator.hasStylus();
6643}
6644
6645
6646// --- MultiTouchInputMapper ---
6647
6648MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6649 TouchInputMapper(device) {
6650}
6651
6652MultiTouchInputMapper::~MultiTouchInputMapper() {
6653}
6654
6655void MultiTouchInputMapper::reset(nsecs_t when) {
6656 mMultiTouchMotionAccumulator.reset(getDevice());
6657
6658 mPointerIdBits.clear();
6659
6660 TouchInputMapper::reset(when);
6661}
6662
6663void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6664 TouchInputMapper::process(rawEvent);
6665
6666 mMultiTouchMotionAccumulator.process(rawEvent);
6667}
6668
Michael Wright842500e2015-03-13 17:32:02 -07006669void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006670 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6671 size_t outCount = 0;
6672 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006673 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006674
6675 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6676 const MultiTouchMotionAccumulator::Slot* inSlot =
6677 mMultiTouchMotionAccumulator.getSlot(inIndex);
6678 if (!inSlot->isInUse()) {
6679 continue;
6680 }
6681
6682 if (outCount >= MAX_POINTERS) {
6683#if DEBUG_POINTERS
6684 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6685 "ignoring the rest.",
6686 getDeviceName().string(), MAX_POINTERS);
6687#endif
6688 break; // too many fingers!
6689 }
6690
Michael Wright842500e2015-03-13 17:32:02 -07006691 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006692 outPointer.x = inSlot->getX();
6693 outPointer.y = inSlot->getY();
6694 outPointer.pressure = inSlot->getPressure();
6695 outPointer.touchMajor = inSlot->getTouchMajor();
6696 outPointer.touchMinor = inSlot->getTouchMinor();
6697 outPointer.toolMajor = inSlot->getToolMajor();
6698 outPointer.toolMinor = inSlot->getToolMinor();
6699 outPointer.orientation = inSlot->getOrientation();
6700 outPointer.distance = inSlot->getDistance();
6701 outPointer.tiltX = 0;
6702 outPointer.tiltY = 0;
6703
6704 outPointer.toolType = inSlot->getToolType();
6705 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6706 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6707 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6708 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6709 }
6710 }
6711
6712 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6713 && (mTouchButtonAccumulator.isHovering()
6714 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6715 outPointer.isHovering = isHovering;
6716
6717 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006718 if (mHavePointerIds) {
6719 int32_t trackingId = inSlot->getTrackingId();
6720 int32_t id = -1;
6721 if (trackingId >= 0) {
6722 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6723 uint32_t n = idBits.clearFirstMarkedBit();
6724 if (mPointerTrackingIdMap[n] == trackingId) {
6725 id = n;
6726 }
6727 }
6728
6729 if (id < 0 && !mPointerIdBits.isFull()) {
6730 id = mPointerIdBits.markFirstUnmarkedBit();
6731 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006732 }
Michael Wright842500e2015-03-13 17:32:02 -07006733 }
gaoshang1a632de2016-08-24 10:23:50 +08006734 if (id < 0) {
6735 mHavePointerIds = false;
6736 outState->rawPointerData.clearIdBits();
6737 newPointerIdBits.clear();
6738 } else {
6739 outPointer.id = id;
6740 outState->rawPointerData.idToIndex[id] = outCount;
6741 outState->rawPointerData.markIdBit(id, isHovering);
6742 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006743 }
Michael Wright842500e2015-03-13 17:32:02 -07006744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006745 outCount += 1;
6746 }
6747
Michael Wright842500e2015-03-13 17:32:02 -07006748 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006749 mPointerIdBits = newPointerIdBits;
6750
6751 mMultiTouchMotionAccumulator.finishSync();
6752}
6753
6754void MultiTouchInputMapper::configureRawPointerAxes() {
6755 TouchInputMapper::configureRawPointerAxes();
6756
6757 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6758 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6759 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6760 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6761 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6762 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6763 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6764 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6765 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6766 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6767 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6768
6769 if (mRawPointerAxes.trackingId.valid
6770 && mRawPointerAxes.slot.valid
6771 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6772 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6773 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006774 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6775 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006776 getDeviceName().string(), slotCount, MAX_SLOTS);
6777 slotCount = MAX_SLOTS;
6778 }
6779 mMultiTouchMotionAccumulator.configure(getDevice(),
6780 slotCount, true /*usingSlotsProtocol*/);
6781 } else {
6782 mMultiTouchMotionAccumulator.configure(getDevice(),
6783 MAX_POINTERS, false /*usingSlotsProtocol*/);
6784 }
6785}
6786
6787bool MultiTouchInputMapper::hasStylus() const {
6788 return mMultiTouchMotionAccumulator.hasStylus()
6789 || mTouchButtonAccumulator.hasStylus();
6790}
6791
Michael Wright842500e2015-03-13 17:32:02 -07006792// --- ExternalStylusInputMapper
6793
6794ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6795 InputMapper(device) {
6796
6797}
6798
6799uint32_t ExternalStylusInputMapper::getSources() {
6800 return AINPUT_SOURCE_STYLUS;
6801}
6802
6803void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6804 InputMapper::populateDeviceInfo(info);
6805 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6806 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6807}
6808
6809void ExternalStylusInputMapper::dump(String8& dump) {
6810 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6811 dump.append(INDENT3 "Raw Stylus Axes:\n");
6812 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6813 dump.append(INDENT3 "Stylus State:\n");
6814 dumpStylusState(dump, mStylusState);
6815}
6816
6817void ExternalStylusInputMapper::configure(nsecs_t when,
6818 const InputReaderConfiguration* config, uint32_t changes) {
6819 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6820 mTouchButtonAccumulator.configure(getDevice());
6821}
6822
6823void ExternalStylusInputMapper::reset(nsecs_t when) {
6824 InputDevice* device = getDevice();
6825 mSingleTouchMotionAccumulator.reset(device);
6826 mTouchButtonAccumulator.reset(device);
6827 InputMapper::reset(when);
6828}
6829
6830void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6831 mSingleTouchMotionAccumulator.process(rawEvent);
6832 mTouchButtonAccumulator.process(rawEvent);
6833
6834 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6835 sync(rawEvent->when);
6836 }
6837}
6838
6839void ExternalStylusInputMapper::sync(nsecs_t when) {
6840 mStylusState.clear();
6841
6842 mStylusState.when = when;
6843
Michael Wright45ccacf2015-04-21 19:01:58 +01006844 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6845 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6846 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6847 }
6848
Michael Wright842500e2015-03-13 17:32:02 -07006849 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6850 if (mRawPressureAxis.valid) {
6851 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6852 } else if (mTouchButtonAccumulator.isToolActive()) {
6853 mStylusState.pressure = 1.0f;
6854 } else {
6855 mStylusState.pressure = 0.0f;
6856 }
6857
6858 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07006859
6860 mContext->dispatchExternalStylusState(mStylusState);
6861}
6862
Michael Wrightd02c5b62014-02-10 15:10:22 -08006863
6864// --- JoystickInputMapper ---
6865
6866JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6867 InputMapper(device) {
6868}
6869
6870JoystickInputMapper::~JoystickInputMapper() {
6871}
6872
6873uint32_t JoystickInputMapper::getSources() {
6874 return AINPUT_SOURCE_JOYSTICK;
6875}
6876
6877void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6878 InputMapper::populateDeviceInfo(info);
6879
6880 for (size_t i = 0; i < mAxes.size(); i++) {
6881 const Axis& axis = mAxes.valueAt(i);
6882 addMotionRange(axis.axisInfo.axis, axis, info);
6883
6884 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6885 addMotionRange(axis.axisInfo.highAxis, axis, info);
6886
6887 }
6888 }
6889}
6890
6891void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6892 InputDeviceInfo* info) {
6893 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6894 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6895 /* In order to ease the transition for developers from using the old axes
6896 * to the newer, more semantically correct axes, we'll continue to register
6897 * the old axes as duplicates of their corresponding new ones. */
6898 int32_t compatAxis = getCompatAxis(axisId);
6899 if (compatAxis >= 0) {
6900 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6901 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6902 }
6903}
6904
6905/* A mapping from axes the joystick actually has to the axes that should be
6906 * artificially created for compatibility purposes.
6907 * Returns -1 if no compatibility axis is needed. */
6908int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6909 switch(axis) {
6910 case AMOTION_EVENT_AXIS_LTRIGGER:
6911 return AMOTION_EVENT_AXIS_BRAKE;
6912 case AMOTION_EVENT_AXIS_RTRIGGER:
6913 return AMOTION_EVENT_AXIS_GAS;
6914 }
6915 return -1;
6916}
6917
6918void JoystickInputMapper::dump(String8& dump) {
6919 dump.append(INDENT2 "Joystick Input Mapper:\n");
6920
6921 dump.append(INDENT3 "Axes:\n");
6922 size_t numAxes = mAxes.size();
6923 for (size_t i = 0; i < numAxes; i++) {
6924 const Axis& axis = mAxes.valueAt(i);
6925 const char* label = getAxisLabel(axis.axisInfo.axis);
6926 if (label) {
6927 dump.appendFormat(INDENT4 "%s", label);
6928 } else {
6929 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6930 }
6931 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6932 label = getAxisLabel(axis.axisInfo.highAxis);
6933 if (label) {
6934 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6935 } else {
6936 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6937 axis.axisInfo.splitValue);
6938 }
6939 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6940 dump.append(" (invert)");
6941 }
6942
6943 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6944 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6945 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
6946 "highScale=%0.5f, highOffset=%0.5f\n",
6947 axis.scale, axis.offset, axis.highScale, axis.highOffset);
6948 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
6949 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6950 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6951 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6952 }
6953}
6954
6955void JoystickInputMapper::configure(nsecs_t when,
6956 const InputReaderConfiguration* config, uint32_t changes) {
6957 InputMapper::configure(when, config, changes);
6958
6959 if (!changes) { // first time only
6960 // Collect all axes.
6961 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6962 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6963 & INPUT_DEVICE_CLASS_JOYSTICK)) {
6964 continue; // axis must be claimed by a different device
6965 }
6966
6967 RawAbsoluteAxisInfo rawAxisInfo;
6968 getAbsoluteAxisInfo(abs, &rawAxisInfo);
6969 if (rawAxisInfo.valid) {
6970 // Map axis.
6971 AxisInfo axisInfo;
6972 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6973 if (!explicitlyMapped) {
6974 // Axis is not explicitly mapped, will choose a generic axis later.
6975 axisInfo.mode = AxisInfo::MODE_NORMAL;
6976 axisInfo.axis = -1;
6977 }
6978
6979 // Apply flat override.
6980 int32_t rawFlat = axisInfo.flatOverride < 0
6981 ? rawAxisInfo.flat : axisInfo.flatOverride;
6982
6983 // Calculate scaling factors and limits.
6984 Axis axis;
6985 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6986 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6987 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6988 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6989 scale, 0.0f, highScale, 0.0f,
6990 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6991 rawAxisInfo.resolution * scale);
6992 } else if (isCenteredAxis(axisInfo.axis)) {
6993 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6994 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6995 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6996 scale, offset, scale, offset,
6997 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6998 rawAxisInfo.resolution * scale);
6999 } else {
7000 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7001 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7002 scale, 0.0f, scale, 0.0f,
7003 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7004 rawAxisInfo.resolution * scale);
7005 }
7006
7007 // To eliminate noise while the joystick is at rest, filter out small variations
7008 // in axis values up front.
7009 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7010
7011 mAxes.add(abs, axis);
7012 }
7013 }
7014
7015 // If there are too many axes, start dropping them.
7016 // Prefer to keep explicitly mapped axes.
7017 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007018 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007019 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7020 pruneAxes(true);
7021 pruneAxes(false);
7022 }
7023
7024 // Assign generic axis ids to remaining axes.
7025 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7026 size_t numAxes = mAxes.size();
7027 for (size_t i = 0; i < numAxes; i++) {
7028 Axis& axis = mAxes.editValueAt(i);
7029 if (axis.axisInfo.axis < 0) {
7030 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7031 && haveAxis(nextGenericAxisId)) {
7032 nextGenericAxisId += 1;
7033 }
7034
7035 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7036 axis.axisInfo.axis = nextGenericAxisId;
7037 nextGenericAxisId += 1;
7038 } else {
7039 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7040 "have already been assigned to other axes.",
7041 getDeviceName().string(), mAxes.keyAt(i));
7042 mAxes.removeItemsAt(i--);
7043 numAxes -= 1;
7044 }
7045 }
7046 }
7047 }
7048}
7049
7050bool JoystickInputMapper::haveAxis(int32_t axisId) {
7051 size_t numAxes = mAxes.size();
7052 for (size_t i = 0; i < numAxes; i++) {
7053 const Axis& axis = mAxes.valueAt(i);
7054 if (axis.axisInfo.axis == axisId
7055 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7056 && axis.axisInfo.highAxis == axisId)) {
7057 return true;
7058 }
7059 }
7060 return false;
7061}
7062
7063void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7064 size_t i = mAxes.size();
7065 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7066 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7067 continue;
7068 }
7069 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7070 getDeviceName().string(), mAxes.keyAt(i));
7071 mAxes.removeItemsAt(i);
7072 }
7073}
7074
7075bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7076 switch (axis) {
7077 case AMOTION_EVENT_AXIS_X:
7078 case AMOTION_EVENT_AXIS_Y:
7079 case AMOTION_EVENT_AXIS_Z:
7080 case AMOTION_EVENT_AXIS_RX:
7081 case AMOTION_EVENT_AXIS_RY:
7082 case AMOTION_EVENT_AXIS_RZ:
7083 case AMOTION_EVENT_AXIS_HAT_X:
7084 case AMOTION_EVENT_AXIS_HAT_Y:
7085 case AMOTION_EVENT_AXIS_ORIENTATION:
7086 case AMOTION_EVENT_AXIS_RUDDER:
7087 case AMOTION_EVENT_AXIS_WHEEL:
7088 return true;
7089 default:
7090 return false;
7091 }
7092}
7093
7094void JoystickInputMapper::reset(nsecs_t when) {
7095 // Recenter all axes.
7096 size_t numAxes = mAxes.size();
7097 for (size_t i = 0; i < numAxes; i++) {
7098 Axis& axis = mAxes.editValueAt(i);
7099 axis.resetValue();
7100 }
7101
7102 InputMapper::reset(when);
7103}
7104
7105void JoystickInputMapper::process(const RawEvent* rawEvent) {
7106 switch (rawEvent->type) {
7107 case EV_ABS: {
7108 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7109 if (index >= 0) {
7110 Axis& axis = mAxes.editValueAt(index);
7111 float newValue, highNewValue;
7112 switch (axis.axisInfo.mode) {
7113 case AxisInfo::MODE_INVERT:
7114 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7115 * axis.scale + axis.offset;
7116 highNewValue = 0.0f;
7117 break;
7118 case AxisInfo::MODE_SPLIT:
7119 if (rawEvent->value < axis.axisInfo.splitValue) {
7120 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7121 * axis.scale + axis.offset;
7122 highNewValue = 0.0f;
7123 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7124 newValue = 0.0f;
7125 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7126 * axis.highScale + axis.highOffset;
7127 } else {
7128 newValue = 0.0f;
7129 highNewValue = 0.0f;
7130 }
7131 break;
7132 default:
7133 newValue = rawEvent->value * axis.scale + axis.offset;
7134 highNewValue = 0.0f;
7135 break;
7136 }
7137 axis.newValue = newValue;
7138 axis.highNewValue = highNewValue;
7139 }
7140 break;
7141 }
7142
7143 case EV_SYN:
7144 switch (rawEvent->code) {
7145 case SYN_REPORT:
7146 sync(rawEvent->when, false /*force*/);
7147 break;
7148 }
7149 break;
7150 }
7151}
7152
7153void JoystickInputMapper::sync(nsecs_t when, bool force) {
7154 if (!filterAxes(force)) {
7155 return;
7156 }
7157
7158 int32_t metaState = mContext->getGlobalMetaState();
7159 int32_t buttonState = 0;
7160
7161 PointerProperties pointerProperties;
7162 pointerProperties.clear();
7163 pointerProperties.id = 0;
7164 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7165
7166 PointerCoords pointerCoords;
7167 pointerCoords.clear();
7168
7169 size_t numAxes = mAxes.size();
7170 for (size_t i = 0; i < numAxes; i++) {
7171 const Axis& axis = mAxes.valueAt(i);
7172 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7173 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7174 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7175 axis.highCurrentValue);
7176 }
7177 }
7178
7179 // Moving a joystick axis should not wake the device because joysticks can
7180 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7181 // button will likely wake the device.
7182 // TODO: Use the input device configuration to control this behavior more finely.
7183 uint32_t policyFlags = 0;
7184
7185 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007186 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007187 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7188 getListener()->notifyMotion(&args);
7189}
7190
7191void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7192 int32_t axis, float value) {
7193 pointerCoords->setAxisValue(axis, value);
7194 /* In order to ease the transition for developers from using the old axes
7195 * to the newer, more semantically correct axes, we'll continue to produce
7196 * values for the old axes as mirrors of the value of their corresponding
7197 * new axes. */
7198 int32_t compatAxis = getCompatAxis(axis);
7199 if (compatAxis >= 0) {
7200 pointerCoords->setAxisValue(compatAxis, value);
7201 }
7202}
7203
7204bool JoystickInputMapper::filterAxes(bool force) {
7205 bool atLeastOneSignificantChange = force;
7206 size_t numAxes = mAxes.size();
7207 for (size_t i = 0; i < numAxes; i++) {
7208 Axis& axis = mAxes.editValueAt(i);
7209 if (force || hasValueChangedSignificantly(axis.filter,
7210 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7211 axis.currentValue = axis.newValue;
7212 atLeastOneSignificantChange = true;
7213 }
7214 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7215 if (force || hasValueChangedSignificantly(axis.filter,
7216 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7217 axis.highCurrentValue = axis.highNewValue;
7218 atLeastOneSignificantChange = true;
7219 }
7220 }
7221 }
7222 return atLeastOneSignificantChange;
7223}
7224
7225bool JoystickInputMapper::hasValueChangedSignificantly(
7226 float filter, float newValue, float currentValue, float min, float max) {
7227 if (newValue != currentValue) {
7228 // Filter out small changes in value unless the value is converging on the axis
7229 // bounds or center point. This is intended to reduce the amount of information
7230 // sent to applications by particularly noisy joysticks (such as PS3).
7231 if (fabs(newValue - currentValue) > filter
7232 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7233 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7234 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7235 return true;
7236 }
7237 }
7238 return false;
7239}
7240
7241bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7242 float filter, float newValue, float currentValue, float thresholdValue) {
7243 float newDistance = fabs(newValue - thresholdValue);
7244 if (newDistance < filter) {
7245 float oldDistance = fabs(currentValue - thresholdValue);
7246 if (newDistance < oldDistance) {
7247 return true;
7248 }
7249 }
7250 return false;
7251}
7252
7253} // namespace android