blob: 8af90386961794c5f2ce80b809a7899f84df8d4d [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
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700791bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
792 AutoMutex _l(mLock);
793
794 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
795 if (deviceIndex >= 0) {
796 InputDevice* device = mDevices.valueAt(deviceIndex);
797 return device->isEnabled();
798 }
799 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
800 return false;
801}
802
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803void InputReader::dump(String8& dump) {
804 AutoMutex _l(mLock);
805
806 mEventHub->dump(dump);
807 dump.append("\n");
808
809 dump.append("Input Reader State:\n");
810
811 for (size_t i = 0; i < mDevices.size(); i++) {
812 mDevices.valueAt(i)->dump(dump);
813 }
814
815 dump.append(INDENT "Configuration:\n");
816 dump.append(INDENT2 "ExcludedDeviceNames: [");
817 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
818 if (i != 0) {
819 dump.append(", ");
820 }
821 dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
822 }
823 dump.append("]\n");
824 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
825 mConfig.virtualKeyQuietTime * 0.000001f);
826
827 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
828 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
829 mConfig.pointerVelocityControlParameters.scale,
830 mConfig.pointerVelocityControlParameters.lowThreshold,
831 mConfig.pointerVelocityControlParameters.highThreshold,
832 mConfig.pointerVelocityControlParameters.acceleration);
833
834 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
835 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
836 mConfig.wheelVelocityControlParameters.scale,
837 mConfig.wheelVelocityControlParameters.lowThreshold,
838 mConfig.wheelVelocityControlParameters.highThreshold,
839 mConfig.wheelVelocityControlParameters.acceleration);
840
841 dump.appendFormat(INDENT2 "PointerGesture:\n");
842 dump.appendFormat(INDENT3 "Enabled: %s\n",
843 toString(mConfig.pointerGesturesEnabled));
844 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
845 mConfig.pointerGestureQuietInterval * 0.000001f);
846 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
847 mConfig.pointerGestureDragMinSwitchSpeed);
848 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
849 mConfig.pointerGestureTapInterval * 0.000001f);
850 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
851 mConfig.pointerGestureTapDragInterval * 0.000001f);
852 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
853 mConfig.pointerGestureTapSlop);
854 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
855 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
856 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
857 mConfig.pointerGestureMultitouchMinDistance);
858 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
859 mConfig.pointerGestureSwipeTransitionAngleCosine);
860 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
861 mConfig.pointerGestureSwipeMaxWidthRatio);
862 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
863 mConfig.pointerGestureMovementSpeedRatio);
864 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
865 mConfig.pointerGestureZoomSpeedRatio);
866}
867
868void InputReader::monitor() {
869 // Acquire and release the lock to ensure that the reader has not deadlocked.
870 mLock.lock();
871 mEventHub->wake();
872 mReaderIsAliveCondition.wait(mLock);
873 mLock.unlock();
874
875 // Check the EventHub
876 mEventHub->monitor();
877}
878
879
880// --- InputReader::ContextImpl ---
881
882InputReader::ContextImpl::ContextImpl(InputReader* reader) :
883 mReader(reader) {
884}
885
886void InputReader::ContextImpl::updateGlobalMetaState() {
887 // lock is already held by the input loop
888 mReader->updateGlobalMetaStateLocked();
889}
890
891int32_t InputReader::ContextImpl::getGlobalMetaState() {
892 // lock is already held by the input loop
893 return mReader->getGlobalMetaStateLocked();
894}
895
896void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
897 // lock is already held by the input loop
898 mReader->disableVirtualKeysUntilLocked(time);
899}
900
901bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
902 InputDevice* device, int32_t keyCode, int32_t scanCode) {
903 // lock is already held by the input loop
904 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
905}
906
907void InputReader::ContextImpl::fadePointer() {
908 // lock is already held by the input loop
909 mReader->fadePointerLocked();
910}
911
912void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
913 // lock is already held by the input loop
914 mReader->requestTimeoutAtTimeLocked(when);
915}
916
917int32_t InputReader::ContextImpl::bumpGeneration() {
918 // lock is already held by the input loop
919 return mReader->bumpGenerationLocked();
920}
921
Michael Wright842500e2015-03-13 17:32:02 -0700922void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
923 // lock is already held by whatever called refreshConfigurationLocked
924 mReader->getExternalStylusDevicesLocked(outDevices);
925}
926
927void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
928 mReader->dispatchExternalStylusState(state);
929}
930
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
932 return mReader->mPolicy.get();
933}
934
935InputListenerInterface* InputReader::ContextImpl::getListener() {
936 return mReader->mQueuedListener.get();
937}
938
939EventHubInterface* InputReader::ContextImpl::getEventHub() {
940 return mReader->mEventHub.get();
941}
942
943
944// --- InputReaderThread ---
945
946InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
947 Thread(/*canCallJava*/ true), mReader(reader) {
948}
949
950InputReaderThread::~InputReaderThread() {
951}
952
953bool InputReaderThread::threadLoop() {
954 mReader->loopOnce();
955 return true;
956}
957
958
959// --- InputDevice ---
960
961InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
962 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
963 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
964 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700965 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966}
967
968InputDevice::~InputDevice() {
969 size_t numMappers = mMappers.size();
970 for (size_t i = 0; i < numMappers; i++) {
971 delete mMappers[i];
972 }
973 mMappers.clear();
974}
975
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700976bool InputDevice::isEnabled() {
977 return getEventHub()->isDeviceEnabled(mId);
978}
979
980void InputDevice::setEnabled(bool enabled, nsecs_t when) {
981 if (isEnabled() == enabled) {
982 return;
983 }
984
985 if (enabled) {
986 getEventHub()->enableDevice(mId);
987 reset(when);
988 } else {
989 reset(when);
990 getEventHub()->disableDevice(mId);
991 }
992 // Must change generation to flag this device as changed
993 bumpGeneration();
994}
995
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996void InputDevice::dump(String8& dump) {
997 InputDeviceInfo deviceInfo;
998 getDeviceInfo(& deviceInfo);
999
1000 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
1001 deviceInfo.getDisplayName().string());
1002 dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
1003 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Tim Kilbourn063ff532015-04-08 10:26:18 -07001004 dump.appendFormat(INDENT2 "HasMic: %s\n", toString(mHasMic));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1006 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
1007
1008 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1009 if (!ranges.isEmpty()) {
1010 dump.append(INDENT2 "Motion Ranges:\n");
1011 for (size_t i = 0; i < ranges.size(); i++) {
1012 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1013 const char* label = getAxisLabel(range.axis);
1014 char name[32];
1015 if (label) {
1016 strncpy(name, label, sizeof(name));
1017 name[sizeof(name) - 1] = '\0';
1018 } else {
1019 snprintf(name, sizeof(name), "%d", range.axis);
1020 }
1021 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
1022 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1023 name, range.source, range.min, range.max, range.flat, range.fuzz,
1024 range.resolution);
1025 }
1026 }
1027
1028 size_t numMappers = mMappers.size();
1029 for (size_t i = 0; i < numMappers; i++) {
1030 InputMapper* mapper = mMappers[i];
1031 mapper->dump(dump);
1032 }
1033}
1034
1035void InputDevice::addMapper(InputMapper* mapper) {
1036 mMappers.add(mapper);
1037}
1038
1039void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1040 mSources = 0;
1041
1042 if (!isIgnored()) {
1043 if (!changes) { // first time only
1044 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1045 }
1046
1047 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1048 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1049 sp<KeyCharacterMap> keyboardLayout =
1050 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1051 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1052 bumpGeneration();
1053 }
1054 }
1055 }
1056
1057 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1058 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1059 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1060 if (mAlias != alias) {
1061 mAlias = alias;
1062 bumpGeneration();
1063 }
1064 }
1065 }
1066
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001067 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1068 ssize_t index = config->disabledDevices.indexOf(mId);
1069 bool enabled = index < 0;
1070 setEnabled(enabled, when);
1071 }
1072
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 size_t numMappers = mMappers.size();
1074 for (size_t i = 0; i < numMappers; i++) {
1075 InputMapper* mapper = mMappers[i];
1076 mapper->configure(when, config, changes);
1077 mSources |= mapper->getSources();
1078 }
1079 }
1080}
1081
1082void InputDevice::reset(nsecs_t when) {
1083 size_t numMappers = mMappers.size();
1084 for (size_t i = 0; i < numMappers; i++) {
1085 InputMapper* mapper = mMappers[i];
1086 mapper->reset(when);
1087 }
1088
1089 mContext->updateGlobalMetaState();
1090
1091 notifyReset(when);
1092}
1093
1094void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1095 // Process all of the events in order for each mapper.
1096 // We cannot simply ask each mapper to process them in bulk because mappers may
1097 // have side-effects that must be interleaved. For example, joystick movement events and
1098 // gamepad button presses are handled by different mappers but they should be dispatched
1099 // in the order received.
1100 size_t numMappers = mMappers.size();
1101 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
1102#if DEBUG_RAW_EVENTS
1103 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
1104 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1105 rawEvent->when);
1106#endif
1107
1108 if (mDropUntilNextSync) {
1109 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1110 mDropUntilNextSync = false;
1111#if DEBUG_RAW_EVENTS
1112 ALOGD("Recovered from input event buffer overrun.");
1113#endif
1114 } else {
1115#if DEBUG_RAW_EVENTS
1116 ALOGD("Dropped input event while waiting for next input sync.");
1117#endif
1118 }
1119 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1120 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1121 mDropUntilNextSync = true;
1122 reset(rawEvent->when);
1123 } else {
1124 for (size_t i = 0; i < numMappers; i++) {
1125 InputMapper* mapper = mMappers[i];
1126 mapper->process(rawEvent);
1127 }
1128 }
1129 }
1130}
1131
1132void InputDevice::timeoutExpired(nsecs_t when) {
1133 size_t numMappers = mMappers.size();
1134 for (size_t i = 0; i < numMappers; i++) {
1135 InputMapper* mapper = mMappers[i];
1136 mapper->timeoutExpired(when);
1137 }
1138}
1139
Michael Wright842500e2015-03-13 17:32:02 -07001140void InputDevice::updateExternalStylusState(const StylusState& state) {
1141 size_t numMappers = mMappers.size();
1142 for (size_t i = 0; i < numMappers; i++) {
1143 InputMapper* mapper = mMappers[i];
1144 mapper->updateExternalStylusState(state);
1145 }
1146}
1147
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1149 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001150 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 size_t numMappers = mMappers.size();
1152 for (size_t i = 0; i < numMappers; i++) {
1153 InputMapper* mapper = mMappers[i];
1154 mapper->populateDeviceInfo(outDeviceInfo);
1155 }
1156}
1157
1158int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1159 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1160}
1161
1162int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1163 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1164}
1165
1166int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1167 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1168}
1169
1170int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1171 int32_t result = AKEY_STATE_UNKNOWN;
1172 size_t numMappers = mMappers.size();
1173 for (size_t i = 0; i < numMappers; i++) {
1174 InputMapper* mapper = mMappers[i];
1175 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1176 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1177 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1178 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1179 if (currentResult >= AKEY_STATE_DOWN) {
1180 return currentResult;
1181 } else if (currentResult == AKEY_STATE_UP) {
1182 result = currentResult;
1183 }
1184 }
1185 }
1186 return result;
1187}
1188
1189bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1190 const int32_t* keyCodes, uint8_t* outFlags) {
1191 bool result = false;
1192 size_t numMappers = mMappers.size();
1193 for (size_t i = 0; i < numMappers; i++) {
1194 InputMapper* mapper = mMappers[i];
1195 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1196 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1197 }
1198 }
1199 return result;
1200}
1201
1202void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1203 int32_t token) {
1204 size_t numMappers = mMappers.size();
1205 for (size_t i = 0; i < numMappers; i++) {
1206 InputMapper* mapper = mMappers[i];
1207 mapper->vibrate(pattern, patternSize, repeat, token);
1208 }
1209}
1210
1211void InputDevice::cancelVibrate(int32_t token) {
1212 size_t numMappers = mMappers.size();
1213 for (size_t i = 0; i < numMappers; i++) {
1214 InputMapper* mapper = mMappers[i];
1215 mapper->cancelVibrate(token);
1216 }
1217}
1218
Jeff Brownc9aa6282015-02-11 19:03:28 -08001219void InputDevice::cancelTouch(nsecs_t when) {
1220 size_t numMappers = mMappers.size();
1221 for (size_t i = 0; i < numMappers; i++) {
1222 InputMapper* mapper = mMappers[i];
1223 mapper->cancelTouch(when);
1224 }
1225}
1226
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227int32_t InputDevice::getMetaState() {
1228 int32_t result = 0;
1229 size_t numMappers = mMappers.size();
1230 for (size_t i = 0; i < numMappers; i++) {
1231 InputMapper* mapper = mMappers[i];
1232 result |= mapper->getMetaState();
1233 }
1234 return result;
1235}
1236
Andrii Kulian763a3a42016-03-08 10:46:16 -08001237void InputDevice::updateMetaState(int32_t keyCode) {
1238 size_t numMappers = mMappers.size();
1239 for (size_t i = 0; i < numMappers; i++) {
1240 mMappers[i]->updateMetaState(keyCode);
1241 }
1242}
1243
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244void InputDevice::fadePointer() {
1245 size_t numMappers = mMappers.size();
1246 for (size_t i = 0; i < numMappers; i++) {
1247 InputMapper* mapper = mMappers[i];
1248 mapper->fadePointer();
1249 }
1250}
1251
1252void InputDevice::bumpGeneration() {
1253 mGeneration = mContext->bumpGeneration();
1254}
1255
1256void InputDevice::notifyReset(nsecs_t when) {
1257 NotifyDeviceResetArgs args(when, mId);
1258 mContext->getListener()->notifyDeviceReset(&args);
1259}
1260
1261
1262// --- CursorButtonAccumulator ---
1263
1264CursorButtonAccumulator::CursorButtonAccumulator() {
1265 clearButtons();
1266}
1267
1268void CursorButtonAccumulator::reset(InputDevice* device) {
1269 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1270 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1271 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1272 mBtnBack = device->isKeyPressed(BTN_BACK);
1273 mBtnSide = device->isKeyPressed(BTN_SIDE);
1274 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1275 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1276 mBtnTask = device->isKeyPressed(BTN_TASK);
1277}
1278
1279void CursorButtonAccumulator::clearButtons() {
1280 mBtnLeft = 0;
1281 mBtnRight = 0;
1282 mBtnMiddle = 0;
1283 mBtnBack = 0;
1284 mBtnSide = 0;
1285 mBtnForward = 0;
1286 mBtnExtra = 0;
1287 mBtnTask = 0;
1288}
1289
1290void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1291 if (rawEvent->type == EV_KEY) {
1292 switch (rawEvent->code) {
1293 case BTN_LEFT:
1294 mBtnLeft = rawEvent->value;
1295 break;
1296 case BTN_RIGHT:
1297 mBtnRight = rawEvent->value;
1298 break;
1299 case BTN_MIDDLE:
1300 mBtnMiddle = rawEvent->value;
1301 break;
1302 case BTN_BACK:
1303 mBtnBack = rawEvent->value;
1304 break;
1305 case BTN_SIDE:
1306 mBtnSide = rawEvent->value;
1307 break;
1308 case BTN_FORWARD:
1309 mBtnForward = rawEvent->value;
1310 break;
1311 case BTN_EXTRA:
1312 mBtnExtra = rawEvent->value;
1313 break;
1314 case BTN_TASK:
1315 mBtnTask = rawEvent->value;
1316 break;
1317 }
1318 }
1319}
1320
1321uint32_t CursorButtonAccumulator::getButtonState() const {
1322 uint32_t result = 0;
1323 if (mBtnLeft) {
1324 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1325 }
1326 if (mBtnRight) {
1327 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1328 }
1329 if (mBtnMiddle) {
1330 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1331 }
1332 if (mBtnBack || mBtnSide) {
1333 result |= AMOTION_EVENT_BUTTON_BACK;
1334 }
1335 if (mBtnForward || mBtnExtra) {
1336 result |= AMOTION_EVENT_BUTTON_FORWARD;
1337 }
1338 return result;
1339}
1340
1341
1342// --- CursorMotionAccumulator ---
1343
1344CursorMotionAccumulator::CursorMotionAccumulator() {
1345 clearRelativeAxes();
1346}
1347
1348void CursorMotionAccumulator::reset(InputDevice* device) {
1349 clearRelativeAxes();
1350}
1351
1352void CursorMotionAccumulator::clearRelativeAxes() {
1353 mRelX = 0;
1354 mRelY = 0;
1355}
1356
1357void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1358 if (rawEvent->type == EV_REL) {
1359 switch (rawEvent->code) {
1360 case REL_X:
1361 mRelX = rawEvent->value;
1362 break;
1363 case REL_Y:
1364 mRelY = rawEvent->value;
1365 break;
1366 }
1367 }
1368}
1369
1370void CursorMotionAccumulator::finishSync() {
1371 clearRelativeAxes();
1372}
1373
1374
1375// --- CursorScrollAccumulator ---
1376
1377CursorScrollAccumulator::CursorScrollAccumulator() :
1378 mHaveRelWheel(false), mHaveRelHWheel(false) {
1379 clearRelativeAxes();
1380}
1381
1382void CursorScrollAccumulator::configure(InputDevice* device) {
1383 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1384 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1385}
1386
1387void CursorScrollAccumulator::reset(InputDevice* device) {
1388 clearRelativeAxes();
1389}
1390
1391void CursorScrollAccumulator::clearRelativeAxes() {
1392 mRelWheel = 0;
1393 mRelHWheel = 0;
1394}
1395
1396void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1397 if (rawEvent->type == EV_REL) {
1398 switch (rawEvent->code) {
1399 case REL_WHEEL:
1400 mRelWheel = rawEvent->value;
1401 break;
1402 case REL_HWHEEL:
1403 mRelHWheel = rawEvent->value;
1404 break;
1405 }
1406 }
1407}
1408
1409void CursorScrollAccumulator::finishSync() {
1410 clearRelativeAxes();
1411}
1412
1413
1414// --- TouchButtonAccumulator ---
1415
1416TouchButtonAccumulator::TouchButtonAccumulator() :
1417 mHaveBtnTouch(false), mHaveStylus(false) {
1418 clearButtons();
1419}
1420
1421void TouchButtonAccumulator::configure(InputDevice* device) {
1422 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1423 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1424 || device->hasKey(BTN_TOOL_RUBBER)
1425 || device->hasKey(BTN_TOOL_BRUSH)
1426 || device->hasKey(BTN_TOOL_PENCIL)
1427 || device->hasKey(BTN_TOOL_AIRBRUSH);
1428}
1429
1430void TouchButtonAccumulator::reset(InputDevice* device) {
1431 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1432 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001433 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1434 mBtnStylus2 =
1435 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1437 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1438 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1439 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1440 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1441 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1442 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1443 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1444 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1445 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1446 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1447}
1448
1449void TouchButtonAccumulator::clearButtons() {
1450 mBtnTouch = 0;
1451 mBtnStylus = 0;
1452 mBtnStylus2 = 0;
1453 mBtnToolFinger = 0;
1454 mBtnToolPen = 0;
1455 mBtnToolRubber = 0;
1456 mBtnToolBrush = 0;
1457 mBtnToolPencil = 0;
1458 mBtnToolAirbrush = 0;
1459 mBtnToolMouse = 0;
1460 mBtnToolLens = 0;
1461 mBtnToolDoubleTap = 0;
1462 mBtnToolTripleTap = 0;
1463 mBtnToolQuadTap = 0;
1464}
1465
1466void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1467 if (rawEvent->type == EV_KEY) {
1468 switch (rawEvent->code) {
1469 case BTN_TOUCH:
1470 mBtnTouch = rawEvent->value;
1471 break;
1472 case BTN_STYLUS:
1473 mBtnStylus = rawEvent->value;
1474 break;
1475 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001476 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 mBtnStylus2 = rawEvent->value;
1478 break;
1479 case BTN_TOOL_FINGER:
1480 mBtnToolFinger = rawEvent->value;
1481 break;
1482 case BTN_TOOL_PEN:
1483 mBtnToolPen = rawEvent->value;
1484 break;
1485 case BTN_TOOL_RUBBER:
1486 mBtnToolRubber = rawEvent->value;
1487 break;
1488 case BTN_TOOL_BRUSH:
1489 mBtnToolBrush = rawEvent->value;
1490 break;
1491 case BTN_TOOL_PENCIL:
1492 mBtnToolPencil = rawEvent->value;
1493 break;
1494 case BTN_TOOL_AIRBRUSH:
1495 mBtnToolAirbrush = rawEvent->value;
1496 break;
1497 case BTN_TOOL_MOUSE:
1498 mBtnToolMouse = rawEvent->value;
1499 break;
1500 case BTN_TOOL_LENS:
1501 mBtnToolLens = rawEvent->value;
1502 break;
1503 case BTN_TOOL_DOUBLETAP:
1504 mBtnToolDoubleTap = rawEvent->value;
1505 break;
1506 case BTN_TOOL_TRIPLETAP:
1507 mBtnToolTripleTap = rawEvent->value;
1508 break;
1509 case BTN_TOOL_QUADTAP:
1510 mBtnToolQuadTap = rawEvent->value;
1511 break;
1512 }
1513 }
1514}
1515
1516uint32_t TouchButtonAccumulator::getButtonState() const {
1517 uint32_t result = 0;
1518 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001519 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 }
1521 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001522 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 }
1524 return result;
1525}
1526
1527int32_t TouchButtonAccumulator::getToolType() const {
1528 if (mBtnToolMouse || mBtnToolLens) {
1529 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1530 }
1531 if (mBtnToolRubber) {
1532 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1533 }
1534 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1535 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1536 }
1537 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1538 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1539 }
1540 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1541}
1542
1543bool TouchButtonAccumulator::isToolActive() const {
1544 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1545 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1546 || mBtnToolMouse || mBtnToolLens
1547 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1548}
1549
1550bool TouchButtonAccumulator::isHovering() const {
1551 return mHaveBtnTouch && !mBtnTouch;
1552}
1553
1554bool TouchButtonAccumulator::hasStylus() const {
1555 return mHaveStylus;
1556}
1557
1558
1559// --- RawPointerAxes ---
1560
1561RawPointerAxes::RawPointerAxes() {
1562 clear();
1563}
1564
1565void RawPointerAxes::clear() {
1566 x.clear();
1567 y.clear();
1568 pressure.clear();
1569 touchMajor.clear();
1570 touchMinor.clear();
1571 toolMajor.clear();
1572 toolMinor.clear();
1573 orientation.clear();
1574 distance.clear();
1575 tiltX.clear();
1576 tiltY.clear();
1577 trackingId.clear();
1578 slot.clear();
1579}
1580
1581
1582// --- RawPointerData ---
1583
1584RawPointerData::RawPointerData() {
1585 clear();
1586}
1587
1588void RawPointerData::clear() {
1589 pointerCount = 0;
1590 clearIdBits();
1591}
1592
1593void RawPointerData::copyFrom(const RawPointerData& other) {
1594 pointerCount = other.pointerCount;
1595 hoveringIdBits = other.hoveringIdBits;
1596 touchingIdBits = other.touchingIdBits;
1597
1598 for (uint32_t i = 0; i < pointerCount; i++) {
1599 pointers[i] = other.pointers[i];
1600
1601 int id = pointers[i].id;
1602 idToIndex[id] = other.idToIndex[id];
1603 }
1604}
1605
1606void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1607 float x = 0, y = 0;
1608 uint32_t count = touchingIdBits.count();
1609 if (count) {
1610 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1611 uint32_t id = idBits.clearFirstMarkedBit();
1612 const Pointer& pointer = pointerForId(id);
1613 x += pointer.x;
1614 y += pointer.y;
1615 }
1616 x /= count;
1617 y /= count;
1618 }
1619 *outX = x;
1620 *outY = y;
1621}
1622
1623
1624// --- CookedPointerData ---
1625
1626CookedPointerData::CookedPointerData() {
1627 clear();
1628}
1629
1630void CookedPointerData::clear() {
1631 pointerCount = 0;
1632 hoveringIdBits.clear();
1633 touchingIdBits.clear();
1634}
1635
1636void CookedPointerData::copyFrom(const CookedPointerData& other) {
1637 pointerCount = other.pointerCount;
1638 hoveringIdBits = other.hoveringIdBits;
1639 touchingIdBits = other.touchingIdBits;
1640
1641 for (uint32_t i = 0; i < pointerCount; i++) {
1642 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1643 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1644
1645 int id = pointerProperties[i].id;
1646 idToIndex[id] = other.idToIndex[id];
1647 }
1648}
1649
1650
1651// --- SingleTouchMotionAccumulator ---
1652
1653SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1654 clearAbsoluteAxes();
1655}
1656
1657void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1658 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1659 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1660 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1661 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1662 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1663 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1664 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1665}
1666
1667void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1668 mAbsX = 0;
1669 mAbsY = 0;
1670 mAbsPressure = 0;
1671 mAbsToolWidth = 0;
1672 mAbsDistance = 0;
1673 mAbsTiltX = 0;
1674 mAbsTiltY = 0;
1675}
1676
1677void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1678 if (rawEvent->type == EV_ABS) {
1679 switch (rawEvent->code) {
1680 case ABS_X:
1681 mAbsX = rawEvent->value;
1682 break;
1683 case ABS_Y:
1684 mAbsY = rawEvent->value;
1685 break;
1686 case ABS_PRESSURE:
1687 mAbsPressure = rawEvent->value;
1688 break;
1689 case ABS_TOOL_WIDTH:
1690 mAbsToolWidth = rawEvent->value;
1691 break;
1692 case ABS_DISTANCE:
1693 mAbsDistance = rawEvent->value;
1694 break;
1695 case ABS_TILT_X:
1696 mAbsTiltX = rawEvent->value;
1697 break;
1698 case ABS_TILT_Y:
1699 mAbsTiltY = rawEvent->value;
1700 break;
1701 }
1702 }
1703}
1704
1705
1706// --- MultiTouchMotionAccumulator ---
1707
1708MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1709 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1710 mHaveStylus(false) {
1711}
1712
1713MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1714 delete[] mSlots;
1715}
1716
1717void MultiTouchMotionAccumulator::configure(InputDevice* device,
1718 size_t slotCount, bool usingSlotsProtocol) {
1719 mSlotCount = slotCount;
1720 mUsingSlotsProtocol = usingSlotsProtocol;
1721 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1722
1723 delete[] mSlots;
1724 mSlots = new Slot[slotCount];
1725}
1726
1727void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1728 // Unfortunately there is no way to read the initial contents of the slots.
1729 // So when we reset the accumulator, we must assume they are all zeroes.
1730 if (mUsingSlotsProtocol) {
1731 // Query the driver for the current slot index and use it as the initial slot
1732 // before we start reading events from the device. It is possible that the
1733 // current slot index will not be the same as it was when the first event was
1734 // written into the evdev buffer, which means the input mapper could start
1735 // out of sync with the initial state of the events in the evdev buffer.
1736 // In the extremely unlikely case that this happens, the data from
1737 // two slots will be confused until the next ABS_MT_SLOT event is received.
1738 // This can cause the touch point to "jump", but at least there will be
1739 // no stuck touches.
1740 int32_t initialSlot;
1741 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1742 ABS_MT_SLOT, &initialSlot);
1743 if (status) {
1744 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1745 initialSlot = -1;
1746 }
1747 clearSlots(initialSlot);
1748 } else {
1749 clearSlots(-1);
1750 }
1751}
1752
1753void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1754 if (mSlots) {
1755 for (size_t i = 0; i < mSlotCount; i++) {
1756 mSlots[i].clear();
1757 }
1758 }
1759 mCurrentSlot = initialSlot;
1760}
1761
1762void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1763 if (rawEvent->type == EV_ABS) {
1764 bool newSlot = false;
1765 if (mUsingSlotsProtocol) {
1766 if (rawEvent->code == ABS_MT_SLOT) {
1767 mCurrentSlot = rawEvent->value;
1768 newSlot = true;
1769 }
1770 } else if (mCurrentSlot < 0) {
1771 mCurrentSlot = 0;
1772 }
1773
1774 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1775#if DEBUG_POINTERS
1776 if (newSlot) {
1777 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1778 "should be between 0 and %d; ignoring this slot.",
1779 mCurrentSlot, mSlotCount - 1);
1780 }
1781#endif
1782 } else {
1783 Slot* slot = &mSlots[mCurrentSlot];
1784
1785 switch (rawEvent->code) {
1786 case ABS_MT_POSITION_X:
1787 slot->mInUse = true;
1788 slot->mAbsMTPositionX = rawEvent->value;
1789 break;
1790 case ABS_MT_POSITION_Y:
1791 slot->mInUse = true;
1792 slot->mAbsMTPositionY = rawEvent->value;
1793 break;
1794 case ABS_MT_TOUCH_MAJOR:
1795 slot->mInUse = true;
1796 slot->mAbsMTTouchMajor = rawEvent->value;
1797 break;
1798 case ABS_MT_TOUCH_MINOR:
1799 slot->mInUse = true;
1800 slot->mAbsMTTouchMinor = rawEvent->value;
1801 slot->mHaveAbsMTTouchMinor = true;
1802 break;
1803 case ABS_MT_WIDTH_MAJOR:
1804 slot->mInUse = true;
1805 slot->mAbsMTWidthMajor = rawEvent->value;
1806 break;
1807 case ABS_MT_WIDTH_MINOR:
1808 slot->mInUse = true;
1809 slot->mAbsMTWidthMinor = rawEvent->value;
1810 slot->mHaveAbsMTWidthMinor = true;
1811 break;
1812 case ABS_MT_ORIENTATION:
1813 slot->mInUse = true;
1814 slot->mAbsMTOrientation = rawEvent->value;
1815 break;
1816 case ABS_MT_TRACKING_ID:
1817 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1818 // The slot is no longer in use but it retains its previous contents,
1819 // which may be reused for subsequent touches.
1820 slot->mInUse = false;
1821 } else {
1822 slot->mInUse = true;
1823 slot->mAbsMTTrackingId = rawEvent->value;
1824 }
1825 break;
1826 case ABS_MT_PRESSURE:
1827 slot->mInUse = true;
1828 slot->mAbsMTPressure = rawEvent->value;
1829 break;
1830 case ABS_MT_DISTANCE:
1831 slot->mInUse = true;
1832 slot->mAbsMTDistance = rawEvent->value;
1833 break;
1834 case ABS_MT_TOOL_TYPE:
1835 slot->mInUse = true;
1836 slot->mAbsMTToolType = rawEvent->value;
1837 slot->mHaveAbsMTToolType = true;
1838 break;
1839 }
1840 }
1841 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1842 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1843 mCurrentSlot += 1;
1844 }
1845}
1846
1847void MultiTouchMotionAccumulator::finishSync() {
1848 if (!mUsingSlotsProtocol) {
1849 clearSlots(-1);
1850 }
1851}
1852
1853bool MultiTouchMotionAccumulator::hasStylus() const {
1854 return mHaveStylus;
1855}
1856
1857
1858// --- MultiTouchMotionAccumulator::Slot ---
1859
1860MultiTouchMotionAccumulator::Slot::Slot() {
1861 clear();
1862}
1863
1864void MultiTouchMotionAccumulator::Slot::clear() {
1865 mInUse = false;
1866 mHaveAbsMTTouchMinor = false;
1867 mHaveAbsMTWidthMinor = false;
1868 mHaveAbsMTToolType = false;
1869 mAbsMTPositionX = 0;
1870 mAbsMTPositionY = 0;
1871 mAbsMTTouchMajor = 0;
1872 mAbsMTTouchMinor = 0;
1873 mAbsMTWidthMajor = 0;
1874 mAbsMTWidthMinor = 0;
1875 mAbsMTOrientation = 0;
1876 mAbsMTTrackingId = -1;
1877 mAbsMTPressure = 0;
1878 mAbsMTDistance = 0;
1879 mAbsMTToolType = 0;
1880}
1881
1882int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1883 if (mHaveAbsMTToolType) {
1884 switch (mAbsMTToolType) {
1885 case MT_TOOL_FINGER:
1886 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1887 case MT_TOOL_PEN:
1888 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1889 }
1890 }
1891 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1892}
1893
1894
1895// --- InputMapper ---
1896
1897InputMapper::InputMapper(InputDevice* device) :
1898 mDevice(device), mContext(device->getContext()) {
1899}
1900
1901InputMapper::~InputMapper() {
1902}
1903
1904void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1905 info->addSource(getSources());
1906}
1907
1908void InputMapper::dump(String8& dump) {
1909}
1910
1911void InputMapper::configure(nsecs_t when,
1912 const InputReaderConfiguration* config, uint32_t changes) {
1913}
1914
1915void InputMapper::reset(nsecs_t when) {
1916}
1917
1918void InputMapper::timeoutExpired(nsecs_t when) {
1919}
1920
1921int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1922 return AKEY_STATE_UNKNOWN;
1923}
1924
1925int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1926 return AKEY_STATE_UNKNOWN;
1927}
1928
1929int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1930 return AKEY_STATE_UNKNOWN;
1931}
1932
1933bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1934 const int32_t* keyCodes, uint8_t* outFlags) {
1935 return false;
1936}
1937
1938void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1939 int32_t token) {
1940}
1941
1942void InputMapper::cancelVibrate(int32_t token) {
1943}
1944
Jeff Brownc9aa6282015-02-11 19:03:28 -08001945void InputMapper::cancelTouch(nsecs_t when) {
1946}
1947
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948int32_t InputMapper::getMetaState() {
1949 return 0;
1950}
1951
Andrii Kulian763a3a42016-03-08 10:46:16 -08001952void InputMapper::updateMetaState(int32_t keyCode) {
1953}
1954
Michael Wright842500e2015-03-13 17:32:02 -07001955void InputMapper::updateExternalStylusState(const StylusState& state) {
1956
1957}
1958
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959void InputMapper::fadePointer() {
1960}
1961
1962status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1963 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1964}
1965
1966void InputMapper::bumpGeneration() {
1967 mDevice->bumpGeneration();
1968}
1969
1970void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
1971 const RawAbsoluteAxisInfo& axis, const char* name) {
1972 if (axis.valid) {
1973 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
1974 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1975 } else {
1976 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1977 }
1978}
1979
Michael Wright842500e2015-03-13 17:32:02 -07001980void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
1981 dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
1982 dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
1983 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
1984 dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
1985}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986
1987// --- SwitchInputMapper ---
1988
1989SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001990 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991}
1992
1993SwitchInputMapper::~SwitchInputMapper() {
1994}
1995
1996uint32_t SwitchInputMapper::getSources() {
1997 return AINPUT_SOURCE_SWITCH;
1998}
1999
2000void SwitchInputMapper::process(const RawEvent* rawEvent) {
2001 switch (rawEvent->type) {
2002 case EV_SW:
2003 processSwitch(rawEvent->code, rawEvent->value);
2004 break;
2005
2006 case EV_SYN:
2007 if (rawEvent->code == SYN_REPORT) {
2008 sync(rawEvent->when);
2009 }
2010 }
2011}
2012
2013void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2014 if (switchCode >= 0 && switchCode < 32) {
2015 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002016 mSwitchValues |= 1 << switchCode;
2017 } else {
2018 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
2020 mUpdatedSwitchMask |= 1 << switchCode;
2021 }
2022}
2023
2024void SwitchInputMapper::sync(nsecs_t when) {
2025 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002026 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002027 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 getListener()->notifySwitch(&args);
2029
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 mUpdatedSwitchMask = 0;
2031 }
2032}
2033
2034int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2035 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2036}
2037
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002038void SwitchInputMapper::dump(String8& dump) {
2039 dump.append(INDENT2 "Switch Input Mapper:\n");
2040 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
2041}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042
2043// --- VibratorInputMapper ---
2044
2045VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2046 InputMapper(device), mVibrating(false) {
2047}
2048
2049VibratorInputMapper::~VibratorInputMapper() {
2050}
2051
2052uint32_t VibratorInputMapper::getSources() {
2053 return 0;
2054}
2055
2056void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2057 InputMapper::populateDeviceInfo(info);
2058
2059 info->setVibrator(true);
2060}
2061
2062void VibratorInputMapper::process(const RawEvent* rawEvent) {
2063 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2064}
2065
2066void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2067 int32_t token) {
2068#if DEBUG_VIBRATOR
2069 String8 patternStr;
2070 for (size_t i = 0; i < patternSize; i++) {
2071 if (i != 0) {
2072 patternStr.append(", ");
2073 }
2074 patternStr.appendFormat("%lld", pattern[i]);
2075 }
2076 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
2077 getDeviceId(), patternStr.string(), repeat, token);
2078#endif
2079
2080 mVibrating = true;
2081 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2082 mPatternSize = patternSize;
2083 mRepeat = repeat;
2084 mToken = token;
2085 mIndex = -1;
2086
2087 nextStep();
2088}
2089
2090void VibratorInputMapper::cancelVibrate(int32_t token) {
2091#if DEBUG_VIBRATOR
2092 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2093#endif
2094
2095 if (mVibrating && mToken == token) {
2096 stopVibrating();
2097 }
2098}
2099
2100void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2101 if (mVibrating) {
2102 if (when >= mNextStepTime) {
2103 nextStep();
2104 } else {
2105 getContext()->requestTimeoutAtTime(mNextStepTime);
2106 }
2107 }
2108}
2109
2110void VibratorInputMapper::nextStep() {
2111 mIndex += 1;
2112 if (size_t(mIndex) >= mPatternSize) {
2113 if (mRepeat < 0) {
2114 // We are done.
2115 stopVibrating();
2116 return;
2117 }
2118 mIndex = mRepeat;
2119 }
2120
2121 bool vibratorOn = mIndex & 1;
2122 nsecs_t duration = mPattern[mIndex];
2123 if (vibratorOn) {
2124#if DEBUG_VIBRATOR
2125 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
2126 getDeviceId(), duration);
2127#endif
2128 getEventHub()->vibrate(getDeviceId(), duration);
2129 } else {
2130#if DEBUG_VIBRATOR
2131 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2132#endif
2133 getEventHub()->cancelVibrate(getDeviceId());
2134 }
2135 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2136 mNextStepTime = now + duration;
2137 getContext()->requestTimeoutAtTime(mNextStepTime);
2138#if DEBUG_VIBRATOR
2139 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2140#endif
2141}
2142
2143void VibratorInputMapper::stopVibrating() {
2144 mVibrating = false;
2145#if DEBUG_VIBRATOR
2146 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2147#endif
2148 getEventHub()->cancelVibrate(getDeviceId());
2149}
2150
2151void VibratorInputMapper::dump(String8& dump) {
2152 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2153 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2154}
2155
2156
2157// --- KeyboardInputMapper ---
2158
2159KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2160 uint32_t source, int32_t keyboardType) :
2161 InputMapper(device), mSource(source),
2162 mKeyboardType(keyboardType) {
2163}
2164
2165KeyboardInputMapper::~KeyboardInputMapper() {
2166}
2167
2168uint32_t KeyboardInputMapper::getSources() {
2169 return mSource;
2170}
2171
2172void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2173 InputMapper::populateDeviceInfo(info);
2174
2175 info->setKeyboardType(mKeyboardType);
2176 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2177}
2178
2179void KeyboardInputMapper::dump(String8& dump) {
2180 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2181 dumpParameters(dump);
2182 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2183 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002184 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002186 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187}
2188
2189
2190void KeyboardInputMapper::configure(nsecs_t when,
2191 const InputReaderConfiguration* config, uint32_t changes) {
2192 InputMapper::configure(when, config, changes);
2193
2194 if (!changes) { // first time only
2195 // Configure basic parameters.
2196 configureParameters();
2197 }
2198
2199 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2200 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2201 DisplayViewport v;
2202 if (config->getDisplayInfo(false /*external*/, &v)) {
2203 mOrientation = v.orientation;
2204 } else {
2205 mOrientation = DISPLAY_ORIENTATION_0;
2206 }
2207 } else {
2208 mOrientation = DISPLAY_ORIENTATION_0;
2209 }
2210 }
2211}
2212
2213void KeyboardInputMapper::configureParameters() {
2214 mParameters.orientationAware = false;
2215 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
2216 mParameters.orientationAware);
2217
2218 mParameters.hasAssociatedDisplay = false;
2219 if (mParameters.orientationAware) {
2220 mParameters.hasAssociatedDisplay = true;
2221 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002222
2223 mParameters.handlesKeyRepeat = false;
2224 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.handlesKeyRepeat"),
2225 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226}
2227
2228void KeyboardInputMapper::dumpParameters(String8& dump) {
2229 dump.append(INDENT3 "Parameters:\n");
2230 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2231 toString(mParameters.hasAssociatedDisplay));
2232 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2233 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002234 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2235 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236}
2237
2238void KeyboardInputMapper::reset(nsecs_t when) {
2239 mMetaState = AMETA_NONE;
2240 mDownTime = 0;
2241 mKeyDowns.clear();
2242 mCurrentHidUsage = 0;
2243
2244 resetLedState();
2245
2246 InputMapper::reset(when);
2247}
2248
2249void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2250 switch (rawEvent->type) {
2251 case EV_KEY: {
2252 int32_t scanCode = rawEvent->code;
2253 int32_t usageCode = mCurrentHidUsage;
2254 mCurrentHidUsage = 0;
2255
2256 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002257 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 }
2259 break;
2260 }
2261 case EV_MSC: {
2262 if (rawEvent->code == MSC_SCAN) {
2263 mCurrentHidUsage = rawEvent->value;
2264 }
2265 break;
2266 }
2267 case EV_SYN: {
2268 if (rawEvent->code == SYN_REPORT) {
2269 mCurrentHidUsage = 0;
2270 }
2271 }
2272 }
2273}
2274
2275bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2276 return scanCode < BTN_MOUSE
2277 || scanCode >= KEY_OK
2278 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2279 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2280}
2281
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002282void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2283 int32_t usageCode) {
2284 int32_t keyCode;
2285 int32_t keyMetaState;
2286 uint32_t policyFlags;
2287
2288 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2289 &keyCode, &keyMetaState, &policyFlags)) {
2290 keyCode = AKEYCODE_UNKNOWN;
2291 keyMetaState = mMetaState;
2292 policyFlags = 0;
2293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294
2295 if (down) {
2296 // Rotate key codes according to orientation if needed.
2297 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2298 keyCode = rotateKeyCode(keyCode, mOrientation);
2299 }
2300
2301 // Add key down.
2302 ssize_t keyDownIndex = findKeyDown(scanCode);
2303 if (keyDownIndex >= 0) {
2304 // key repeat, be sure to use same keycode as before in case of rotation
2305 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2306 } else {
2307 // key down
2308 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2309 && mContext->shouldDropVirtualKey(when,
2310 getDevice(), keyCode, scanCode)) {
2311 return;
2312 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002313 if (policyFlags & POLICY_FLAG_GESTURE) {
2314 mDevice->cancelTouch(when);
2315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316
2317 mKeyDowns.push();
2318 KeyDown& keyDown = mKeyDowns.editTop();
2319 keyDown.keyCode = keyCode;
2320 keyDown.scanCode = scanCode;
2321 }
2322
2323 mDownTime = when;
2324 } else {
2325 // Remove key down.
2326 ssize_t keyDownIndex = findKeyDown(scanCode);
2327 if (keyDownIndex >= 0) {
2328 // key up, be sure to use same keycode as before in case of rotation
2329 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2330 mKeyDowns.removeAt(size_t(keyDownIndex));
2331 } else {
2332 // key was not actually down
2333 ALOGI("Dropping key up from device %s because the key was not down. "
2334 "keyCode=%d, scanCode=%d",
2335 getDeviceName().string(), keyCode, scanCode);
2336 return;
2337 }
2338 }
2339
Andrii Kulian763a3a42016-03-08 10:46:16 -08002340 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002341 // If global meta state changed send it along with the key.
2342 // If it has not changed then we'll use what keymap gave us,
2343 // since key replacement logic might temporarily reset a few
2344 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002345 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
2347
2348 nsecs_t downTime = mDownTime;
2349
2350 // Key down on external an keyboard should wake the device.
2351 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2352 // For internal keyboards, the key layout file should specify the policy flags for
2353 // each wake key individually.
2354 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright872db4f2014-04-22 15:03:51 -07002355 if (down && getDevice()->isExternal()) {
2356 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
2358
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002359 if (mParameters.handlesKeyRepeat) {
2360 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2361 }
2362
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2364 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002365 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 getListener()->notifyKey(&args);
2367}
2368
2369ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2370 size_t n = mKeyDowns.size();
2371 for (size_t i = 0; i < n; i++) {
2372 if (mKeyDowns[i].scanCode == scanCode) {
2373 return i;
2374 }
2375 }
2376 return -1;
2377}
2378
2379int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2380 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2381}
2382
2383int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2384 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2385}
2386
2387bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2388 const int32_t* keyCodes, uint8_t* outFlags) {
2389 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2390}
2391
2392int32_t KeyboardInputMapper::getMetaState() {
2393 return mMetaState;
2394}
2395
Andrii Kulian763a3a42016-03-08 10:46:16 -08002396void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2397 updateMetaStateIfNeeded(keyCode, false);
2398}
2399
2400bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2401 int32_t oldMetaState = mMetaState;
2402 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2403 bool metaStateChanged = oldMetaState != newMetaState;
2404 if (metaStateChanged) {
2405 mMetaState = newMetaState;
2406 updateLedState(false);
2407
2408 getContext()->updateGlobalMetaState();
2409 }
2410
2411 return metaStateChanged;
2412}
2413
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414void KeyboardInputMapper::resetLedState() {
2415 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2416 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2417 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2418
2419 updateLedState(true);
2420}
2421
2422void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2423 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2424 ledState.on = false;
2425}
2426
2427void KeyboardInputMapper::updateLedState(bool reset) {
2428 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2429 AMETA_CAPS_LOCK_ON, reset);
2430 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2431 AMETA_NUM_LOCK_ON, reset);
2432 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2433 AMETA_SCROLL_LOCK_ON, reset);
2434}
2435
2436void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2437 int32_t led, int32_t modifier, bool reset) {
2438 if (ledState.avail) {
2439 bool desiredState = (mMetaState & modifier) != 0;
2440 if (reset || ledState.on != desiredState) {
2441 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2442 ledState.on = desiredState;
2443 }
2444 }
2445}
2446
2447
2448// --- CursorInputMapper ---
2449
2450CursorInputMapper::CursorInputMapper(InputDevice* device) :
2451 InputMapper(device) {
2452}
2453
2454CursorInputMapper::~CursorInputMapper() {
2455}
2456
2457uint32_t CursorInputMapper::getSources() {
2458 return mSource;
2459}
2460
2461void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2462 InputMapper::populateDeviceInfo(info);
2463
2464 if (mParameters.mode == Parameters::MODE_POINTER) {
2465 float minX, minY, maxX, maxY;
2466 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2467 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2468 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2469 }
2470 } else {
2471 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2472 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2473 }
2474 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2475
2476 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2477 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2478 }
2479 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2480 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2481 }
2482}
2483
2484void CursorInputMapper::dump(String8& dump) {
2485 dump.append(INDENT2 "Cursor Input Mapper:\n");
2486 dumpParameters(dump);
2487 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2488 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2489 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2490 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2491 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2492 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2493 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2494 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2495 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2496 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2497 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2498 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2499 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002500 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501}
2502
2503void CursorInputMapper::configure(nsecs_t when,
2504 const InputReaderConfiguration* config, uint32_t changes) {
2505 InputMapper::configure(when, config, changes);
2506
2507 if (!changes) { // first time only
2508 mCursorScrollAccumulator.configure(getDevice());
2509
2510 // Configure basic parameters.
2511 configureParameters();
2512
2513 // Configure device mode.
2514 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002515 case Parameters::MODE_POINTER_RELATIVE:
2516 // Should not happen during first time configuration.
2517 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2518 mParameters.mode = Parameters::MODE_POINTER;
2519 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 case Parameters::MODE_POINTER:
2521 mSource = AINPUT_SOURCE_MOUSE;
2522 mXPrecision = 1.0f;
2523 mYPrecision = 1.0f;
2524 mXScale = 1.0f;
2525 mYScale = 1.0f;
2526 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2527 break;
2528 case Parameters::MODE_NAVIGATION:
2529 mSource = AINPUT_SOURCE_TRACKBALL;
2530 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2531 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2532 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2533 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2534 break;
2535 }
2536
2537 mVWheelScale = 1.0f;
2538 mHWheelScale = 1.0f;
2539 }
2540
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002541 if ((!changes && config->pointerCapture)
2542 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2543 if (config->pointerCapture) {
2544 if (mParameters.mode == Parameters::MODE_POINTER) {
2545 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2546 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2547 // Keep PointerController around in order to preserve the pointer position.
2548 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2549 } else {
2550 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2551 }
2552 } else {
2553 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2554 mParameters.mode = Parameters::MODE_POINTER;
2555 mSource = AINPUT_SOURCE_MOUSE;
2556 } else {
2557 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2558 }
2559 }
2560 bumpGeneration();
2561 if (changes) {
2562 getDevice()->notifyReset(when);
2563 }
2564 }
2565
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2567 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2568 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2569 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2570 }
2571
2572 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2573 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2574 DisplayViewport v;
2575 if (config->getDisplayInfo(false /*external*/, &v)) {
2576 mOrientation = v.orientation;
2577 } else {
2578 mOrientation = DISPLAY_ORIENTATION_0;
2579 }
2580 } else {
2581 mOrientation = DISPLAY_ORIENTATION_0;
2582 }
2583 bumpGeneration();
2584 }
2585}
2586
2587void CursorInputMapper::configureParameters() {
2588 mParameters.mode = Parameters::MODE_POINTER;
2589 String8 cursorModeString;
2590 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2591 if (cursorModeString == "navigation") {
2592 mParameters.mode = Parameters::MODE_NAVIGATION;
2593 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2594 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2595 }
2596 }
2597
2598 mParameters.orientationAware = false;
2599 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2600 mParameters.orientationAware);
2601
2602 mParameters.hasAssociatedDisplay = false;
2603 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2604 mParameters.hasAssociatedDisplay = true;
2605 }
2606}
2607
2608void CursorInputMapper::dumpParameters(String8& dump) {
2609 dump.append(INDENT3 "Parameters:\n");
2610 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2611 toString(mParameters.hasAssociatedDisplay));
2612
2613 switch (mParameters.mode) {
2614 case Parameters::MODE_POINTER:
2615 dump.append(INDENT4 "Mode: pointer\n");
2616 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002617 case Parameters::MODE_POINTER_RELATIVE:
2618 dump.append(INDENT4 "Mode: relative pointer\n");
2619 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 case Parameters::MODE_NAVIGATION:
2621 dump.append(INDENT4 "Mode: navigation\n");
2622 break;
2623 default:
2624 ALOG_ASSERT(false);
2625 }
2626
2627 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2628 toString(mParameters.orientationAware));
2629}
2630
2631void CursorInputMapper::reset(nsecs_t when) {
2632 mButtonState = 0;
2633 mDownTime = 0;
2634
2635 mPointerVelocityControl.reset();
2636 mWheelXVelocityControl.reset();
2637 mWheelYVelocityControl.reset();
2638
2639 mCursorButtonAccumulator.reset(getDevice());
2640 mCursorMotionAccumulator.reset(getDevice());
2641 mCursorScrollAccumulator.reset(getDevice());
2642
2643 InputMapper::reset(when);
2644}
2645
2646void CursorInputMapper::process(const RawEvent* rawEvent) {
2647 mCursorButtonAccumulator.process(rawEvent);
2648 mCursorMotionAccumulator.process(rawEvent);
2649 mCursorScrollAccumulator.process(rawEvent);
2650
2651 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2652 sync(rawEvent->when);
2653 }
2654}
2655
2656void CursorInputMapper::sync(nsecs_t when) {
2657 int32_t lastButtonState = mButtonState;
2658 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2659 mButtonState = currentButtonState;
2660
2661 bool wasDown = isPointerDown(lastButtonState);
2662 bool down = isPointerDown(currentButtonState);
2663 bool downChanged;
2664 if (!wasDown && down) {
2665 mDownTime = when;
2666 downChanged = true;
2667 } else if (wasDown && !down) {
2668 downChanged = true;
2669 } else {
2670 downChanged = false;
2671 }
2672 nsecs_t downTime = mDownTime;
2673 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002674 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2675 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676
2677 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2678 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2679 bool moved = deltaX != 0 || deltaY != 0;
2680
2681 // Rotate delta according to orientation if needed.
2682 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2683 && (deltaX != 0.0f || deltaY != 0.0f)) {
2684 rotateDelta(mOrientation, &deltaX, &deltaY);
2685 }
2686
2687 // Move the pointer.
2688 PointerProperties pointerProperties;
2689 pointerProperties.clear();
2690 pointerProperties.id = 0;
2691 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2692
2693 PointerCoords pointerCoords;
2694 pointerCoords.clear();
2695
2696 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2697 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2698 bool scrolled = vscroll != 0 || hscroll != 0;
2699
2700 mWheelYVelocityControl.move(when, NULL, &vscroll);
2701 mWheelXVelocityControl.move(when, &hscroll, NULL);
2702
2703 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2704
2705 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002706 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 if (moved || scrolled || buttonsChanged) {
2708 mPointerController->setPresentation(
2709 PointerControllerInterface::PRESENTATION_POINTER);
2710
2711 if (moved) {
2712 mPointerController->move(deltaX, deltaY);
2713 }
2714
2715 if (buttonsChanged) {
2716 mPointerController->setButtonState(currentButtonState);
2717 }
2718
2719 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2720 }
2721
2722 float x, y;
2723 mPointerController->getPosition(&x, &y);
2724 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2725 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002726 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2727 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 displayId = ADISPLAY_ID_DEFAULT;
2729 } else {
2730 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2731 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2732 displayId = ADISPLAY_ID_NONE;
2733 }
2734
2735 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2736
2737 // Moving an external trackball or mouse should wake the device.
2738 // We don't do this for internal cursor devices to prevent them from waking up
2739 // the device in your pocket.
2740 // TODO: Use the input device configuration to control this behavior more finely.
2741 uint32_t policyFlags = 0;
2742 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002743 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
2745
2746 // Synthesize key down from buttons if needed.
2747 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2748 policyFlags, lastButtonState, currentButtonState);
2749
2750 // Send motion event.
2751 if (downChanged || moved || scrolled || buttonsChanged) {
2752 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002753 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754 int32_t motionEventAction;
2755 if (downChanged) {
2756 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002757 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2759 } else {
2760 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2761 }
2762
Michael Wright7b159c92015-05-14 14:48:03 +01002763 if (buttonsReleased) {
2764 BitSet32 released(buttonsReleased);
2765 while (!released.isEmpty()) {
2766 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2767 buttonState &= ~actionButton;
2768 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2769 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2770 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2771 displayId, 1, &pointerProperties, &pointerCoords,
2772 mXPrecision, mYPrecision, downTime);
2773 getListener()->notifyMotion(&releaseArgs);
2774 }
2775 }
2776
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002778 motionEventAction, 0, 0, metaState, currentButtonState,
2779 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 displayId, 1, &pointerProperties, &pointerCoords,
2781 mXPrecision, mYPrecision, downTime);
2782 getListener()->notifyMotion(&args);
2783
Michael Wright7b159c92015-05-14 14:48:03 +01002784 if (buttonsPressed) {
2785 BitSet32 pressed(buttonsPressed);
2786 while (!pressed.isEmpty()) {
2787 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2788 buttonState |= actionButton;
2789 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2790 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2791 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2792 displayId, 1, &pointerProperties, &pointerCoords,
2793 mXPrecision, mYPrecision, downTime);
2794 getListener()->notifyMotion(&pressArgs);
2795 }
2796 }
2797
2798 ALOG_ASSERT(buttonState == currentButtonState);
2799
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 // Send hover move after UP to tell the application that the mouse is hovering now.
2801 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002802 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002804 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2806 displayId, 1, &pointerProperties, &pointerCoords,
2807 mXPrecision, mYPrecision, downTime);
2808 getListener()->notifyMotion(&hoverArgs);
2809 }
2810
2811 // Send scroll events.
2812 if (scrolled) {
2813 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2814 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2815
2816 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002817 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 AMOTION_EVENT_EDGE_FLAG_NONE,
2819 displayId, 1, &pointerProperties, &pointerCoords,
2820 mXPrecision, mYPrecision, downTime);
2821 getListener()->notifyMotion(&scrollArgs);
2822 }
2823 }
2824
2825 // Synthesize key up from buttons if needed.
2826 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2827 policyFlags, lastButtonState, currentButtonState);
2828
2829 mCursorMotionAccumulator.finishSync();
2830 mCursorScrollAccumulator.finishSync();
2831}
2832
2833int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2834 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2835 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2836 } else {
2837 return AKEY_STATE_UNKNOWN;
2838 }
2839}
2840
2841void CursorInputMapper::fadePointer() {
2842 if (mPointerController != NULL) {
2843 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2844 }
2845}
2846
Prashant Malani1941ff52015-08-11 18:29:28 -07002847// --- RotaryEncoderInputMapper ---
2848
2849RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2850 InputMapper(device) {
2851 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2852}
2853
2854RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2855}
2856
2857uint32_t RotaryEncoderInputMapper::getSources() {
2858 return mSource;
2859}
2860
2861void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2862 InputMapper::populateDeviceInfo(info);
2863
2864 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002865 float res = 0.0f;
2866 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2867 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2868 }
2869 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2870 mScalingFactor)) {
2871 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2872 "default to 1.0!\n");
2873 mScalingFactor = 1.0f;
2874 }
2875 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2876 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002877 }
2878}
2879
2880void RotaryEncoderInputMapper::dump(String8& dump) {
2881 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2882 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2883 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2884}
2885
2886void RotaryEncoderInputMapper::configure(nsecs_t when,
2887 const InputReaderConfiguration* config, uint32_t changes) {
2888 InputMapper::configure(when, config, changes);
2889 if (!changes) {
2890 mRotaryEncoderScrollAccumulator.configure(getDevice());
2891 }
2892}
2893
2894void RotaryEncoderInputMapper::reset(nsecs_t when) {
2895 mRotaryEncoderScrollAccumulator.reset(getDevice());
2896
2897 InputMapper::reset(when);
2898}
2899
2900void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2901 mRotaryEncoderScrollAccumulator.process(rawEvent);
2902
2903 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2904 sync(rawEvent->when);
2905 }
2906}
2907
2908void RotaryEncoderInputMapper::sync(nsecs_t when) {
2909 PointerCoords pointerCoords;
2910 pointerCoords.clear();
2911
2912 PointerProperties pointerProperties;
2913 pointerProperties.clear();
2914 pointerProperties.id = 0;
2915 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2916
2917 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2918 bool scrolled = scroll != 0;
2919
2920 // This is not a pointer, so it's not associated with a display.
2921 int32_t displayId = ADISPLAY_ID_NONE;
2922
2923 // Moving the rotary encoder should wake the device (if specified).
2924 uint32_t policyFlags = 0;
2925 if (scrolled && getDevice()->isExternal()) {
2926 policyFlags |= POLICY_FLAG_WAKE;
2927 }
2928
2929 // Send motion event.
2930 if (scrolled) {
2931 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002932 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002933
2934 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2935 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2936 AMOTION_EVENT_EDGE_FLAG_NONE,
2937 displayId, 1, &pointerProperties, &pointerCoords,
2938 0, 0, 0);
2939 getListener()->notifyMotion(&scrollArgs);
2940 }
2941
2942 mRotaryEncoderScrollAccumulator.finishSync();
2943}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944
2945// --- TouchInputMapper ---
2946
2947TouchInputMapper::TouchInputMapper(InputDevice* device) :
2948 InputMapper(device),
2949 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2950 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2951 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2952}
2953
2954TouchInputMapper::~TouchInputMapper() {
2955}
2956
2957uint32_t TouchInputMapper::getSources() {
2958 return mSource;
2959}
2960
2961void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2962 InputMapper::populateDeviceInfo(info);
2963
2964 if (mDeviceMode != DEVICE_MODE_DISABLED) {
2965 info->addMotionRange(mOrientedRanges.x);
2966 info->addMotionRange(mOrientedRanges.y);
2967 info->addMotionRange(mOrientedRanges.pressure);
2968
2969 if (mOrientedRanges.haveSize) {
2970 info->addMotionRange(mOrientedRanges.size);
2971 }
2972
2973 if (mOrientedRanges.haveTouchSize) {
2974 info->addMotionRange(mOrientedRanges.touchMajor);
2975 info->addMotionRange(mOrientedRanges.touchMinor);
2976 }
2977
2978 if (mOrientedRanges.haveToolSize) {
2979 info->addMotionRange(mOrientedRanges.toolMajor);
2980 info->addMotionRange(mOrientedRanges.toolMinor);
2981 }
2982
2983 if (mOrientedRanges.haveOrientation) {
2984 info->addMotionRange(mOrientedRanges.orientation);
2985 }
2986
2987 if (mOrientedRanges.haveDistance) {
2988 info->addMotionRange(mOrientedRanges.distance);
2989 }
2990
2991 if (mOrientedRanges.haveTilt) {
2992 info->addMotionRange(mOrientedRanges.tilt);
2993 }
2994
2995 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2996 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2997 0.0f);
2998 }
2999 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3000 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3001 0.0f);
3002 }
3003 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3004 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3005 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3006 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3007 x.fuzz, x.resolution);
3008 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3009 y.fuzz, y.resolution);
3010 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3011 x.fuzz, x.resolution);
3012 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3013 y.fuzz, y.resolution);
3014 }
3015 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3016 }
3017}
3018
3019void TouchInputMapper::dump(String8& dump) {
3020 dump.append(INDENT2 "Touch Input Mapper:\n");
3021 dumpParameters(dump);
3022 dumpVirtualKeys(dump);
3023 dumpRawPointerAxes(dump);
3024 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003025 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 dumpSurface(dump);
3027
3028 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3029 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3030 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3031 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3032 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3033 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3034 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3035 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3036 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3037 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3038 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3039 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3040 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3041 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3042 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3043 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3044 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3045
Michael Wright7b159c92015-05-14 14:48:03 +01003046 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003048 mLastRawState.rawPointerData.pointerCount);
3049 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3050 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3052 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3053 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3054 "toolType=%d, isHovering=%s\n", i,
3055 pointer.id, pointer.x, pointer.y, pointer.pressure,
3056 pointer.touchMajor, pointer.touchMinor,
3057 pointer.toolMajor, pointer.toolMinor,
3058 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3059 pointer.toolType, toString(pointer.isHovering));
3060 }
3061
Michael Wright7b159c92015-05-14 14:48:03 +01003062 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003064 mLastCookedState.cookedPointerData.pointerCount);
3065 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3066 const PointerProperties& pointerProperties =
3067 mLastCookedState.cookedPointerData.pointerProperties[i];
3068 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3070 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3071 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3072 "toolType=%d, isHovering=%s\n", i,
3073 pointerProperties.id,
3074 pointerCoords.getX(),
3075 pointerCoords.getY(),
3076 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3077 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3078 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3079 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3080 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3081 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3082 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3083 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3084 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003085 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
3087
Michael Wright842500e2015-03-13 17:32:02 -07003088 dump.append(INDENT3 "Stylus Fusion:\n");
3089 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3090 toString(mExternalStylusConnected));
3091 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3092 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003093 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003094 dump.append(INDENT3 "External Stylus State:\n");
3095 dumpStylusState(dump, mExternalStylusState);
3096
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 if (mDeviceMode == DEVICE_MODE_POINTER) {
3098 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3099 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3100 mPointerXMovementScale);
3101 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3102 mPointerYMovementScale);
3103 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3104 mPointerXZoomScale);
3105 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3106 mPointerYZoomScale);
3107 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3108 mPointerGestureMaxSwipeWidth);
3109 }
3110}
3111
3112void TouchInputMapper::configure(nsecs_t when,
3113 const InputReaderConfiguration* config, uint32_t changes) {
3114 InputMapper::configure(when, config, changes);
3115
3116 mConfig = *config;
3117
3118 if (!changes) { // first time only
3119 // Configure basic parameters.
3120 configureParameters();
3121
3122 // Configure common accumulators.
3123 mCursorScrollAccumulator.configure(getDevice());
3124 mTouchButtonAccumulator.configure(getDevice());
3125
3126 // Configure absolute axis information.
3127 configureRawPointerAxes();
3128
3129 // Prepare input device calibration.
3130 parseCalibration();
3131 resolveCalibration();
3132 }
3133
Michael Wright842500e2015-03-13 17:32:02 -07003134 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003135 // Update location calibration to reflect current settings
3136 updateAffineTransformation();
3137 }
3138
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3140 // Update pointer speed.
3141 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3142 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3143 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3144 }
3145
3146 bool resetNeeded = false;
3147 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3148 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003149 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3150 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 // Configure device sources, surface dimensions, orientation and
3152 // scaling factors.
3153 configureSurface(when, &resetNeeded);
3154 }
3155
3156 if (changes && resetNeeded) {
3157 // Send reset, unless this is the first time the device has been configured,
3158 // in which case the reader will call reset itself after all mappers are ready.
3159 getDevice()->notifyReset(when);
3160 }
3161}
3162
Michael Wright842500e2015-03-13 17:32:02 -07003163void TouchInputMapper::resolveExternalStylusPresence() {
3164 Vector<InputDeviceInfo> devices;
3165 mContext->getExternalStylusDevices(devices);
3166 mExternalStylusConnected = !devices.isEmpty();
3167
3168 if (!mExternalStylusConnected) {
3169 resetExternalStylus();
3170 }
3171}
3172
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173void TouchInputMapper::configureParameters() {
3174 // Use the pointer presentation mode for devices that do not support distinct
3175 // multitouch. The spot-based presentation relies on being able to accurately
3176 // locate two or more fingers on the touch pad.
3177 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003178 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179
3180 String8 gestureModeString;
3181 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3182 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003183 if (gestureModeString == "single-touch") {
3184 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3185 } else if (gestureModeString == "multi-touch") {
3186 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 } else if (gestureModeString != "default") {
3188 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3189 }
3190 }
3191
3192 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3193 // The device is a touch screen.
3194 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3195 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3196 // The device is a pointing device like a track pad.
3197 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3198 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3199 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3200 // The device is a cursor device with a touch pad attached.
3201 // By default don't use the touch pad to move the pointer.
3202 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3203 } else {
3204 // The device is a touch pad of unknown purpose.
3205 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3206 }
3207
3208 mParameters.hasButtonUnderPad=
3209 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3210
3211 String8 deviceTypeString;
3212 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3213 deviceTypeString)) {
3214 if (deviceTypeString == "touchScreen") {
3215 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3216 } else if (deviceTypeString == "touchPad") {
3217 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3218 } else if (deviceTypeString == "touchNavigation") {
3219 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3220 } else if (deviceTypeString == "pointer") {
3221 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3222 } else if (deviceTypeString != "default") {
3223 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3224 }
3225 }
3226
3227 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3228 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3229 mParameters.orientationAware);
3230
3231 mParameters.hasAssociatedDisplay = false;
3232 mParameters.associatedDisplayIsExternal = false;
3233 if (mParameters.orientationAware
3234 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3235 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3236 mParameters.hasAssociatedDisplay = true;
3237 mParameters.associatedDisplayIsExternal =
3238 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3239 && getDevice()->isExternal();
3240 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003241
3242 // Initial downs on external touch devices should wake the device.
3243 // Normally we don't do this for internal touch screens to prevent them from waking
3244 // up in your pocket but you can enable it using the input device configuration.
3245 mParameters.wake = getDevice()->isExternal();
3246 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3247 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248}
3249
3250void TouchInputMapper::dumpParameters(String8& dump) {
3251 dump.append(INDENT3 "Parameters:\n");
3252
3253 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003254 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3255 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003257 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3258 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 break;
3260 default:
3261 assert(false);
3262 }
3263
3264 switch (mParameters.deviceType) {
3265 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3266 dump.append(INDENT4 "DeviceType: touchScreen\n");
3267 break;
3268 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3269 dump.append(INDENT4 "DeviceType: touchPad\n");
3270 break;
3271 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3272 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3273 break;
3274 case Parameters::DEVICE_TYPE_POINTER:
3275 dump.append(INDENT4 "DeviceType: pointer\n");
3276 break;
3277 default:
3278 ALOG_ASSERT(false);
3279 }
3280
3281 dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
3282 toString(mParameters.hasAssociatedDisplay),
3283 toString(mParameters.associatedDisplayIsExternal));
3284 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3285 toString(mParameters.orientationAware));
3286}
3287
3288void TouchInputMapper::configureRawPointerAxes() {
3289 mRawPointerAxes.clear();
3290}
3291
3292void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3293 dump.append(INDENT3 "Raw Touch Axes:\n");
3294 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3295 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3296 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3297 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3298 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3299 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3300 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3301 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3302 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3303 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3304 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3305 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3306 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3307}
3308
Michael Wright842500e2015-03-13 17:32:02 -07003309bool TouchInputMapper::hasExternalStylus() const {
3310 return mExternalStylusConnected;
3311}
3312
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3314 int32_t oldDeviceMode = mDeviceMode;
3315
Michael Wright842500e2015-03-13 17:32:02 -07003316 resolveExternalStylusPresence();
3317
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 // Determine device mode.
3319 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3320 && mConfig.pointerGesturesEnabled) {
3321 mSource = AINPUT_SOURCE_MOUSE;
3322 mDeviceMode = DEVICE_MODE_POINTER;
3323 if (hasStylus()) {
3324 mSource |= AINPUT_SOURCE_STYLUS;
3325 }
3326 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3327 && mParameters.hasAssociatedDisplay) {
3328 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3329 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003330 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 mSource |= AINPUT_SOURCE_STYLUS;
3332 }
Michael Wright2f78b682015-06-12 15:25:08 +01003333 if (hasExternalStylus()) {
3334 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3337 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3338 mDeviceMode = DEVICE_MODE_NAVIGATION;
3339 } else {
3340 mSource = AINPUT_SOURCE_TOUCHPAD;
3341 mDeviceMode = DEVICE_MODE_UNSCALED;
3342 }
3343
3344 // Ensure we have valid X and Y axes.
3345 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3346 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3347 "The device will be inoperable.", getDeviceName().string());
3348 mDeviceMode = DEVICE_MODE_DISABLED;
3349 return;
3350 }
3351
3352 // Raw width and height in the natural orientation.
3353 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3354 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3355
3356 // Get associated display dimensions.
3357 DisplayViewport newViewport;
3358 if (mParameters.hasAssociatedDisplay) {
3359 if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
3360 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3361 "display. The device will be inoperable until the display size "
3362 "becomes available.",
3363 getDeviceName().string());
3364 mDeviceMode = DEVICE_MODE_DISABLED;
3365 return;
3366 }
3367 } else {
3368 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3369 }
3370 bool viewportChanged = mViewport != newViewport;
3371 if (viewportChanged) {
3372 mViewport = newViewport;
3373
3374 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3375 // Convert rotated viewport to natural surface coordinates.
3376 int32_t naturalLogicalWidth, naturalLogicalHeight;
3377 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3378 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3379 int32_t naturalDeviceWidth, naturalDeviceHeight;
3380 switch (mViewport.orientation) {
3381 case DISPLAY_ORIENTATION_90:
3382 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3383 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3384 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3385 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3386 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3387 naturalPhysicalTop = mViewport.physicalLeft;
3388 naturalDeviceWidth = mViewport.deviceHeight;
3389 naturalDeviceHeight = mViewport.deviceWidth;
3390 break;
3391 case DISPLAY_ORIENTATION_180:
3392 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3393 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3394 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3395 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3396 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3397 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3398 naturalDeviceWidth = mViewport.deviceWidth;
3399 naturalDeviceHeight = mViewport.deviceHeight;
3400 break;
3401 case DISPLAY_ORIENTATION_270:
3402 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3403 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3404 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3405 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3406 naturalPhysicalLeft = mViewport.physicalTop;
3407 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3408 naturalDeviceWidth = mViewport.deviceHeight;
3409 naturalDeviceHeight = mViewport.deviceWidth;
3410 break;
3411 case DISPLAY_ORIENTATION_0:
3412 default:
3413 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3414 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3415 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3416 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3417 naturalPhysicalLeft = mViewport.physicalLeft;
3418 naturalPhysicalTop = mViewport.physicalTop;
3419 naturalDeviceWidth = mViewport.deviceWidth;
3420 naturalDeviceHeight = mViewport.deviceHeight;
3421 break;
3422 }
3423
3424 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3425 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3426 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3427 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3428
3429 mSurfaceOrientation = mParameters.orientationAware ?
3430 mViewport.orientation : DISPLAY_ORIENTATION_0;
3431 } else {
3432 mSurfaceWidth = rawWidth;
3433 mSurfaceHeight = rawHeight;
3434 mSurfaceLeft = 0;
3435 mSurfaceTop = 0;
3436 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3437 }
3438 }
3439
3440 // If moving between pointer modes, need to reset some state.
3441 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3442 if (deviceModeChanged) {
3443 mOrientedRanges.clear();
3444 }
3445
3446 // Create pointer controller if needed.
3447 if (mDeviceMode == DEVICE_MODE_POINTER ||
3448 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3449 if (mPointerController == NULL) {
3450 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3451 }
3452 } else {
3453 mPointerController.clear();
3454 }
3455
3456 if (viewportChanged || deviceModeChanged) {
3457 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3458 "display id %d",
3459 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3460 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3461
3462 // Configure X and Y factors.
3463 mXScale = float(mSurfaceWidth) / rawWidth;
3464 mYScale = float(mSurfaceHeight) / rawHeight;
3465 mXTranslate = -mSurfaceLeft;
3466 mYTranslate = -mSurfaceTop;
3467 mXPrecision = 1.0f / mXScale;
3468 mYPrecision = 1.0f / mYScale;
3469
3470 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3471 mOrientedRanges.x.source = mSource;
3472 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3473 mOrientedRanges.y.source = mSource;
3474
3475 configureVirtualKeys();
3476
3477 // Scale factor for terms that are not oriented in a particular axis.
3478 // If the pixels are square then xScale == yScale otherwise we fake it
3479 // by choosing an average.
3480 mGeometricScale = avg(mXScale, mYScale);
3481
3482 // Size of diagonal axis.
3483 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3484
3485 // Size factors.
3486 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3487 if (mRawPointerAxes.touchMajor.valid
3488 && mRawPointerAxes.touchMajor.maxValue != 0) {
3489 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3490 } else if (mRawPointerAxes.toolMajor.valid
3491 && mRawPointerAxes.toolMajor.maxValue != 0) {
3492 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3493 } else {
3494 mSizeScale = 0.0f;
3495 }
3496
3497 mOrientedRanges.haveTouchSize = true;
3498 mOrientedRanges.haveToolSize = true;
3499 mOrientedRanges.haveSize = true;
3500
3501 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3502 mOrientedRanges.touchMajor.source = mSource;
3503 mOrientedRanges.touchMajor.min = 0;
3504 mOrientedRanges.touchMajor.max = diagonalSize;
3505 mOrientedRanges.touchMajor.flat = 0;
3506 mOrientedRanges.touchMajor.fuzz = 0;
3507 mOrientedRanges.touchMajor.resolution = 0;
3508
3509 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3510 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3511
3512 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3513 mOrientedRanges.toolMajor.source = mSource;
3514 mOrientedRanges.toolMajor.min = 0;
3515 mOrientedRanges.toolMajor.max = diagonalSize;
3516 mOrientedRanges.toolMajor.flat = 0;
3517 mOrientedRanges.toolMajor.fuzz = 0;
3518 mOrientedRanges.toolMajor.resolution = 0;
3519
3520 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3521 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3522
3523 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3524 mOrientedRanges.size.source = mSource;
3525 mOrientedRanges.size.min = 0;
3526 mOrientedRanges.size.max = 1.0;
3527 mOrientedRanges.size.flat = 0;
3528 mOrientedRanges.size.fuzz = 0;
3529 mOrientedRanges.size.resolution = 0;
3530 } else {
3531 mSizeScale = 0.0f;
3532 }
3533
3534 // Pressure factors.
3535 mPressureScale = 0;
3536 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3537 || mCalibration.pressureCalibration
3538 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3539 if (mCalibration.havePressureScale) {
3540 mPressureScale = mCalibration.pressureScale;
3541 } else if (mRawPointerAxes.pressure.valid
3542 && mRawPointerAxes.pressure.maxValue != 0) {
3543 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3544 }
3545 }
3546
3547 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3548 mOrientedRanges.pressure.source = mSource;
3549 mOrientedRanges.pressure.min = 0;
3550 mOrientedRanges.pressure.max = 1.0;
3551 mOrientedRanges.pressure.flat = 0;
3552 mOrientedRanges.pressure.fuzz = 0;
3553 mOrientedRanges.pressure.resolution = 0;
3554
3555 // Tilt
3556 mTiltXCenter = 0;
3557 mTiltXScale = 0;
3558 mTiltYCenter = 0;
3559 mTiltYScale = 0;
3560 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3561 if (mHaveTilt) {
3562 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3563 mRawPointerAxes.tiltX.maxValue);
3564 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3565 mRawPointerAxes.tiltY.maxValue);
3566 mTiltXScale = M_PI / 180;
3567 mTiltYScale = M_PI / 180;
3568
3569 mOrientedRanges.haveTilt = true;
3570
3571 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3572 mOrientedRanges.tilt.source = mSource;
3573 mOrientedRanges.tilt.min = 0;
3574 mOrientedRanges.tilt.max = M_PI_2;
3575 mOrientedRanges.tilt.flat = 0;
3576 mOrientedRanges.tilt.fuzz = 0;
3577 mOrientedRanges.tilt.resolution = 0;
3578 }
3579
3580 // Orientation
3581 mOrientationScale = 0;
3582 if (mHaveTilt) {
3583 mOrientedRanges.haveOrientation = true;
3584
3585 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3586 mOrientedRanges.orientation.source = mSource;
3587 mOrientedRanges.orientation.min = -M_PI;
3588 mOrientedRanges.orientation.max = M_PI;
3589 mOrientedRanges.orientation.flat = 0;
3590 mOrientedRanges.orientation.fuzz = 0;
3591 mOrientedRanges.orientation.resolution = 0;
3592 } else if (mCalibration.orientationCalibration !=
3593 Calibration::ORIENTATION_CALIBRATION_NONE) {
3594 if (mCalibration.orientationCalibration
3595 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3596 if (mRawPointerAxes.orientation.valid) {
3597 if (mRawPointerAxes.orientation.maxValue > 0) {
3598 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3599 } else if (mRawPointerAxes.orientation.minValue < 0) {
3600 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3601 } else {
3602 mOrientationScale = 0;
3603 }
3604 }
3605 }
3606
3607 mOrientedRanges.haveOrientation = true;
3608
3609 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3610 mOrientedRanges.orientation.source = mSource;
3611 mOrientedRanges.orientation.min = -M_PI_2;
3612 mOrientedRanges.orientation.max = M_PI_2;
3613 mOrientedRanges.orientation.flat = 0;
3614 mOrientedRanges.orientation.fuzz = 0;
3615 mOrientedRanges.orientation.resolution = 0;
3616 }
3617
3618 // Distance
3619 mDistanceScale = 0;
3620 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3621 if (mCalibration.distanceCalibration
3622 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3623 if (mCalibration.haveDistanceScale) {
3624 mDistanceScale = mCalibration.distanceScale;
3625 } else {
3626 mDistanceScale = 1.0f;
3627 }
3628 }
3629
3630 mOrientedRanges.haveDistance = true;
3631
3632 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3633 mOrientedRanges.distance.source = mSource;
3634 mOrientedRanges.distance.min =
3635 mRawPointerAxes.distance.minValue * mDistanceScale;
3636 mOrientedRanges.distance.max =
3637 mRawPointerAxes.distance.maxValue * mDistanceScale;
3638 mOrientedRanges.distance.flat = 0;
3639 mOrientedRanges.distance.fuzz =
3640 mRawPointerAxes.distance.fuzz * mDistanceScale;
3641 mOrientedRanges.distance.resolution = 0;
3642 }
3643
3644 // Compute oriented precision, scales and ranges.
3645 // Note that the maximum value reported is an inclusive maximum value so it is one
3646 // unit less than the total width or height of surface.
3647 switch (mSurfaceOrientation) {
3648 case DISPLAY_ORIENTATION_90:
3649 case DISPLAY_ORIENTATION_270:
3650 mOrientedXPrecision = mYPrecision;
3651 mOrientedYPrecision = mXPrecision;
3652
3653 mOrientedRanges.x.min = mYTranslate;
3654 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3655 mOrientedRanges.x.flat = 0;
3656 mOrientedRanges.x.fuzz = 0;
3657 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3658
3659 mOrientedRanges.y.min = mXTranslate;
3660 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3661 mOrientedRanges.y.flat = 0;
3662 mOrientedRanges.y.fuzz = 0;
3663 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3664 break;
3665
3666 default:
3667 mOrientedXPrecision = mXPrecision;
3668 mOrientedYPrecision = mYPrecision;
3669
3670 mOrientedRanges.x.min = mXTranslate;
3671 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3672 mOrientedRanges.x.flat = 0;
3673 mOrientedRanges.x.fuzz = 0;
3674 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3675
3676 mOrientedRanges.y.min = mYTranslate;
3677 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3678 mOrientedRanges.y.flat = 0;
3679 mOrientedRanges.y.fuzz = 0;
3680 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3681 break;
3682 }
3683
Jason Gerecke71b16e82014-03-10 09:47:59 -07003684 // Location
3685 updateAffineTransformation();
3686
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 if (mDeviceMode == DEVICE_MODE_POINTER) {
3688 // Compute pointer gesture detection parameters.
3689 float rawDiagonal = hypotf(rawWidth, rawHeight);
3690 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3691
3692 // Scale movements such that one whole swipe of the touch pad covers a
3693 // given area relative to the diagonal size of the display when no acceleration
3694 // is applied.
3695 // Assume that the touch pad has a square aspect ratio such that movements in
3696 // X and Y of the same number of raw units cover the same physical distance.
3697 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3698 * displayDiagonal / rawDiagonal;
3699 mPointerYMovementScale = mPointerXMovementScale;
3700
3701 // Scale zooms to cover a smaller range of the display than movements do.
3702 // This value determines the area around the pointer that is affected by freeform
3703 // pointer gestures.
3704 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3705 * displayDiagonal / rawDiagonal;
3706 mPointerYZoomScale = mPointerXZoomScale;
3707
3708 // Max width between pointers to detect a swipe gesture is more than some fraction
3709 // of the diagonal axis of the touch pad. Touches that are wider than this are
3710 // translated into freeform gestures.
3711 mPointerGestureMaxSwipeWidth =
3712 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3713
3714 // Abort current pointer usages because the state has changed.
3715 abortPointerUsage(when, 0 /*policyFlags*/);
3716 }
3717
3718 // Inform the dispatcher about the changes.
3719 *outResetNeeded = true;
3720 bumpGeneration();
3721 }
3722}
3723
3724void TouchInputMapper::dumpSurface(String8& dump) {
3725 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3726 "logicalFrame=[%d, %d, %d, %d], "
3727 "physicalFrame=[%d, %d, %d, %d], "
3728 "deviceSize=[%d, %d]\n",
3729 mViewport.displayId, mViewport.orientation,
3730 mViewport.logicalLeft, mViewport.logicalTop,
3731 mViewport.logicalRight, mViewport.logicalBottom,
3732 mViewport.physicalLeft, mViewport.physicalTop,
3733 mViewport.physicalRight, mViewport.physicalBottom,
3734 mViewport.deviceWidth, mViewport.deviceHeight);
3735
3736 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3737 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3738 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3739 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3740 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3741}
3742
3743void TouchInputMapper::configureVirtualKeys() {
3744 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3745 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3746
3747 mVirtualKeys.clear();
3748
3749 if (virtualKeyDefinitions.size() == 0) {
3750 return;
3751 }
3752
3753 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3754
3755 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3756 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3757 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3758 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3759
3760 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3761 const VirtualKeyDefinition& virtualKeyDefinition =
3762 virtualKeyDefinitions[i];
3763
3764 mVirtualKeys.add();
3765 VirtualKey& virtualKey = mVirtualKeys.editTop();
3766
3767 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3768 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003769 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003771 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3772 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3774 virtualKey.scanCode);
3775 mVirtualKeys.pop(); // drop the key
3776 continue;
3777 }
3778
3779 virtualKey.keyCode = keyCode;
3780 virtualKey.flags = flags;
3781
3782 // convert the key definition's display coordinates into touch coordinates for a hit box
3783 int32_t halfWidth = virtualKeyDefinition.width / 2;
3784 int32_t halfHeight = virtualKeyDefinition.height / 2;
3785
3786 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3787 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3788 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3789 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3790 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3791 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3792 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3793 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3794 }
3795}
3796
3797void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3798 if (!mVirtualKeys.isEmpty()) {
3799 dump.append(INDENT3 "Virtual Keys:\n");
3800
3801 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3802 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003803 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3805 i, virtualKey.scanCode, virtualKey.keyCode,
3806 virtualKey.hitLeft, virtualKey.hitRight,
3807 virtualKey.hitTop, virtualKey.hitBottom);
3808 }
3809 }
3810}
3811
3812void TouchInputMapper::parseCalibration() {
3813 const PropertyMap& in = getDevice()->getConfiguration();
3814 Calibration& out = mCalibration;
3815
3816 // Size
3817 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3818 String8 sizeCalibrationString;
3819 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3820 if (sizeCalibrationString == "none") {
3821 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3822 } else if (sizeCalibrationString == "geometric") {
3823 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3824 } else if (sizeCalibrationString == "diameter") {
3825 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3826 } else if (sizeCalibrationString == "box") {
3827 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3828 } else if (sizeCalibrationString == "area") {
3829 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3830 } else if (sizeCalibrationString != "default") {
3831 ALOGW("Invalid value for touch.size.calibration: '%s'",
3832 sizeCalibrationString.string());
3833 }
3834 }
3835
3836 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3837 out.sizeScale);
3838 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3839 out.sizeBias);
3840 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3841 out.sizeIsSummed);
3842
3843 // Pressure
3844 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3845 String8 pressureCalibrationString;
3846 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3847 if (pressureCalibrationString == "none") {
3848 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3849 } else if (pressureCalibrationString == "physical") {
3850 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3851 } else if (pressureCalibrationString == "amplitude") {
3852 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3853 } else if (pressureCalibrationString != "default") {
3854 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3855 pressureCalibrationString.string());
3856 }
3857 }
3858
3859 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3860 out.pressureScale);
3861
3862 // Orientation
3863 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3864 String8 orientationCalibrationString;
3865 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3866 if (orientationCalibrationString == "none") {
3867 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3868 } else if (orientationCalibrationString == "interpolated") {
3869 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3870 } else if (orientationCalibrationString == "vector") {
3871 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3872 } else if (orientationCalibrationString != "default") {
3873 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3874 orientationCalibrationString.string());
3875 }
3876 }
3877
3878 // Distance
3879 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3880 String8 distanceCalibrationString;
3881 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3882 if (distanceCalibrationString == "none") {
3883 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3884 } else if (distanceCalibrationString == "scaled") {
3885 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3886 } else if (distanceCalibrationString != "default") {
3887 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3888 distanceCalibrationString.string());
3889 }
3890 }
3891
3892 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3893 out.distanceScale);
3894
3895 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3896 String8 coverageCalibrationString;
3897 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3898 if (coverageCalibrationString == "none") {
3899 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3900 } else if (coverageCalibrationString == "box") {
3901 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3902 } else if (coverageCalibrationString != "default") {
3903 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3904 coverageCalibrationString.string());
3905 }
3906 }
3907}
3908
3909void TouchInputMapper::resolveCalibration() {
3910 // Size
3911 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3912 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3913 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3914 }
3915 } else {
3916 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3917 }
3918
3919 // Pressure
3920 if (mRawPointerAxes.pressure.valid) {
3921 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3922 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3923 }
3924 } else {
3925 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3926 }
3927
3928 // Orientation
3929 if (mRawPointerAxes.orientation.valid) {
3930 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3931 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3932 }
3933 } else {
3934 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3935 }
3936
3937 // Distance
3938 if (mRawPointerAxes.distance.valid) {
3939 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3940 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3941 }
3942 } else {
3943 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3944 }
3945
3946 // Coverage
3947 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3948 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3949 }
3950}
3951
3952void TouchInputMapper::dumpCalibration(String8& dump) {
3953 dump.append(INDENT3 "Calibration:\n");
3954
3955 // Size
3956 switch (mCalibration.sizeCalibration) {
3957 case Calibration::SIZE_CALIBRATION_NONE:
3958 dump.append(INDENT4 "touch.size.calibration: none\n");
3959 break;
3960 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3961 dump.append(INDENT4 "touch.size.calibration: geometric\n");
3962 break;
3963 case Calibration::SIZE_CALIBRATION_DIAMETER:
3964 dump.append(INDENT4 "touch.size.calibration: diameter\n");
3965 break;
3966 case Calibration::SIZE_CALIBRATION_BOX:
3967 dump.append(INDENT4 "touch.size.calibration: box\n");
3968 break;
3969 case Calibration::SIZE_CALIBRATION_AREA:
3970 dump.append(INDENT4 "touch.size.calibration: area\n");
3971 break;
3972 default:
3973 ALOG_ASSERT(false);
3974 }
3975
3976 if (mCalibration.haveSizeScale) {
3977 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3978 mCalibration.sizeScale);
3979 }
3980
3981 if (mCalibration.haveSizeBias) {
3982 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3983 mCalibration.sizeBias);
3984 }
3985
3986 if (mCalibration.haveSizeIsSummed) {
3987 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3988 toString(mCalibration.sizeIsSummed));
3989 }
3990
3991 // Pressure
3992 switch (mCalibration.pressureCalibration) {
3993 case Calibration::PRESSURE_CALIBRATION_NONE:
3994 dump.append(INDENT4 "touch.pressure.calibration: none\n");
3995 break;
3996 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3997 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3998 break;
3999 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4000 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4001 break;
4002 default:
4003 ALOG_ASSERT(false);
4004 }
4005
4006 if (mCalibration.havePressureScale) {
4007 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4008 mCalibration.pressureScale);
4009 }
4010
4011 // Orientation
4012 switch (mCalibration.orientationCalibration) {
4013 case Calibration::ORIENTATION_CALIBRATION_NONE:
4014 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4015 break;
4016 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4017 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4018 break;
4019 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4020 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4021 break;
4022 default:
4023 ALOG_ASSERT(false);
4024 }
4025
4026 // Distance
4027 switch (mCalibration.distanceCalibration) {
4028 case Calibration::DISTANCE_CALIBRATION_NONE:
4029 dump.append(INDENT4 "touch.distance.calibration: none\n");
4030 break;
4031 case Calibration::DISTANCE_CALIBRATION_SCALED:
4032 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4033 break;
4034 default:
4035 ALOG_ASSERT(false);
4036 }
4037
4038 if (mCalibration.haveDistanceScale) {
4039 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4040 mCalibration.distanceScale);
4041 }
4042
4043 switch (mCalibration.coverageCalibration) {
4044 case Calibration::COVERAGE_CALIBRATION_NONE:
4045 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4046 break;
4047 case Calibration::COVERAGE_CALIBRATION_BOX:
4048 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4049 break;
4050 default:
4051 ALOG_ASSERT(false);
4052 }
4053}
4054
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004055void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4056 dump.append(INDENT3 "Affine Transformation:\n");
4057
4058 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4059 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4060 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4061 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4062 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4063 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4064}
4065
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004066void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004067 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4068 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004069}
4070
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071void TouchInputMapper::reset(nsecs_t when) {
4072 mCursorButtonAccumulator.reset(getDevice());
4073 mCursorScrollAccumulator.reset(getDevice());
4074 mTouchButtonAccumulator.reset(getDevice());
4075
4076 mPointerVelocityControl.reset();
4077 mWheelXVelocityControl.reset();
4078 mWheelYVelocityControl.reset();
4079
Michael Wright842500e2015-03-13 17:32:02 -07004080 mRawStatesPending.clear();
4081 mCurrentRawState.clear();
4082 mCurrentCookedState.clear();
4083 mLastRawState.clear();
4084 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 mPointerUsage = POINTER_USAGE_NONE;
4086 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004087 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004088 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 mDownTime = 0;
4090
4091 mCurrentVirtualKey.down = false;
4092
4093 mPointerGesture.reset();
4094 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004095 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096
4097 if (mPointerController != NULL) {
4098 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4099 mPointerController->clearSpots();
4100 }
4101
4102 InputMapper::reset(when);
4103}
4104
Michael Wright842500e2015-03-13 17:32:02 -07004105void TouchInputMapper::resetExternalStylus() {
4106 mExternalStylusState.clear();
4107 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004108 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004109 mExternalStylusDataPending = false;
4110}
4111
Michael Wright43fd19f2015-04-21 19:02:58 +01004112void TouchInputMapper::clearStylusDataPendingFlags() {
4113 mExternalStylusDataPending = false;
4114 mExternalStylusFusionTimeout = LLONG_MAX;
4115}
4116
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117void TouchInputMapper::process(const RawEvent* rawEvent) {
4118 mCursorButtonAccumulator.process(rawEvent);
4119 mCursorScrollAccumulator.process(rawEvent);
4120 mTouchButtonAccumulator.process(rawEvent);
4121
4122 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4123 sync(rawEvent->when);
4124 }
4125}
4126
4127void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004128 const RawState* last = mRawStatesPending.isEmpty() ?
4129 &mCurrentRawState : &mRawStatesPending.top();
4130
4131 // Push a new state.
4132 mRawStatesPending.push();
4133 RawState* next = &mRawStatesPending.editTop();
4134 next->clear();
4135 next->when = when;
4136
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004138 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 | mCursorButtonAccumulator.getButtonState();
4140
Michael Wright842500e2015-03-13 17:32:02 -07004141 // Sync scroll
4142 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4143 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 mCursorScrollAccumulator.finishSync();
4145
Michael Wright842500e2015-03-13 17:32:02 -07004146 // Sync touch
4147 syncTouch(when, next);
4148
4149 // Assign pointer ids.
4150 if (!mHavePointerIds) {
4151 assignPointerIds(last, next);
4152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153
4154#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004155 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4156 "hovering ids 0x%08x -> 0x%08x",
4157 last->rawPointerData.pointerCount,
4158 next->rawPointerData.pointerCount,
4159 last->rawPointerData.touchingIdBits.value,
4160 next->rawPointerData.touchingIdBits.value,
4161 last->rawPointerData.hoveringIdBits.value,
4162 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163#endif
4164
Michael Wright842500e2015-03-13 17:32:02 -07004165 processRawTouches(false /*timeout*/);
4166}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
Michael Wright842500e2015-03-13 17:32:02 -07004168void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4170 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004171 mCurrentRawState.clear();
4172 mRawStatesPending.clear();
4173 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175
Michael Wright842500e2015-03-13 17:32:02 -07004176 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4177 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4178 // touching the current state will only observe the events that have been dispatched to the
4179 // rest of the pipeline.
4180 const size_t N = mRawStatesPending.size();
4181 size_t count;
4182 for(count = 0; count < N; count++) {
4183 const RawState& next = mRawStatesPending[count];
4184
4185 // A failure to assign the stylus id means that we're waiting on stylus data
4186 // and so should defer the rest of the pipeline.
4187 if (assignExternalStylusId(next, timeout)) {
4188 break;
4189 }
4190
4191 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004192 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004193 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004194 if (mCurrentRawState.when < mLastRawState.when) {
4195 mCurrentRawState.when = mLastRawState.when;
4196 }
Michael Wright842500e2015-03-13 17:32:02 -07004197 cookAndDispatch(mCurrentRawState.when);
4198 }
4199 if (count != 0) {
4200 mRawStatesPending.removeItemsAt(0, count);
4201 }
4202
Michael Wright842500e2015-03-13 17:32:02 -07004203 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004204 if (timeout) {
4205 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4206 clearStylusDataPendingFlags();
4207 mCurrentRawState.copyFrom(mLastRawState);
4208#if DEBUG_STYLUS_FUSION
4209 ALOGD("Timeout expired, synthesizing event with new stylus data");
4210#endif
4211 cookAndDispatch(when);
4212 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4213 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4214 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4215 }
Michael Wright842500e2015-03-13 17:32:02 -07004216 }
4217}
4218
4219void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4220 // Always start with a clean state.
4221 mCurrentCookedState.clear();
4222
4223 // Apply stylus buttons to current raw state.
4224 applyExternalStylusButtonState(when);
4225
4226 // Handle policy on initial down or hover events.
4227 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4228 && mCurrentRawState.rawPointerData.pointerCount != 0;
4229
4230 uint32_t policyFlags = 0;
4231 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4232 if (initialDown || buttonsPressed) {
4233 // If this is a touch screen, hide the pointer on an initial down.
4234 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4235 getContext()->fadePointer();
4236 }
4237
4238 if (mParameters.wake) {
4239 policyFlags |= POLICY_FLAG_WAKE;
4240 }
4241 }
4242
4243 // Consume raw off-screen touches before cooking pointer data.
4244 // If touches are consumed, subsequent code will not receive any pointer data.
4245 if (consumeRawTouches(when, policyFlags)) {
4246 mCurrentRawState.rawPointerData.clear();
4247 }
4248
4249 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4250 // with cooked pointer data that has the same ids and indices as the raw data.
4251 // The following code can use either the raw or cooked data, as needed.
4252 cookPointerData();
4253
4254 // Apply stylus pressure to current cooked state.
4255 applyExternalStylusTouchState(when);
4256
4257 // Synthesize key down from raw buttons if needed.
4258 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004259 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004260
4261 // Dispatch the touches either directly or by translation through a pointer on screen.
4262 if (mDeviceMode == DEVICE_MODE_POINTER) {
4263 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4264 !idBits.isEmpty(); ) {
4265 uint32_t id = idBits.clearFirstMarkedBit();
4266 const RawPointerData::Pointer& pointer =
4267 mCurrentRawState.rawPointerData.pointerForId(id);
4268 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4269 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4270 mCurrentCookedState.stylusIdBits.markBit(id);
4271 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4272 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4273 mCurrentCookedState.fingerIdBits.markBit(id);
4274 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4275 mCurrentCookedState.mouseIdBits.markBit(id);
4276 }
4277 }
4278 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4279 !idBits.isEmpty(); ) {
4280 uint32_t id = idBits.clearFirstMarkedBit();
4281 const RawPointerData::Pointer& pointer =
4282 mCurrentRawState.rawPointerData.pointerForId(id);
4283 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4284 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4285 mCurrentCookedState.stylusIdBits.markBit(id);
4286 }
4287 }
4288
4289 // Stylus takes precedence over all tools, then mouse, then finger.
4290 PointerUsage pointerUsage = mPointerUsage;
4291 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4292 mCurrentCookedState.mouseIdBits.clear();
4293 mCurrentCookedState.fingerIdBits.clear();
4294 pointerUsage = POINTER_USAGE_STYLUS;
4295 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4296 mCurrentCookedState.fingerIdBits.clear();
4297 pointerUsage = POINTER_USAGE_MOUSE;
4298 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4299 isPointerDown(mCurrentRawState.buttonState)) {
4300 pointerUsage = POINTER_USAGE_GESTURES;
4301 }
4302
4303 dispatchPointerUsage(when, policyFlags, pointerUsage);
4304 } else {
4305 if (mDeviceMode == DEVICE_MODE_DIRECT
4306 && mConfig.showTouches && mPointerController != NULL) {
4307 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4308 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4309
4310 mPointerController->setButtonState(mCurrentRawState.buttonState);
4311 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4312 mCurrentCookedState.cookedPointerData.idToIndex,
4313 mCurrentCookedState.cookedPointerData.touchingIdBits);
4314 }
4315
Michael Wright8e812822015-06-22 16:18:21 +01004316 if (!mCurrentMotionAborted) {
4317 dispatchButtonRelease(when, policyFlags);
4318 dispatchHoverExit(when, policyFlags);
4319 dispatchTouches(when, policyFlags);
4320 dispatchHoverEnterAndMove(when, policyFlags);
4321 dispatchButtonPress(when, policyFlags);
4322 }
4323
4324 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4325 mCurrentMotionAborted = false;
4326 }
Michael Wright842500e2015-03-13 17:32:02 -07004327 }
4328
4329 // Synthesize key up from raw buttons if needed.
4330 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004331 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
4333 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004334 mCurrentRawState.rawVScroll = 0;
4335 mCurrentRawState.rawHScroll = 0;
4336
4337 // Copy current touch to last touch in preparation for the next cycle.
4338 mLastRawState.copyFrom(mCurrentRawState);
4339 mLastCookedState.copyFrom(mCurrentCookedState);
4340}
4341
4342void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004343 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004344 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4345 }
4346}
4347
4348void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004349 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4350 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004351
Michael Wright53dca3a2015-04-23 17:39:53 +01004352 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4353 float pressure = mExternalStylusState.pressure;
4354 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4355 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4356 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4357 }
4358 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4359 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4360
4361 PointerProperties& properties =
4362 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004363 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4364 properties.toolType = mExternalStylusState.toolType;
4365 }
4366 }
4367}
4368
4369bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4370 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4371 return false;
4372 }
4373
4374 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4375 && state.rawPointerData.pointerCount != 0;
4376 if (initialDown) {
4377 if (mExternalStylusState.pressure != 0.0f) {
4378#if DEBUG_STYLUS_FUSION
4379 ALOGD("Have both stylus and touch data, beginning fusion");
4380#endif
4381 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4382 } else if (timeout) {
4383#if DEBUG_STYLUS_FUSION
4384 ALOGD("Timeout expired, assuming touch is not a stylus.");
4385#endif
4386 resetExternalStylus();
4387 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004388 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4389 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004390 }
4391#if DEBUG_STYLUS_FUSION
4392 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004393 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004394#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004395 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004396 return true;
4397 }
4398 }
4399
4400 // Check if the stylus pointer has gone up.
4401 if (mExternalStylusId != -1 &&
4402 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4403#if DEBUG_STYLUS_FUSION
4404 ALOGD("Stylus pointer is going up");
4405#endif
4406 mExternalStylusId = -1;
4407 }
4408
4409 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410}
4411
4412void TouchInputMapper::timeoutExpired(nsecs_t when) {
4413 if (mDeviceMode == DEVICE_MODE_POINTER) {
4414 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4415 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4416 }
Michael Wright842500e2015-03-13 17:32:02 -07004417 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004418 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004419 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004420 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4421 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004422 }
4423 }
4424}
4425
4426void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004427 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004428 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004429 // We're either in the middle of a fused stream of data or we're waiting on data before
4430 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4431 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004432 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004433 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 }
4435}
4436
4437bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4438 // Check for release of a virtual key.
4439 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004440 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 // Pointer went up while virtual key was down.
4442 mCurrentVirtualKey.down = false;
4443 if (!mCurrentVirtualKey.ignored) {
4444#if DEBUG_VIRTUAL_KEYS
4445 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4446 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4447#endif
4448 dispatchVirtualKey(when, policyFlags,
4449 AKEY_EVENT_ACTION_UP,
4450 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4451 }
4452 return true;
4453 }
4454
Michael Wright842500e2015-03-13 17:32:02 -07004455 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4456 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4457 const RawPointerData::Pointer& pointer =
4458 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4460 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4461 // Pointer is still within the space of the virtual key.
4462 return true;
4463 }
4464 }
4465
4466 // Pointer left virtual key area or another pointer also went down.
4467 // Send key cancellation but do not consume the touch yet.
4468 // This is useful when the user swipes through from the virtual key area
4469 // into the main display surface.
4470 mCurrentVirtualKey.down = false;
4471 if (!mCurrentVirtualKey.ignored) {
4472#if DEBUG_VIRTUAL_KEYS
4473 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4474 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4475#endif
4476 dispatchVirtualKey(when, policyFlags,
4477 AKEY_EVENT_ACTION_UP,
4478 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4479 | AKEY_EVENT_FLAG_CANCELED);
4480 }
4481 }
4482
Michael Wright842500e2015-03-13 17:32:02 -07004483 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4484 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004486 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4487 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4489 // If exactly one pointer went down, check for virtual key hit.
4490 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004491 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4493 if (virtualKey) {
4494 mCurrentVirtualKey.down = true;
4495 mCurrentVirtualKey.downTime = when;
4496 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4497 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4498 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4499 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4500
4501 if (!mCurrentVirtualKey.ignored) {
4502#if DEBUG_VIRTUAL_KEYS
4503 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4504 mCurrentVirtualKey.keyCode,
4505 mCurrentVirtualKey.scanCode);
4506#endif
4507 dispatchVirtualKey(when, policyFlags,
4508 AKEY_EVENT_ACTION_DOWN,
4509 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4510 }
4511 }
4512 }
4513 return true;
4514 }
4515 }
4516
4517 // Disable all virtual key touches that happen within a short time interval of the
4518 // most recent touch within the screen area. The idea is to filter out stray
4519 // virtual key presses when interacting with the touch screen.
4520 //
4521 // Problems we're trying to solve:
4522 //
4523 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4524 // virtual key area that is implemented by a separate touch panel and accidentally
4525 // triggers a virtual key.
4526 //
4527 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4528 // area and accidentally triggers a virtual key. This often happens when virtual keys
4529 // are layed out below the screen near to where the on screen keyboard's space bar
4530 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004531 if (mConfig.virtualKeyQuietTime > 0 &&
4532 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4534 }
4535 return false;
4536}
4537
4538void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4539 int32_t keyEventAction, int32_t keyEventFlags) {
4540 int32_t keyCode = mCurrentVirtualKey.keyCode;
4541 int32_t scanCode = mCurrentVirtualKey.scanCode;
4542 nsecs_t downTime = mCurrentVirtualKey.downTime;
4543 int32_t metaState = mContext->getGlobalMetaState();
4544 policyFlags |= POLICY_FLAG_VIRTUAL;
4545
4546 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4547 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4548 getListener()->notifyKey(&args);
4549}
4550
Michael Wright8e812822015-06-22 16:18:21 +01004551void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4552 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4553 if (!currentIdBits.isEmpty()) {
4554 int32_t metaState = getContext()->getGlobalMetaState();
4555 int32_t buttonState = mCurrentCookedState.buttonState;
4556 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4557 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4558 mCurrentCookedState.cookedPointerData.pointerProperties,
4559 mCurrentCookedState.cookedPointerData.pointerCoords,
4560 mCurrentCookedState.cookedPointerData.idToIndex,
4561 currentIdBits, -1,
4562 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4563 mCurrentMotionAborted = true;
4564 }
4565}
4566
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004568 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4569 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004571 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572
4573 if (currentIdBits == lastIdBits) {
4574 if (!currentIdBits.isEmpty()) {
4575 // No pointer id changes so this is a move event.
4576 // The listener takes care of batching moves so we don't have to deal with that here.
4577 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004578 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004580 mCurrentCookedState.cookedPointerData.pointerProperties,
4581 mCurrentCookedState.cookedPointerData.pointerCoords,
4582 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 currentIdBits, -1,
4584 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4585 }
4586 } else {
4587 // There may be pointers going up and pointers going down and pointers moving
4588 // all at the same time.
4589 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4590 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4591 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4592 BitSet32 dispatchedIdBits(lastIdBits.value);
4593
4594 // Update last coordinates of pointers that have moved so that we observe the new
4595 // pointer positions at the same time as other pointers that have just gone up.
4596 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004597 mCurrentCookedState.cookedPointerData.pointerProperties,
4598 mCurrentCookedState.cookedPointerData.pointerCoords,
4599 mCurrentCookedState.cookedPointerData.idToIndex,
4600 mLastCookedState.cookedPointerData.pointerProperties,
4601 mLastCookedState.cookedPointerData.pointerCoords,
4602 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004604 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 moveNeeded = true;
4606 }
4607
4608 // Dispatch pointer up events.
4609 while (!upIdBits.isEmpty()) {
4610 uint32_t upId = upIdBits.clearFirstMarkedBit();
4611
4612 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004613 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004614 mLastCookedState.cookedPointerData.pointerProperties,
4615 mLastCookedState.cookedPointerData.pointerCoords,
4616 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004617 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 dispatchedIdBits.clearBit(upId);
4619 }
4620
4621 // Dispatch move events if any of the remaining pointers moved from their old locations.
4622 // Although applications receive new locations as part of individual pointer up
4623 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004624 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4626 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004627 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004628 mCurrentCookedState.cookedPointerData.pointerProperties,
4629 mCurrentCookedState.cookedPointerData.pointerCoords,
4630 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004631 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 }
4633
4634 // Dispatch pointer down events using the new pointer locations.
4635 while (!downIdBits.isEmpty()) {
4636 uint32_t downId = downIdBits.clearFirstMarkedBit();
4637 dispatchedIdBits.markBit(downId);
4638
4639 if (dispatchedIdBits.count() == 1) {
4640 // First pointer is going down. Set down time.
4641 mDownTime = when;
4642 }
4643
4644 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004645 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004646 mCurrentCookedState.cookedPointerData.pointerProperties,
4647 mCurrentCookedState.cookedPointerData.pointerCoords,
4648 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004649 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 }
4651 }
4652}
4653
4654void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4655 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004656 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4657 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 int32_t metaState = getContext()->getGlobalMetaState();
4659 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004660 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004661 mLastCookedState.cookedPointerData.pointerProperties,
4662 mLastCookedState.cookedPointerData.pointerCoords,
4663 mLastCookedState.cookedPointerData.idToIndex,
4664 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4666 mSentHoverEnter = false;
4667 }
4668}
4669
4670void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004671 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4672 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 int32_t metaState = getContext()->getGlobalMetaState();
4674 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004675 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004676 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004677 mCurrentCookedState.cookedPointerData.pointerProperties,
4678 mCurrentCookedState.cookedPointerData.pointerCoords,
4679 mCurrentCookedState.cookedPointerData.idToIndex,
4680 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4682 mSentHoverEnter = true;
4683 }
4684
4685 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004686 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004687 mCurrentRawState.buttonState, 0,
4688 mCurrentCookedState.cookedPointerData.pointerProperties,
4689 mCurrentCookedState.cookedPointerData.pointerCoords,
4690 mCurrentCookedState.cookedPointerData.idToIndex,
4691 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4693 }
4694}
4695
Michael Wright7b159c92015-05-14 14:48:03 +01004696void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4697 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4698 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4699 const int32_t metaState = getContext()->getGlobalMetaState();
4700 int32_t buttonState = mLastCookedState.buttonState;
4701 while (!releasedButtons.isEmpty()) {
4702 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4703 buttonState &= ~actionButton;
4704 dispatchMotion(when, policyFlags, mSource,
4705 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4706 0, metaState, buttonState, 0,
4707 mCurrentCookedState.cookedPointerData.pointerProperties,
4708 mCurrentCookedState.cookedPointerData.pointerCoords,
4709 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4710 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4711 }
4712}
4713
4714void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4715 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4716 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4717 const int32_t metaState = getContext()->getGlobalMetaState();
4718 int32_t buttonState = mLastCookedState.buttonState;
4719 while (!pressedButtons.isEmpty()) {
4720 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4721 buttonState |= actionButton;
4722 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4723 0, metaState, buttonState, 0,
4724 mCurrentCookedState.cookedPointerData.pointerProperties,
4725 mCurrentCookedState.cookedPointerData.pointerCoords,
4726 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4727 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4728 }
4729}
4730
4731const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4732 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4733 return cookedPointerData.touchingIdBits;
4734 }
4735 return cookedPointerData.hoveringIdBits;
4736}
4737
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004739 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740
Michael Wright842500e2015-03-13 17:32:02 -07004741 mCurrentCookedState.cookedPointerData.clear();
4742 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4743 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4744 mCurrentRawState.rawPointerData.hoveringIdBits;
4745 mCurrentCookedState.cookedPointerData.touchingIdBits =
4746 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747
Michael Wright7b159c92015-05-14 14:48:03 +01004748 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4749 mCurrentCookedState.buttonState = 0;
4750 } else {
4751 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4752 }
4753
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 // Walk through the the active pointers and map device coordinates onto
4755 // surface coordinates and adjust for display orientation.
4756 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004757 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
4759 // Size
4760 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4761 switch (mCalibration.sizeCalibration) {
4762 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4763 case Calibration::SIZE_CALIBRATION_DIAMETER:
4764 case Calibration::SIZE_CALIBRATION_BOX:
4765 case Calibration::SIZE_CALIBRATION_AREA:
4766 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4767 touchMajor = in.touchMajor;
4768 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4769 toolMajor = in.toolMajor;
4770 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4771 size = mRawPointerAxes.touchMinor.valid
4772 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4773 } else if (mRawPointerAxes.touchMajor.valid) {
4774 toolMajor = touchMajor = in.touchMajor;
4775 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4776 ? in.touchMinor : in.touchMajor;
4777 size = mRawPointerAxes.touchMinor.valid
4778 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4779 } else if (mRawPointerAxes.toolMajor.valid) {
4780 touchMajor = toolMajor = in.toolMajor;
4781 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4782 ? in.toolMinor : in.toolMajor;
4783 size = mRawPointerAxes.toolMinor.valid
4784 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4785 } else {
4786 ALOG_ASSERT(false, "No touch or tool axes. "
4787 "Size calibration should have been resolved to NONE.");
4788 touchMajor = 0;
4789 touchMinor = 0;
4790 toolMajor = 0;
4791 toolMinor = 0;
4792 size = 0;
4793 }
4794
4795 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004796 uint32_t touchingCount =
4797 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 if (touchingCount > 1) {
4799 touchMajor /= touchingCount;
4800 touchMinor /= touchingCount;
4801 toolMajor /= touchingCount;
4802 toolMinor /= touchingCount;
4803 size /= touchingCount;
4804 }
4805 }
4806
4807 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4808 touchMajor *= mGeometricScale;
4809 touchMinor *= mGeometricScale;
4810 toolMajor *= mGeometricScale;
4811 toolMinor *= mGeometricScale;
4812 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4813 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4814 touchMinor = touchMajor;
4815 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4816 toolMinor = toolMajor;
4817 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4818 touchMinor = touchMajor;
4819 toolMinor = toolMajor;
4820 }
4821
4822 mCalibration.applySizeScaleAndBias(&touchMajor);
4823 mCalibration.applySizeScaleAndBias(&touchMinor);
4824 mCalibration.applySizeScaleAndBias(&toolMajor);
4825 mCalibration.applySizeScaleAndBias(&toolMinor);
4826 size *= mSizeScale;
4827 break;
4828 default:
4829 touchMajor = 0;
4830 touchMinor = 0;
4831 toolMajor = 0;
4832 toolMinor = 0;
4833 size = 0;
4834 break;
4835 }
4836
4837 // Pressure
4838 float pressure;
4839 switch (mCalibration.pressureCalibration) {
4840 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4841 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4842 pressure = in.pressure * mPressureScale;
4843 break;
4844 default:
4845 pressure = in.isHovering ? 0 : 1;
4846 break;
4847 }
4848
4849 // Tilt and Orientation
4850 float tilt;
4851 float orientation;
4852 if (mHaveTilt) {
4853 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4854 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4855 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4856 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4857 } else {
4858 tilt = 0;
4859
4860 switch (mCalibration.orientationCalibration) {
4861 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4862 orientation = in.orientation * mOrientationScale;
4863 break;
4864 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4865 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4866 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4867 if (c1 != 0 || c2 != 0) {
4868 orientation = atan2f(c1, c2) * 0.5f;
4869 float confidence = hypotf(c1, c2);
4870 float scale = 1.0f + confidence / 16.0f;
4871 touchMajor *= scale;
4872 touchMinor /= scale;
4873 toolMajor *= scale;
4874 toolMinor /= scale;
4875 } else {
4876 orientation = 0;
4877 }
4878 break;
4879 }
4880 default:
4881 orientation = 0;
4882 }
4883 }
4884
4885 // Distance
4886 float distance;
4887 switch (mCalibration.distanceCalibration) {
4888 case Calibration::DISTANCE_CALIBRATION_SCALED:
4889 distance = in.distance * mDistanceScale;
4890 break;
4891 default:
4892 distance = 0;
4893 }
4894
4895 // Coverage
4896 int32_t rawLeft, rawTop, rawRight, rawBottom;
4897 switch (mCalibration.coverageCalibration) {
4898 case Calibration::COVERAGE_CALIBRATION_BOX:
4899 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4900 rawRight = in.toolMinor & 0x0000ffff;
4901 rawBottom = in.toolMajor & 0x0000ffff;
4902 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4903 break;
4904 default:
4905 rawLeft = rawTop = rawRight = rawBottom = 0;
4906 break;
4907 }
4908
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004909 // Adjust X,Y coords for device calibration
4910 // TODO: Adjust coverage coords?
4911 float xTransformed = in.x, yTransformed = in.y;
4912 mAffineTransform.applyTo(xTransformed, yTransformed);
4913
4914 // Adjust X, Y, and coverage coords for surface orientation.
4915 float x, y;
4916 float left, top, right, bottom;
4917
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 switch (mSurfaceOrientation) {
4919 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004920 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4921 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4923 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4924 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4925 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4926 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004927 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4929 }
4930 break;
4931 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004932 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4933 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4935 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4936 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4937 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4938 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09004939 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4941 }
4942 break;
4943 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004944 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4945 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4947 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4948 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4949 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4950 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09004951 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4953 }
4954 break;
4955 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004956 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4957 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4959 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4960 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4961 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4962 break;
4963 }
4964
4965 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07004966 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 out.clear();
4968 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4969 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4970 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4971 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4972 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4973 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4974 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4975 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4976 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4977 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4978 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4979 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4980 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4981 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4982 } else {
4983 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4984 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4985 }
4986
4987 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07004988 PointerProperties& properties =
4989 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 uint32_t id = in.id;
4991 properties.clear();
4992 properties.id = id;
4993 properties.toolType = in.toolType;
4994
4995 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07004996 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 }
4998}
4999
5000void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5001 PointerUsage pointerUsage) {
5002 if (pointerUsage != mPointerUsage) {
5003 abortPointerUsage(when, policyFlags);
5004 mPointerUsage = pointerUsage;
5005 }
5006
5007 switch (mPointerUsage) {
5008 case POINTER_USAGE_GESTURES:
5009 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5010 break;
5011 case POINTER_USAGE_STYLUS:
5012 dispatchPointerStylus(when, policyFlags);
5013 break;
5014 case POINTER_USAGE_MOUSE:
5015 dispatchPointerMouse(when, policyFlags);
5016 break;
5017 default:
5018 break;
5019 }
5020}
5021
5022void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5023 switch (mPointerUsage) {
5024 case POINTER_USAGE_GESTURES:
5025 abortPointerGestures(when, policyFlags);
5026 break;
5027 case POINTER_USAGE_STYLUS:
5028 abortPointerStylus(when, policyFlags);
5029 break;
5030 case POINTER_USAGE_MOUSE:
5031 abortPointerMouse(when, policyFlags);
5032 break;
5033 default:
5034 break;
5035 }
5036
5037 mPointerUsage = POINTER_USAGE_NONE;
5038}
5039
5040void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5041 bool isTimeout) {
5042 // Update current gesture coordinates.
5043 bool cancelPreviousGesture, finishPreviousGesture;
5044 bool sendEvents = preparePointerGestures(when,
5045 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5046 if (!sendEvents) {
5047 return;
5048 }
5049 if (finishPreviousGesture) {
5050 cancelPreviousGesture = false;
5051 }
5052
5053 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005054 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5055 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 if (finishPreviousGesture || cancelPreviousGesture) {
5057 mPointerController->clearSpots();
5058 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005059
5060 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5061 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5062 mPointerGesture.currentGestureIdToIndex,
5063 mPointerGesture.currentGestureIdBits);
5064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 } else {
5066 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5067 }
5068
5069 // Show or hide the pointer if needed.
5070 switch (mPointerGesture.currentGestureMode) {
5071 case PointerGesture::NEUTRAL:
5072 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005073 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5074 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 // Remind the user of where the pointer is after finishing a gesture with spots.
5076 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5077 }
5078 break;
5079 case PointerGesture::TAP:
5080 case PointerGesture::TAP_DRAG:
5081 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5082 case PointerGesture::HOVER:
5083 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005084 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085 // Unfade the pointer when the current gesture manipulates the
5086 // area directly under the pointer.
5087 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5088 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 case PointerGesture::FREEFORM:
5090 // Fade the pointer when the current gesture manipulates a different
5091 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005092 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5094 } else {
5095 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5096 }
5097 break;
5098 }
5099
5100 // Send events!
5101 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005102 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103
5104 // Update last coordinates of pointers that have moved so that we observe the new
5105 // pointer positions at the same time as other pointers that have just gone up.
5106 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5107 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5108 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5109 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5110 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5111 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5112 bool moveNeeded = false;
5113 if (down && !cancelPreviousGesture && !finishPreviousGesture
5114 && !mPointerGesture.lastGestureIdBits.isEmpty()
5115 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5116 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5117 & mPointerGesture.lastGestureIdBits.value);
5118 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5119 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5120 mPointerGesture.lastGestureProperties,
5121 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5122 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005123 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 moveNeeded = true;
5125 }
5126 }
5127
5128 // Send motion events for all pointers that went up or were canceled.
5129 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5130 if (!dispatchedGestureIdBits.isEmpty()) {
5131 if (cancelPreviousGesture) {
5132 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005133 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 AMOTION_EVENT_EDGE_FLAG_NONE,
5135 mPointerGesture.lastGestureProperties,
5136 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005137 dispatchedGestureIdBits, -1, 0,
5138 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139
5140 dispatchedGestureIdBits.clear();
5141 } else {
5142 BitSet32 upGestureIdBits;
5143 if (finishPreviousGesture) {
5144 upGestureIdBits = dispatchedGestureIdBits;
5145 } else {
5146 upGestureIdBits.value = dispatchedGestureIdBits.value
5147 & ~mPointerGesture.currentGestureIdBits.value;
5148 }
5149 while (!upGestureIdBits.isEmpty()) {
5150 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5151
5152 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005153 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5155 mPointerGesture.lastGestureProperties,
5156 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5157 dispatchedGestureIdBits, id,
5158 0, 0, mPointerGesture.downTime);
5159
5160 dispatchedGestureIdBits.clearBit(id);
5161 }
5162 }
5163 }
5164
5165 // Send motion events for all pointers that moved.
5166 if (moveNeeded) {
5167 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005168 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5169 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 mPointerGesture.currentGestureProperties,
5171 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5172 dispatchedGestureIdBits, -1,
5173 0, 0, mPointerGesture.downTime);
5174 }
5175
5176 // Send motion events for all pointers that went down.
5177 if (down) {
5178 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5179 & ~dispatchedGestureIdBits.value);
5180 while (!downGestureIdBits.isEmpty()) {
5181 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5182 dispatchedGestureIdBits.markBit(id);
5183
5184 if (dispatchedGestureIdBits.count() == 1) {
5185 mPointerGesture.downTime = when;
5186 }
5187
5188 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005189 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 mPointerGesture.currentGestureProperties,
5191 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5192 dispatchedGestureIdBits, id,
5193 0, 0, mPointerGesture.downTime);
5194 }
5195 }
5196
5197 // Send motion events for hover.
5198 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5199 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005200 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5202 mPointerGesture.currentGestureProperties,
5203 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5204 mPointerGesture.currentGestureIdBits, -1,
5205 0, 0, mPointerGesture.downTime);
5206 } else if (dispatchedGestureIdBits.isEmpty()
5207 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5208 // Synthesize a hover move event after all pointers go up to indicate that
5209 // the pointer is hovering again even if the user is not currently touching
5210 // the touch pad. This ensures that a view will receive a fresh hover enter
5211 // event after a tap.
5212 float x, y;
5213 mPointerController->getPosition(&x, &y);
5214
5215 PointerProperties pointerProperties;
5216 pointerProperties.clear();
5217 pointerProperties.id = 0;
5218 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5219
5220 PointerCoords pointerCoords;
5221 pointerCoords.clear();
5222 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5223 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5224
5225 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005226 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5228 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5229 0, 0, mPointerGesture.downTime);
5230 getListener()->notifyMotion(&args);
5231 }
5232
5233 // Update state.
5234 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5235 if (!down) {
5236 mPointerGesture.lastGestureIdBits.clear();
5237 } else {
5238 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5239 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5240 uint32_t id = idBits.clearFirstMarkedBit();
5241 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5242 mPointerGesture.lastGestureProperties[index].copyFrom(
5243 mPointerGesture.currentGestureProperties[index]);
5244 mPointerGesture.lastGestureCoords[index].copyFrom(
5245 mPointerGesture.currentGestureCoords[index]);
5246 mPointerGesture.lastGestureIdToIndex[id] = index;
5247 }
5248 }
5249}
5250
5251void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5252 // Cancel previously dispatches pointers.
5253 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5254 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005255 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005257 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 AMOTION_EVENT_EDGE_FLAG_NONE,
5259 mPointerGesture.lastGestureProperties,
5260 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5261 mPointerGesture.lastGestureIdBits, -1,
5262 0, 0, mPointerGesture.downTime);
5263 }
5264
5265 // Reset the current pointer gesture.
5266 mPointerGesture.reset();
5267 mPointerVelocityControl.reset();
5268
5269 // Remove any current spots.
5270 if (mPointerController != NULL) {
5271 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5272 mPointerController->clearSpots();
5273 }
5274}
5275
5276bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5277 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5278 *outCancelPreviousGesture = false;
5279 *outFinishPreviousGesture = false;
5280
5281 // Handle TAP timeout.
5282 if (isTimeout) {
5283#if DEBUG_GESTURES
5284 ALOGD("Gestures: Processing timeout");
5285#endif
5286
5287 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5288 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5289 // The tap/drag timeout has not yet expired.
5290 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5291 + mConfig.pointerGestureTapDragInterval);
5292 } else {
5293 // The tap is finished.
5294#if DEBUG_GESTURES
5295 ALOGD("Gestures: TAP finished");
5296#endif
5297 *outFinishPreviousGesture = true;
5298
5299 mPointerGesture.activeGestureId = -1;
5300 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5301 mPointerGesture.currentGestureIdBits.clear();
5302
5303 mPointerVelocityControl.reset();
5304 return true;
5305 }
5306 }
5307
5308 // We did not handle this timeout.
5309 return false;
5310 }
5311
Michael Wright842500e2015-03-13 17:32:02 -07005312 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5313 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314
5315 // Update the velocity tracker.
5316 {
5317 VelocityTracker::Position positions[MAX_POINTERS];
5318 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005319 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005321 const RawPointerData::Pointer& pointer =
5322 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 positions[count].x = pointer.x * mPointerXMovementScale;
5324 positions[count].y = pointer.y * mPointerYMovementScale;
5325 }
5326 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005327 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 }
5329
5330 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5331 // to NEUTRAL, then we should not generate tap event.
5332 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5333 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5334 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5335 mPointerGesture.resetTap();
5336 }
5337
5338 // Pick a new active touch id if needed.
5339 // Choose an arbitrary pointer that just went down, if there is one.
5340 // Otherwise choose an arbitrary remaining pointer.
5341 // This guarantees we always have an active touch id when there is at least one pointer.
5342 // We keep the same active touch id for as long as possible.
5343 bool activeTouchChanged = false;
5344 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5345 int32_t activeTouchId = lastActiveTouchId;
5346 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005347 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 activeTouchChanged = true;
5349 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005350 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 mPointerGesture.firstTouchTime = when;
5352 }
Michael Wright842500e2015-03-13 17:32:02 -07005353 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005355 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005357 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 } else {
5359 activeTouchId = mPointerGesture.activeTouchId = -1;
5360 }
5361 }
5362
5363 // Determine whether we are in quiet time.
5364 bool isQuietTime = false;
5365 if (activeTouchId < 0) {
5366 mPointerGesture.resetQuietTime();
5367 } else {
5368 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5369 if (!isQuietTime) {
5370 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5371 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5372 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5373 && currentFingerCount < 2) {
5374 // Enter quiet time when exiting swipe or freeform state.
5375 // This is to prevent accidentally entering the hover state and flinging the
5376 // pointer when finishing a swipe and there is still one pointer left onscreen.
5377 isQuietTime = true;
5378 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5379 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005380 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 // Enter quiet time when releasing the button and there are still two or more
5382 // fingers down. This may indicate that one finger was used to press the button
5383 // but it has not gone up yet.
5384 isQuietTime = true;
5385 }
5386 if (isQuietTime) {
5387 mPointerGesture.quietTime = when;
5388 }
5389 }
5390 }
5391
5392 // Switch states based on button and pointer state.
5393 if (isQuietTime) {
5394 // Case 1: Quiet time. (QUIET)
5395#if DEBUG_GESTURES
5396 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5397 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5398#endif
5399 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5400 *outFinishPreviousGesture = true;
5401 }
5402
5403 mPointerGesture.activeGestureId = -1;
5404 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5405 mPointerGesture.currentGestureIdBits.clear();
5406
5407 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005408 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5410 // The pointer follows the active touch point.
5411 // Emit DOWN, MOVE, UP events at the pointer location.
5412 //
5413 // Only the active touch matters; other fingers are ignored. This policy helps
5414 // to handle the case where the user places a second finger on the touch pad
5415 // to apply the necessary force to depress an integrated button below the surface.
5416 // We don't want the second finger to be delivered to applications.
5417 //
5418 // For this to work well, we need to make sure to track the pointer that is really
5419 // active. If the user first puts one finger down to click then adds another
5420 // finger to drag then the active pointer should switch to the finger that is
5421 // being dragged.
5422#if DEBUG_GESTURES
5423 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5424 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5425#endif
5426 // Reset state when just starting.
5427 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5428 *outFinishPreviousGesture = true;
5429 mPointerGesture.activeGestureId = 0;
5430 }
5431
5432 // Switch pointers if needed.
5433 // Find the fastest pointer and follow it.
5434 if (activeTouchId >= 0 && currentFingerCount > 1) {
5435 int32_t bestId = -1;
5436 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005437 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 uint32_t id = idBits.clearFirstMarkedBit();
5439 float vx, vy;
5440 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5441 float speed = hypotf(vx, vy);
5442 if (speed > bestSpeed) {
5443 bestId = id;
5444 bestSpeed = speed;
5445 }
5446 }
5447 }
5448 if (bestId >= 0 && bestId != activeTouchId) {
5449 mPointerGesture.activeTouchId = activeTouchId = bestId;
5450 activeTouchChanged = true;
5451#if DEBUG_GESTURES
5452 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5453 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5454#endif
5455 }
5456 }
5457
Jun Mukaifa1706a2015-12-03 01:14:46 -08005458 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005459 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005461 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005463 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005464 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5465 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466
5467 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5468 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5469
5470 // Move the pointer using a relative motion.
5471 // When using spots, the click will occur at the position of the anchor
5472 // spot and all other spots will move there.
5473 mPointerController->move(deltaX, deltaY);
5474 } else {
5475 mPointerVelocityControl.reset();
5476 }
5477
5478 float x, y;
5479 mPointerController->getPosition(&x, &y);
5480
5481 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5482 mPointerGesture.currentGestureIdBits.clear();
5483 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5484 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5485 mPointerGesture.currentGestureProperties[0].clear();
5486 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5487 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5488 mPointerGesture.currentGestureCoords[0].clear();
5489 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5490 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5491 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5492 } else if (currentFingerCount == 0) {
5493 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5494 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5495 *outFinishPreviousGesture = true;
5496 }
5497
5498 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5499 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5500 bool tapped = false;
5501 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5502 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5503 && lastFingerCount == 1) {
5504 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5505 float x, y;
5506 mPointerController->getPosition(&x, &y);
5507 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5508 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5509#if DEBUG_GESTURES
5510 ALOGD("Gestures: TAP");
5511#endif
5512
5513 mPointerGesture.tapUpTime = when;
5514 getContext()->requestTimeoutAtTime(when
5515 + mConfig.pointerGestureTapDragInterval);
5516
5517 mPointerGesture.activeGestureId = 0;
5518 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5519 mPointerGesture.currentGestureIdBits.clear();
5520 mPointerGesture.currentGestureIdBits.markBit(
5521 mPointerGesture.activeGestureId);
5522 mPointerGesture.currentGestureIdToIndex[
5523 mPointerGesture.activeGestureId] = 0;
5524 mPointerGesture.currentGestureProperties[0].clear();
5525 mPointerGesture.currentGestureProperties[0].id =
5526 mPointerGesture.activeGestureId;
5527 mPointerGesture.currentGestureProperties[0].toolType =
5528 AMOTION_EVENT_TOOL_TYPE_FINGER;
5529 mPointerGesture.currentGestureCoords[0].clear();
5530 mPointerGesture.currentGestureCoords[0].setAxisValue(
5531 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5532 mPointerGesture.currentGestureCoords[0].setAxisValue(
5533 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5534 mPointerGesture.currentGestureCoords[0].setAxisValue(
5535 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5536
5537 tapped = true;
5538 } else {
5539#if DEBUG_GESTURES
5540 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5541 x - mPointerGesture.tapX,
5542 y - mPointerGesture.tapY);
5543#endif
5544 }
5545 } else {
5546#if DEBUG_GESTURES
5547 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5548 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5549 (when - mPointerGesture.tapDownTime) * 0.000001f);
5550 } else {
5551 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5552 }
5553#endif
5554 }
5555 }
5556
5557 mPointerVelocityControl.reset();
5558
5559 if (!tapped) {
5560#if DEBUG_GESTURES
5561 ALOGD("Gestures: NEUTRAL");
5562#endif
5563 mPointerGesture.activeGestureId = -1;
5564 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5565 mPointerGesture.currentGestureIdBits.clear();
5566 }
5567 } else if (currentFingerCount == 1) {
5568 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5569 // The pointer follows the active touch point.
5570 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5571 // When in TAP_DRAG, emit MOVE events at the pointer location.
5572 ALOG_ASSERT(activeTouchId >= 0);
5573
5574 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5575 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5576 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5577 float x, y;
5578 mPointerController->getPosition(&x, &y);
5579 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5580 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5581 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5582 } else {
5583#if DEBUG_GESTURES
5584 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5585 x - mPointerGesture.tapX,
5586 y - mPointerGesture.tapY);
5587#endif
5588 }
5589 } else {
5590#if DEBUG_GESTURES
5591 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5592 (when - mPointerGesture.tapUpTime) * 0.000001f);
5593#endif
5594 }
5595 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5596 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5597 }
5598
Jun Mukaifa1706a2015-12-03 01:14:46 -08005599 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005600 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005602 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005604 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005605 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5606 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
5608 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5609 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5610
5611 // Move the pointer using a relative motion.
5612 // When using spots, the hover or drag will occur at the position of the anchor spot.
5613 mPointerController->move(deltaX, deltaY);
5614 } else {
5615 mPointerVelocityControl.reset();
5616 }
5617
5618 bool down;
5619 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5620#if DEBUG_GESTURES
5621 ALOGD("Gestures: TAP_DRAG");
5622#endif
5623 down = true;
5624 } else {
5625#if DEBUG_GESTURES
5626 ALOGD("Gestures: HOVER");
5627#endif
5628 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5629 *outFinishPreviousGesture = true;
5630 }
5631 mPointerGesture.activeGestureId = 0;
5632 down = false;
5633 }
5634
5635 float x, y;
5636 mPointerController->getPosition(&x, &y);
5637
5638 mPointerGesture.currentGestureIdBits.clear();
5639 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5640 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5641 mPointerGesture.currentGestureProperties[0].clear();
5642 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5643 mPointerGesture.currentGestureProperties[0].toolType =
5644 AMOTION_EVENT_TOOL_TYPE_FINGER;
5645 mPointerGesture.currentGestureCoords[0].clear();
5646 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5647 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5648 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5649 down ? 1.0f : 0.0f);
5650
5651 if (lastFingerCount == 0 && currentFingerCount != 0) {
5652 mPointerGesture.resetTap();
5653 mPointerGesture.tapDownTime = when;
5654 mPointerGesture.tapX = x;
5655 mPointerGesture.tapY = y;
5656 }
5657 } else {
5658 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5659 // We need to provide feedback for each finger that goes down so we cannot wait
5660 // for the fingers to move before deciding what to do.
5661 //
5662 // The ambiguous case is deciding what to do when there are two fingers down but they
5663 // have not moved enough to determine whether they are part of a drag or part of a
5664 // freeform gesture, or just a press or long-press at the pointer location.
5665 //
5666 // When there are two fingers we start with the PRESS hypothesis and we generate a
5667 // down at the pointer location.
5668 //
5669 // When the two fingers move enough or when additional fingers are added, we make
5670 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5671 ALOG_ASSERT(activeTouchId >= 0);
5672
5673 bool settled = when >= mPointerGesture.firstTouchTime
5674 + mConfig.pointerGestureMultitouchSettleInterval;
5675 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5676 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5677 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5678 *outFinishPreviousGesture = true;
5679 } else if (!settled && currentFingerCount > lastFingerCount) {
5680 // Additional pointers have gone down but not yet settled.
5681 // Reset the gesture.
5682#if DEBUG_GESTURES
5683 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5684 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5685 + mConfig.pointerGestureMultitouchSettleInterval - when)
5686 * 0.000001f);
5687#endif
5688 *outCancelPreviousGesture = true;
5689 } else {
5690 // Continue previous gesture.
5691 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5692 }
5693
5694 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5695 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5696 mPointerGesture.activeGestureId = 0;
5697 mPointerGesture.referenceIdBits.clear();
5698 mPointerVelocityControl.reset();
5699
5700 // Use the centroid and pointer location as the reference points for the gesture.
5701#if DEBUG_GESTURES
5702 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5703 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5704 + mConfig.pointerGestureMultitouchSettleInterval - when)
5705 * 0.000001f);
5706#endif
Michael Wright842500e2015-03-13 17:32:02 -07005707 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708 &mPointerGesture.referenceTouchX,
5709 &mPointerGesture.referenceTouchY);
5710 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5711 &mPointerGesture.referenceGestureY);
5712 }
5713
5714 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005715 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5717 uint32_t id = idBits.clearFirstMarkedBit();
5718 mPointerGesture.referenceDeltas[id].dx = 0;
5719 mPointerGesture.referenceDeltas[id].dy = 0;
5720 }
Michael Wright842500e2015-03-13 17:32:02 -07005721 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722
5723 // Add delta for all fingers and calculate a common movement delta.
5724 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005725 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5726 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5728 bool first = (idBits == commonIdBits);
5729 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005730 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5731 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5733 delta.dx += cpd.x - lpd.x;
5734 delta.dy += cpd.y - lpd.y;
5735
5736 if (first) {
5737 commonDeltaX = delta.dx;
5738 commonDeltaY = delta.dy;
5739 } else {
5740 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5741 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5742 }
5743 }
5744
5745 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5746 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5747 float dist[MAX_POINTER_ID + 1];
5748 int32_t distOverThreshold = 0;
5749 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5750 uint32_t id = idBits.clearFirstMarkedBit();
5751 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5752 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5753 delta.dy * mPointerYZoomScale);
5754 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5755 distOverThreshold += 1;
5756 }
5757 }
5758
5759 // Only transition when at least two pointers have moved further than
5760 // the minimum distance threshold.
5761 if (distOverThreshold >= 2) {
5762 if (currentFingerCount > 2) {
5763 // There are more than two pointers, switch to FREEFORM.
5764#if DEBUG_GESTURES
5765 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5766 currentFingerCount);
5767#endif
5768 *outCancelPreviousGesture = true;
5769 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5770 } else {
5771 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005772 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 uint32_t id1 = idBits.clearFirstMarkedBit();
5774 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005775 const RawPointerData::Pointer& p1 =
5776 mCurrentRawState.rawPointerData.pointerForId(id1);
5777 const RawPointerData::Pointer& p2 =
5778 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5780 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5781 // There are two pointers but they are too far apart for a SWIPE,
5782 // switch to FREEFORM.
5783#if DEBUG_GESTURES
5784 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5785 mutualDistance, mPointerGestureMaxSwipeWidth);
5786#endif
5787 *outCancelPreviousGesture = true;
5788 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5789 } else {
5790 // There are two pointers. Wait for both pointers to start moving
5791 // before deciding whether this is a SWIPE or FREEFORM gesture.
5792 float dist1 = dist[id1];
5793 float dist2 = dist[id2];
5794 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5795 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5796 // Calculate the dot product of the displacement vectors.
5797 // When the vectors are oriented in approximately the same direction,
5798 // the angle betweeen them is near zero and the cosine of the angle
5799 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5800 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5801 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5802 float dx1 = delta1.dx * mPointerXZoomScale;
5803 float dy1 = delta1.dy * mPointerYZoomScale;
5804 float dx2 = delta2.dx * mPointerXZoomScale;
5805 float dy2 = delta2.dy * mPointerYZoomScale;
5806 float dot = dx1 * dx2 + dy1 * dy2;
5807 float cosine = dot / (dist1 * dist2); // denominator always > 0
5808 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5809 // Pointers are moving in the same direction. Switch to SWIPE.
5810#if DEBUG_GESTURES
5811 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5812 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5813 "cosine %0.3f >= %0.3f",
5814 dist1, mConfig.pointerGestureMultitouchMinDistance,
5815 dist2, mConfig.pointerGestureMultitouchMinDistance,
5816 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5817#endif
5818 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5819 } else {
5820 // Pointers are moving in different directions. Switch to FREEFORM.
5821#if DEBUG_GESTURES
5822 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5823 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5824 "cosine %0.3f < %0.3f",
5825 dist1, mConfig.pointerGestureMultitouchMinDistance,
5826 dist2, mConfig.pointerGestureMultitouchMinDistance,
5827 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5828#endif
5829 *outCancelPreviousGesture = true;
5830 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5831 }
5832 }
5833 }
5834 }
5835 }
5836 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5837 // Switch from SWIPE to FREEFORM if additional pointers go down.
5838 // Cancel previous gesture.
5839 if (currentFingerCount > 2) {
5840#if DEBUG_GESTURES
5841 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5842 currentFingerCount);
5843#endif
5844 *outCancelPreviousGesture = true;
5845 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5846 }
5847 }
5848
5849 // Move the reference points based on the overall group motion of the fingers
5850 // except in PRESS mode while waiting for a transition to occur.
5851 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5852 && (commonDeltaX || commonDeltaY)) {
5853 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5854 uint32_t id = idBits.clearFirstMarkedBit();
5855 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5856 delta.dx = 0;
5857 delta.dy = 0;
5858 }
5859
5860 mPointerGesture.referenceTouchX += commonDeltaX;
5861 mPointerGesture.referenceTouchY += commonDeltaY;
5862
5863 commonDeltaX *= mPointerXMovementScale;
5864 commonDeltaY *= mPointerYMovementScale;
5865
5866 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5867 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5868
5869 mPointerGesture.referenceGestureX += commonDeltaX;
5870 mPointerGesture.referenceGestureY += commonDeltaY;
5871 }
5872
5873 // Report gestures.
5874 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5875 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5876 // PRESS or SWIPE mode.
5877#if DEBUG_GESTURES
5878 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5879 "activeGestureId=%d, currentTouchPointerCount=%d",
5880 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5881#endif
5882 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5883
5884 mPointerGesture.currentGestureIdBits.clear();
5885 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5886 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5887 mPointerGesture.currentGestureProperties[0].clear();
5888 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5889 mPointerGesture.currentGestureProperties[0].toolType =
5890 AMOTION_EVENT_TOOL_TYPE_FINGER;
5891 mPointerGesture.currentGestureCoords[0].clear();
5892 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5893 mPointerGesture.referenceGestureX);
5894 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5895 mPointerGesture.referenceGestureY);
5896 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5897 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5898 // FREEFORM mode.
5899#if DEBUG_GESTURES
5900 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5901 "activeGestureId=%d, currentTouchPointerCount=%d",
5902 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5903#endif
5904 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5905
5906 mPointerGesture.currentGestureIdBits.clear();
5907
5908 BitSet32 mappedTouchIdBits;
5909 BitSet32 usedGestureIdBits;
5910 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5911 // Initially, assign the active gesture id to the active touch point
5912 // if there is one. No other touch id bits are mapped yet.
5913 if (!*outCancelPreviousGesture) {
5914 mappedTouchIdBits.markBit(activeTouchId);
5915 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5916 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5917 mPointerGesture.activeGestureId;
5918 } else {
5919 mPointerGesture.activeGestureId = -1;
5920 }
5921 } else {
5922 // Otherwise, assume we mapped all touches from the previous frame.
5923 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07005924 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
5925 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5927
5928 // Check whether we need to choose a new active gesture id because the
5929 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07005930 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
5931 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932 !upTouchIdBits.isEmpty(); ) {
5933 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5934 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5935 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5936 mPointerGesture.activeGestureId = -1;
5937 break;
5938 }
5939 }
5940 }
5941
5942#if DEBUG_GESTURES
5943 ALOGD("Gestures: FREEFORM follow up "
5944 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5945 "activeGestureId=%d",
5946 mappedTouchIdBits.value, usedGestureIdBits.value,
5947 mPointerGesture.activeGestureId);
5948#endif
5949
Michael Wright842500e2015-03-13 17:32:02 -07005950 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005951 for (uint32_t i = 0; i < currentFingerCount; i++) {
5952 uint32_t touchId = idBits.clearFirstMarkedBit();
5953 uint32_t gestureId;
5954 if (!mappedTouchIdBits.hasBit(touchId)) {
5955 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5956 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5957#if DEBUG_GESTURES
5958 ALOGD("Gestures: FREEFORM "
5959 "new mapping for touch id %d -> gesture id %d",
5960 touchId, gestureId);
5961#endif
5962 } else {
5963 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5964#if DEBUG_GESTURES
5965 ALOGD("Gestures: FREEFORM "
5966 "existing mapping for touch id %d -> gesture id %d",
5967 touchId, gestureId);
5968#endif
5969 }
5970 mPointerGesture.currentGestureIdBits.markBit(gestureId);
5971 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5972
5973 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07005974 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5976 * mPointerXZoomScale;
5977 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5978 * mPointerYZoomScale;
5979 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5980
5981 mPointerGesture.currentGestureProperties[i].clear();
5982 mPointerGesture.currentGestureProperties[i].id = gestureId;
5983 mPointerGesture.currentGestureProperties[i].toolType =
5984 AMOTION_EVENT_TOOL_TYPE_FINGER;
5985 mPointerGesture.currentGestureCoords[i].clear();
5986 mPointerGesture.currentGestureCoords[i].setAxisValue(
5987 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5988 mPointerGesture.currentGestureCoords[i].setAxisValue(
5989 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5990 mPointerGesture.currentGestureCoords[i].setAxisValue(
5991 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5992 }
5993
5994 if (mPointerGesture.activeGestureId < 0) {
5995 mPointerGesture.activeGestureId =
5996 mPointerGesture.currentGestureIdBits.firstMarkedBit();
5997#if DEBUG_GESTURES
5998 ALOGD("Gestures: FREEFORM new "
5999 "activeGestureId=%d", mPointerGesture.activeGestureId);
6000#endif
6001 }
6002 }
6003 }
6004
Michael Wright842500e2015-03-13 17:32:02 -07006005 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006006
6007#if DEBUG_GESTURES
6008 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6009 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6010 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6011 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6012 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6013 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6014 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6015 uint32_t id = idBits.clearFirstMarkedBit();
6016 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6017 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6018 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6019 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6020 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6021 id, index, properties.toolType,
6022 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6023 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6024 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6025 }
6026 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6027 uint32_t id = idBits.clearFirstMarkedBit();
6028 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6029 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6030 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6031 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6032 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6033 id, index, properties.toolType,
6034 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6035 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6036 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6037 }
6038#endif
6039 return true;
6040}
6041
6042void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6043 mPointerSimple.currentCoords.clear();
6044 mPointerSimple.currentProperties.clear();
6045
6046 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006047 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6048 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6049 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6050 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6051 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 mPointerController->setPosition(x, y);
6053
Michael Wright842500e2015-03-13 17:32:02 -07006054 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055 down = !hovering;
6056
6057 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006058 mPointerSimple.currentCoords.copyFrom(
6059 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6061 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6062 mPointerSimple.currentProperties.id = 0;
6063 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006064 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065 } else {
6066 down = false;
6067 hovering = false;
6068 }
6069
6070 dispatchPointerSimple(when, policyFlags, down, hovering);
6071}
6072
6073void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6074 abortPointerSimple(when, policyFlags);
6075}
6076
6077void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6078 mPointerSimple.currentCoords.clear();
6079 mPointerSimple.currentProperties.clear();
6080
6081 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006082 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6083 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6084 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006085 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006086 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6087 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006088 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006089 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006091 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006092 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093 * mPointerYMovementScale;
6094
6095 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6096 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6097
6098 mPointerController->move(deltaX, deltaY);
6099 } else {
6100 mPointerVelocityControl.reset();
6101 }
6102
Michael Wright842500e2015-03-13 17:32:02 -07006103 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006104 hovering = !down;
6105
6106 float x, y;
6107 mPointerController->getPosition(&x, &y);
6108 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006109 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006110 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6111 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6112 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6113 hovering ? 0.0f : 1.0f);
6114 mPointerSimple.currentProperties.id = 0;
6115 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006116 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 } else {
6118 mPointerVelocityControl.reset();
6119
6120 down = false;
6121 hovering = false;
6122 }
6123
6124 dispatchPointerSimple(when, policyFlags, down, hovering);
6125}
6126
6127void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6128 abortPointerSimple(when, policyFlags);
6129
6130 mPointerVelocityControl.reset();
6131}
6132
6133void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6134 bool down, bool hovering) {
6135 int32_t metaState = getContext()->getGlobalMetaState();
6136
6137 if (mPointerController != NULL) {
6138 if (down || hovering) {
6139 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6140 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006141 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006142 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6143 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6144 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6145 }
6146 }
6147
6148 if (mPointerSimple.down && !down) {
6149 mPointerSimple.down = false;
6150
6151 // Send up.
6152 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006153 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006154 mViewport.displayId,
6155 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6156 mOrientedXPrecision, mOrientedYPrecision,
6157 mPointerSimple.downTime);
6158 getListener()->notifyMotion(&args);
6159 }
6160
6161 if (mPointerSimple.hovering && !hovering) {
6162 mPointerSimple.hovering = false;
6163
6164 // Send hover exit.
6165 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006166 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 mViewport.displayId,
6168 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6169 mOrientedXPrecision, mOrientedYPrecision,
6170 mPointerSimple.downTime);
6171 getListener()->notifyMotion(&args);
6172 }
6173
6174 if (down) {
6175 if (!mPointerSimple.down) {
6176 mPointerSimple.down = true;
6177 mPointerSimple.downTime = when;
6178
6179 // Send down.
6180 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006181 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182 mViewport.displayId,
6183 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6184 mOrientedXPrecision, mOrientedYPrecision,
6185 mPointerSimple.downTime);
6186 getListener()->notifyMotion(&args);
6187 }
6188
6189 // Send move.
6190 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006191 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006192 mViewport.displayId,
6193 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6194 mOrientedXPrecision, mOrientedYPrecision,
6195 mPointerSimple.downTime);
6196 getListener()->notifyMotion(&args);
6197 }
6198
6199 if (hovering) {
6200 if (!mPointerSimple.hovering) {
6201 mPointerSimple.hovering = true;
6202
6203 // Send hover enter.
6204 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006205 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006206 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006207 mViewport.displayId,
6208 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6209 mOrientedXPrecision, mOrientedYPrecision,
6210 mPointerSimple.downTime);
6211 getListener()->notifyMotion(&args);
6212 }
6213
6214 // Send hover move.
6215 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006216 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006217 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 mViewport.displayId,
6219 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6220 mOrientedXPrecision, mOrientedYPrecision,
6221 mPointerSimple.downTime);
6222 getListener()->notifyMotion(&args);
6223 }
6224
Michael Wright842500e2015-03-13 17:32:02 -07006225 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6226 float vscroll = mCurrentRawState.rawVScroll;
6227 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 mWheelYVelocityControl.move(when, NULL, &vscroll);
6229 mWheelXVelocityControl.move(when, &hscroll, NULL);
6230
6231 // Send scroll.
6232 PointerCoords pointerCoords;
6233 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6234 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6235 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6236
6237 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006238 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 mViewport.displayId,
6240 1, &mPointerSimple.currentProperties, &pointerCoords,
6241 mOrientedXPrecision, mOrientedYPrecision,
6242 mPointerSimple.downTime);
6243 getListener()->notifyMotion(&args);
6244 }
6245
6246 // Save state.
6247 if (down || hovering) {
6248 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6249 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6250 } else {
6251 mPointerSimple.reset();
6252 }
6253}
6254
6255void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6256 mPointerSimple.currentCoords.clear();
6257 mPointerSimple.currentProperties.clear();
6258
6259 dispatchPointerSimple(when, policyFlags, false, false);
6260}
6261
6262void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006263 int32_t action, int32_t actionButton, int32_t flags,
6264 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006266 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6267 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268 PointerCoords pointerCoords[MAX_POINTERS];
6269 PointerProperties pointerProperties[MAX_POINTERS];
6270 uint32_t pointerCount = 0;
6271 while (!idBits.isEmpty()) {
6272 uint32_t id = idBits.clearFirstMarkedBit();
6273 uint32_t index = idToIndex[id];
6274 pointerProperties[pointerCount].copyFrom(properties[index]);
6275 pointerCoords[pointerCount].copyFrom(coords[index]);
6276
6277 if (changedId >= 0 && id == uint32_t(changedId)) {
6278 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6279 }
6280
6281 pointerCount += 1;
6282 }
6283
6284 ALOG_ASSERT(pointerCount != 0);
6285
6286 if (changedId >= 0 && pointerCount == 1) {
6287 // Replace initial down and final up action.
6288 // We can compare the action without masking off the changed pointer index
6289 // because we know the index is 0.
6290 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6291 action = AMOTION_EVENT_ACTION_DOWN;
6292 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6293 action = AMOTION_EVENT_ACTION_UP;
6294 } else {
6295 // Can't happen.
6296 ALOG_ASSERT(false);
6297 }
6298 }
6299
6300 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006301 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006302 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6303 xPrecision, yPrecision, downTime);
6304 getListener()->notifyMotion(&args);
6305}
6306
6307bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6308 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6309 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6310 BitSet32 idBits) const {
6311 bool changed = false;
6312 while (!idBits.isEmpty()) {
6313 uint32_t id = idBits.clearFirstMarkedBit();
6314 uint32_t inIndex = inIdToIndex[id];
6315 uint32_t outIndex = outIdToIndex[id];
6316
6317 const PointerProperties& curInProperties = inProperties[inIndex];
6318 const PointerCoords& curInCoords = inCoords[inIndex];
6319 PointerProperties& curOutProperties = outProperties[outIndex];
6320 PointerCoords& curOutCoords = outCoords[outIndex];
6321
6322 if (curInProperties != curOutProperties) {
6323 curOutProperties.copyFrom(curInProperties);
6324 changed = true;
6325 }
6326
6327 if (curInCoords != curOutCoords) {
6328 curOutCoords.copyFrom(curInCoords);
6329 changed = true;
6330 }
6331 }
6332 return changed;
6333}
6334
6335void TouchInputMapper::fadePointer() {
6336 if (mPointerController != NULL) {
6337 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6338 }
6339}
6340
Jeff Brownc9aa6282015-02-11 19:03:28 -08006341void TouchInputMapper::cancelTouch(nsecs_t when) {
6342 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006343 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006344}
6345
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6347 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6348 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6349}
6350
6351const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6352 int32_t x, int32_t y) {
6353 size_t numVirtualKeys = mVirtualKeys.size();
6354 for (size_t i = 0; i < numVirtualKeys; i++) {
6355 const VirtualKey& virtualKey = mVirtualKeys[i];
6356
6357#if DEBUG_VIRTUAL_KEYS
6358 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6359 "left=%d, top=%d, right=%d, bottom=%d",
6360 x, y,
6361 virtualKey.keyCode, virtualKey.scanCode,
6362 virtualKey.hitLeft, virtualKey.hitTop,
6363 virtualKey.hitRight, virtualKey.hitBottom);
6364#endif
6365
6366 if (virtualKey.isHit(x, y)) {
6367 return & virtualKey;
6368 }
6369 }
6370
6371 return NULL;
6372}
6373
Michael Wright842500e2015-03-13 17:32:02 -07006374void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6375 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6376 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377
Michael Wright842500e2015-03-13 17:32:02 -07006378 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379
6380 if (currentPointerCount == 0) {
6381 // No pointers to assign.
6382 return;
6383 }
6384
6385 if (lastPointerCount == 0) {
6386 // All pointers are new.
6387 for (uint32_t i = 0; i < currentPointerCount; i++) {
6388 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006389 current->rawPointerData.pointers[i].id = id;
6390 current->rawPointerData.idToIndex[id] = i;
6391 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392 }
6393 return;
6394 }
6395
6396 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006397 && current->rawPointerData.pointers[0].toolType
6398 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006399 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006400 uint32_t id = last->rawPointerData.pointers[0].id;
6401 current->rawPointerData.pointers[0].id = id;
6402 current->rawPointerData.idToIndex[id] = 0;
6403 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404 return;
6405 }
6406
6407 // General case.
6408 // We build a heap of squared euclidean distances between current and last pointers
6409 // associated with the current and last pointer indices. Then, we find the best
6410 // match (by distance) for each current pointer.
6411 // The pointers must have the same tool type but it is possible for them to
6412 // transition from hovering to touching or vice-versa while retaining the same id.
6413 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6414
6415 uint32_t heapSize = 0;
6416 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6417 currentPointerIndex++) {
6418 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6419 lastPointerIndex++) {
6420 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006421 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006422 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006423 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006424 if (currentPointer.toolType == lastPointer.toolType) {
6425 int64_t deltaX = currentPointer.x - lastPointer.x;
6426 int64_t deltaY = currentPointer.y - lastPointer.y;
6427
6428 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6429
6430 // Insert new element into the heap (sift up).
6431 heap[heapSize].currentPointerIndex = currentPointerIndex;
6432 heap[heapSize].lastPointerIndex = lastPointerIndex;
6433 heap[heapSize].distance = distance;
6434 heapSize += 1;
6435 }
6436 }
6437 }
6438
6439 // Heapify
6440 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6441 startIndex -= 1;
6442 for (uint32_t parentIndex = startIndex; ;) {
6443 uint32_t childIndex = parentIndex * 2 + 1;
6444 if (childIndex >= heapSize) {
6445 break;
6446 }
6447
6448 if (childIndex + 1 < heapSize
6449 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6450 childIndex += 1;
6451 }
6452
6453 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6454 break;
6455 }
6456
6457 swap(heap[parentIndex], heap[childIndex]);
6458 parentIndex = childIndex;
6459 }
6460 }
6461
6462#if DEBUG_POINTER_ASSIGNMENT
6463 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6464 for (size_t i = 0; i < heapSize; i++) {
6465 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6466 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6467 heap[i].distance);
6468 }
6469#endif
6470
6471 // Pull matches out by increasing order of distance.
6472 // To avoid reassigning pointers that have already been matched, the loop keeps track
6473 // of which last and current pointers have been matched using the matchedXXXBits variables.
6474 // It also tracks the used pointer id bits.
6475 BitSet32 matchedLastBits(0);
6476 BitSet32 matchedCurrentBits(0);
6477 BitSet32 usedIdBits(0);
6478 bool first = true;
6479 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6480 while (heapSize > 0) {
6481 if (first) {
6482 // The first time through the loop, we just consume the root element of
6483 // the heap (the one with smallest distance).
6484 first = false;
6485 } else {
6486 // Previous iterations consumed the root element of the heap.
6487 // Pop root element off of the heap (sift down).
6488 heap[0] = heap[heapSize];
6489 for (uint32_t parentIndex = 0; ;) {
6490 uint32_t childIndex = parentIndex * 2 + 1;
6491 if (childIndex >= heapSize) {
6492 break;
6493 }
6494
6495 if (childIndex + 1 < heapSize
6496 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6497 childIndex += 1;
6498 }
6499
6500 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6501 break;
6502 }
6503
6504 swap(heap[parentIndex], heap[childIndex]);
6505 parentIndex = childIndex;
6506 }
6507
6508#if DEBUG_POINTER_ASSIGNMENT
6509 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6510 for (size_t i = 0; i < heapSize; i++) {
6511 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6512 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6513 heap[i].distance);
6514 }
6515#endif
6516 }
6517
6518 heapSize -= 1;
6519
6520 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6521 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6522
6523 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6524 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6525
6526 matchedCurrentBits.markBit(currentPointerIndex);
6527 matchedLastBits.markBit(lastPointerIndex);
6528
Michael Wright842500e2015-03-13 17:32:02 -07006529 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6530 current->rawPointerData.pointers[currentPointerIndex].id = id;
6531 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6532 current->rawPointerData.markIdBit(id,
6533 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534 usedIdBits.markBit(id);
6535
6536#if DEBUG_POINTER_ASSIGNMENT
6537 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6538 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6539#endif
6540 break;
6541 }
6542 }
6543
6544 // Assign fresh ids to pointers that were not matched in the process.
6545 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6546 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6547 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6548
Michael Wright842500e2015-03-13 17:32:02 -07006549 current->rawPointerData.pointers[currentPointerIndex].id = id;
6550 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6551 current->rawPointerData.markIdBit(id,
6552 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553
6554#if DEBUG_POINTER_ASSIGNMENT
6555 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6556 currentPointerIndex, id);
6557#endif
6558 }
6559}
6560
6561int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6562 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6563 return AKEY_STATE_VIRTUAL;
6564 }
6565
6566 size_t numVirtualKeys = mVirtualKeys.size();
6567 for (size_t i = 0; i < numVirtualKeys; i++) {
6568 const VirtualKey& virtualKey = mVirtualKeys[i];
6569 if (virtualKey.keyCode == keyCode) {
6570 return AKEY_STATE_UP;
6571 }
6572 }
6573
6574 return AKEY_STATE_UNKNOWN;
6575}
6576
6577int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6578 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6579 return AKEY_STATE_VIRTUAL;
6580 }
6581
6582 size_t numVirtualKeys = mVirtualKeys.size();
6583 for (size_t i = 0; i < numVirtualKeys; i++) {
6584 const VirtualKey& virtualKey = mVirtualKeys[i];
6585 if (virtualKey.scanCode == scanCode) {
6586 return AKEY_STATE_UP;
6587 }
6588 }
6589
6590 return AKEY_STATE_UNKNOWN;
6591}
6592
6593bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6594 const int32_t* keyCodes, uint8_t* outFlags) {
6595 size_t numVirtualKeys = mVirtualKeys.size();
6596 for (size_t i = 0; i < numVirtualKeys; i++) {
6597 const VirtualKey& virtualKey = mVirtualKeys[i];
6598
6599 for (size_t i = 0; i < numCodes; i++) {
6600 if (virtualKey.keyCode == keyCodes[i]) {
6601 outFlags[i] = 1;
6602 }
6603 }
6604 }
6605
6606 return true;
6607}
6608
6609
6610// --- SingleTouchInputMapper ---
6611
6612SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6613 TouchInputMapper(device) {
6614}
6615
6616SingleTouchInputMapper::~SingleTouchInputMapper() {
6617}
6618
6619void SingleTouchInputMapper::reset(nsecs_t when) {
6620 mSingleTouchMotionAccumulator.reset(getDevice());
6621
6622 TouchInputMapper::reset(when);
6623}
6624
6625void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6626 TouchInputMapper::process(rawEvent);
6627
6628 mSingleTouchMotionAccumulator.process(rawEvent);
6629}
6630
Michael Wright842500e2015-03-13 17:32:02 -07006631void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006633 outState->rawPointerData.pointerCount = 1;
6634 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635
6636 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6637 && (mTouchButtonAccumulator.isHovering()
6638 || (mRawPointerAxes.pressure.valid
6639 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006640 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006641
Michael Wright842500e2015-03-13 17:32:02 -07006642 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006643 outPointer.id = 0;
6644 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6645 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6646 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6647 outPointer.touchMajor = 0;
6648 outPointer.touchMinor = 0;
6649 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6650 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6651 outPointer.orientation = 0;
6652 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6653 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6654 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6655 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6656 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6657 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6658 }
6659 outPointer.isHovering = isHovering;
6660 }
6661}
6662
6663void SingleTouchInputMapper::configureRawPointerAxes() {
6664 TouchInputMapper::configureRawPointerAxes();
6665
6666 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6667 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6668 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6669 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6670 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6671 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6672 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6673}
6674
6675bool SingleTouchInputMapper::hasStylus() const {
6676 return mTouchButtonAccumulator.hasStylus();
6677}
6678
6679
6680// --- MultiTouchInputMapper ---
6681
6682MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6683 TouchInputMapper(device) {
6684}
6685
6686MultiTouchInputMapper::~MultiTouchInputMapper() {
6687}
6688
6689void MultiTouchInputMapper::reset(nsecs_t when) {
6690 mMultiTouchMotionAccumulator.reset(getDevice());
6691
6692 mPointerIdBits.clear();
6693
6694 TouchInputMapper::reset(when);
6695}
6696
6697void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6698 TouchInputMapper::process(rawEvent);
6699
6700 mMultiTouchMotionAccumulator.process(rawEvent);
6701}
6702
Michael Wright842500e2015-03-13 17:32:02 -07006703void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006704 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6705 size_t outCount = 0;
6706 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006707 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006708
6709 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6710 const MultiTouchMotionAccumulator::Slot* inSlot =
6711 mMultiTouchMotionAccumulator.getSlot(inIndex);
6712 if (!inSlot->isInUse()) {
6713 continue;
6714 }
6715
6716 if (outCount >= MAX_POINTERS) {
6717#if DEBUG_POINTERS
6718 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6719 "ignoring the rest.",
6720 getDeviceName().string(), MAX_POINTERS);
6721#endif
6722 break; // too many fingers!
6723 }
6724
Michael Wright842500e2015-03-13 17:32:02 -07006725 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006726 outPointer.x = inSlot->getX();
6727 outPointer.y = inSlot->getY();
6728 outPointer.pressure = inSlot->getPressure();
6729 outPointer.touchMajor = inSlot->getTouchMajor();
6730 outPointer.touchMinor = inSlot->getTouchMinor();
6731 outPointer.toolMajor = inSlot->getToolMajor();
6732 outPointer.toolMinor = inSlot->getToolMinor();
6733 outPointer.orientation = inSlot->getOrientation();
6734 outPointer.distance = inSlot->getDistance();
6735 outPointer.tiltX = 0;
6736 outPointer.tiltY = 0;
6737
6738 outPointer.toolType = inSlot->getToolType();
6739 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6740 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6741 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6742 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6743 }
6744 }
6745
6746 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6747 && (mTouchButtonAccumulator.isHovering()
6748 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6749 outPointer.isHovering = isHovering;
6750
6751 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006752 if (mHavePointerIds) {
6753 int32_t trackingId = inSlot->getTrackingId();
6754 int32_t id = -1;
6755 if (trackingId >= 0) {
6756 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6757 uint32_t n = idBits.clearFirstMarkedBit();
6758 if (mPointerTrackingIdMap[n] == trackingId) {
6759 id = n;
6760 }
6761 }
6762
6763 if (id < 0 && !mPointerIdBits.isFull()) {
6764 id = mPointerIdBits.markFirstUnmarkedBit();
6765 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006766 }
Michael Wright842500e2015-03-13 17:32:02 -07006767 }
gaoshang1a632de2016-08-24 10:23:50 +08006768 if (id < 0) {
6769 mHavePointerIds = false;
6770 outState->rawPointerData.clearIdBits();
6771 newPointerIdBits.clear();
6772 } else {
6773 outPointer.id = id;
6774 outState->rawPointerData.idToIndex[id] = outCount;
6775 outState->rawPointerData.markIdBit(id, isHovering);
6776 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006777 }
Michael Wright842500e2015-03-13 17:32:02 -07006778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006779 outCount += 1;
6780 }
6781
Michael Wright842500e2015-03-13 17:32:02 -07006782 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006783 mPointerIdBits = newPointerIdBits;
6784
6785 mMultiTouchMotionAccumulator.finishSync();
6786}
6787
6788void MultiTouchInputMapper::configureRawPointerAxes() {
6789 TouchInputMapper::configureRawPointerAxes();
6790
6791 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6792 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6793 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6794 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6795 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6796 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6797 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6798 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6799 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6800 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6801 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6802
6803 if (mRawPointerAxes.trackingId.valid
6804 && mRawPointerAxes.slot.valid
6805 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6806 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6807 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006808 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6809 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006810 getDeviceName().string(), slotCount, MAX_SLOTS);
6811 slotCount = MAX_SLOTS;
6812 }
6813 mMultiTouchMotionAccumulator.configure(getDevice(),
6814 slotCount, true /*usingSlotsProtocol*/);
6815 } else {
6816 mMultiTouchMotionAccumulator.configure(getDevice(),
6817 MAX_POINTERS, false /*usingSlotsProtocol*/);
6818 }
6819}
6820
6821bool MultiTouchInputMapper::hasStylus() const {
6822 return mMultiTouchMotionAccumulator.hasStylus()
6823 || mTouchButtonAccumulator.hasStylus();
6824}
6825
Michael Wright842500e2015-03-13 17:32:02 -07006826// --- ExternalStylusInputMapper
6827
6828ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6829 InputMapper(device) {
6830
6831}
6832
6833uint32_t ExternalStylusInputMapper::getSources() {
6834 return AINPUT_SOURCE_STYLUS;
6835}
6836
6837void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6838 InputMapper::populateDeviceInfo(info);
6839 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6840 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6841}
6842
6843void ExternalStylusInputMapper::dump(String8& dump) {
6844 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6845 dump.append(INDENT3 "Raw Stylus Axes:\n");
6846 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6847 dump.append(INDENT3 "Stylus State:\n");
6848 dumpStylusState(dump, mStylusState);
6849}
6850
6851void ExternalStylusInputMapper::configure(nsecs_t when,
6852 const InputReaderConfiguration* config, uint32_t changes) {
6853 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6854 mTouchButtonAccumulator.configure(getDevice());
6855}
6856
6857void ExternalStylusInputMapper::reset(nsecs_t when) {
6858 InputDevice* device = getDevice();
6859 mSingleTouchMotionAccumulator.reset(device);
6860 mTouchButtonAccumulator.reset(device);
6861 InputMapper::reset(when);
6862}
6863
6864void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6865 mSingleTouchMotionAccumulator.process(rawEvent);
6866 mTouchButtonAccumulator.process(rawEvent);
6867
6868 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6869 sync(rawEvent->when);
6870 }
6871}
6872
6873void ExternalStylusInputMapper::sync(nsecs_t when) {
6874 mStylusState.clear();
6875
6876 mStylusState.when = when;
6877
Michael Wright45ccacf2015-04-21 19:01:58 +01006878 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6879 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6880 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6881 }
6882
Michael Wright842500e2015-03-13 17:32:02 -07006883 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6884 if (mRawPressureAxis.valid) {
6885 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6886 } else if (mTouchButtonAccumulator.isToolActive()) {
6887 mStylusState.pressure = 1.0f;
6888 } else {
6889 mStylusState.pressure = 0.0f;
6890 }
6891
6892 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07006893
6894 mContext->dispatchExternalStylusState(mStylusState);
6895}
6896
Michael Wrightd02c5b62014-02-10 15:10:22 -08006897
6898// --- JoystickInputMapper ---
6899
6900JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6901 InputMapper(device) {
6902}
6903
6904JoystickInputMapper::~JoystickInputMapper() {
6905}
6906
6907uint32_t JoystickInputMapper::getSources() {
6908 return AINPUT_SOURCE_JOYSTICK;
6909}
6910
6911void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6912 InputMapper::populateDeviceInfo(info);
6913
6914 for (size_t i = 0; i < mAxes.size(); i++) {
6915 const Axis& axis = mAxes.valueAt(i);
6916 addMotionRange(axis.axisInfo.axis, axis, info);
6917
6918 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6919 addMotionRange(axis.axisInfo.highAxis, axis, info);
6920
6921 }
6922 }
6923}
6924
6925void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6926 InputDeviceInfo* info) {
6927 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6928 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6929 /* In order to ease the transition for developers from using the old axes
6930 * to the newer, more semantically correct axes, we'll continue to register
6931 * the old axes as duplicates of their corresponding new ones. */
6932 int32_t compatAxis = getCompatAxis(axisId);
6933 if (compatAxis >= 0) {
6934 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6935 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6936 }
6937}
6938
6939/* A mapping from axes the joystick actually has to the axes that should be
6940 * artificially created for compatibility purposes.
6941 * Returns -1 if no compatibility axis is needed. */
6942int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6943 switch(axis) {
6944 case AMOTION_EVENT_AXIS_LTRIGGER:
6945 return AMOTION_EVENT_AXIS_BRAKE;
6946 case AMOTION_EVENT_AXIS_RTRIGGER:
6947 return AMOTION_EVENT_AXIS_GAS;
6948 }
6949 return -1;
6950}
6951
6952void JoystickInputMapper::dump(String8& dump) {
6953 dump.append(INDENT2 "Joystick Input Mapper:\n");
6954
6955 dump.append(INDENT3 "Axes:\n");
6956 size_t numAxes = mAxes.size();
6957 for (size_t i = 0; i < numAxes; i++) {
6958 const Axis& axis = mAxes.valueAt(i);
6959 const char* label = getAxisLabel(axis.axisInfo.axis);
6960 if (label) {
6961 dump.appendFormat(INDENT4 "%s", label);
6962 } else {
6963 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6964 }
6965 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6966 label = getAxisLabel(axis.axisInfo.highAxis);
6967 if (label) {
6968 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6969 } else {
6970 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6971 axis.axisInfo.splitValue);
6972 }
6973 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6974 dump.append(" (invert)");
6975 }
6976
6977 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6978 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6979 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
6980 "highScale=%0.5f, highOffset=%0.5f\n",
6981 axis.scale, axis.offset, axis.highScale, axis.highOffset);
6982 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
6983 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6984 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6985 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6986 }
6987}
6988
6989void JoystickInputMapper::configure(nsecs_t when,
6990 const InputReaderConfiguration* config, uint32_t changes) {
6991 InputMapper::configure(when, config, changes);
6992
6993 if (!changes) { // first time only
6994 // Collect all axes.
6995 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6996 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6997 & INPUT_DEVICE_CLASS_JOYSTICK)) {
6998 continue; // axis must be claimed by a different device
6999 }
7000
7001 RawAbsoluteAxisInfo rawAxisInfo;
7002 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7003 if (rawAxisInfo.valid) {
7004 // Map axis.
7005 AxisInfo axisInfo;
7006 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7007 if (!explicitlyMapped) {
7008 // Axis is not explicitly mapped, will choose a generic axis later.
7009 axisInfo.mode = AxisInfo::MODE_NORMAL;
7010 axisInfo.axis = -1;
7011 }
7012
7013 // Apply flat override.
7014 int32_t rawFlat = axisInfo.flatOverride < 0
7015 ? rawAxisInfo.flat : axisInfo.flatOverride;
7016
7017 // Calculate scaling factors and limits.
7018 Axis axis;
7019 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7020 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7021 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7022 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7023 scale, 0.0f, highScale, 0.0f,
7024 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7025 rawAxisInfo.resolution * scale);
7026 } else if (isCenteredAxis(axisInfo.axis)) {
7027 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7028 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7029 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7030 scale, offset, scale, offset,
7031 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7032 rawAxisInfo.resolution * scale);
7033 } else {
7034 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7035 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7036 scale, 0.0f, scale, 0.0f,
7037 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7038 rawAxisInfo.resolution * scale);
7039 }
7040
7041 // To eliminate noise while the joystick is at rest, filter out small variations
7042 // in axis values up front.
7043 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7044
7045 mAxes.add(abs, axis);
7046 }
7047 }
7048
7049 // If there are too many axes, start dropping them.
7050 // Prefer to keep explicitly mapped axes.
7051 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007052 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007053 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7054 pruneAxes(true);
7055 pruneAxes(false);
7056 }
7057
7058 // Assign generic axis ids to remaining axes.
7059 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7060 size_t numAxes = mAxes.size();
7061 for (size_t i = 0; i < numAxes; i++) {
7062 Axis& axis = mAxes.editValueAt(i);
7063 if (axis.axisInfo.axis < 0) {
7064 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7065 && haveAxis(nextGenericAxisId)) {
7066 nextGenericAxisId += 1;
7067 }
7068
7069 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7070 axis.axisInfo.axis = nextGenericAxisId;
7071 nextGenericAxisId += 1;
7072 } else {
7073 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7074 "have already been assigned to other axes.",
7075 getDeviceName().string(), mAxes.keyAt(i));
7076 mAxes.removeItemsAt(i--);
7077 numAxes -= 1;
7078 }
7079 }
7080 }
7081 }
7082}
7083
7084bool JoystickInputMapper::haveAxis(int32_t axisId) {
7085 size_t numAxes = mAxes.size();
7086 for (size_t i = 0; i < numAxes; i++) {
7087 const Axis& axis = mAxes.valueAt(i);
7088 if (axis.axisInfo.axis == axisId
7089 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7090 && axis.axisInfo.highAxis == axisId)) {
7091 return true;
7092 }
7093 }
7094 return false;
7095}
7096
7097void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7098 size_t i = mAxes.size();
7099 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7100 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7101 continue;
7102 }
7103 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7104 getDeviceName().string(), mAxes.keyAt(i));
7105 mAxes.removeItemsAt(i);
7106 }
7107}
7108
7109bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7110 switch (axis) {
7111 case AMOTION_EVENT_AXIS_X:
7112 case AMOTION_EVENT_AXIS_Y:
7113 case AMOTION_EVENT_AXIS_Z:
7114 case AMOTION_EVENT_AXIS_RX:
7115 case AMOTION_EVENT_AXIS_RY:
7116 case AMOTION_EVENT_AXIS_RZ:
7117 case AMOTION_EVENT_AXIS_HAT_X:
7118 case AMOTION_EVENT_AXIS_HAT_Y:
7119 case AMOTION_EVENT_AXIS_ORIENTATION:
7120 case AMOTION_EVENT_AXIS_RUDDER:
7121 case AMOTION_EVENT_AXIS_WHEEL:
7122 return true;
7123 default:
7124 return false;
7125 }
7126}
7127
7128void JoystickInputMapper::reset(nsecs_t when) {
7129 // Recenter all axes.
7130 size_t numAxes = mAxes.size();
7131 for (size_t i = 0; i < numAxes; i++) {
7132 Axis& axis = mAxes.editValueAt(i);
7133 axis.resetValue();
7134 }
7135
7136 InputMapper::reset(when);
7137}
7138
7139void JoystickInputMapper::process(const RawEvent* rawEvent) {
7140 switch (rawEvent->type) {
7141 case EV_ABS: {
7142 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7143 if (index >= 0) {
7144 Axis& axis = mAxes.editValueAt(index);
7145 float newValue, highNewValue;
7146 switch (axis.axisInfo.mode) {
7147 case AxisInfo::MODE_INVERT:
7148 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7149 * axis.scale + axis.offset;
7150 highNewValue = 0.0f;
7151 break;
7152 case AxisInfo::MODE_SPLIT:
7153 if (rawEvent->value < axis.axisInfo.splitValue) {
7154 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7155 * axis.scale + axis.offset;
7156 highNewValue = 0.0f;
7157 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7158 newValue = 0.0f;
7159 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7160 * axis.highScale + axis.highOffset;
7161 } else {
7162 newValue = 0.0f;
7163 highNewValue = 0.0f;
7164 }
7165 break;
7166 default:
7167 newValue = rawEvent->value * axis.scale + axis.offset;
7168 highNewValue = 0.0f;
7169 break;
7170 }
7171 axis.newValue = newValue;
7172 axis.highNewValue = highNewValue;
7173 }
7174 break;
7175 }
7176
7177 case EV_SYN:
7178 switch (rawEvent->code) {
7179 case SYN_REPORT:
7180 sync(rawEvent->when, false /*force*/);
7181 break;
7182 }
7183 break;
7184 }
7185}
7186
7187void JoystickInputMapper::sync(nsecs_t when, bool force) {
7188 if (!filterAxes(force)) {
7189 return;
7190 }
7191
7192 int32_t metaState = mContext->getGlobalMetaState();
7193 int32_t buttonState = 0;
7194
7195 PointerProperties pointerProperties;
7196 pointerProperties.clear();
7197 pointerProperties.id = 0;
7198 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7199
7200 PointerCoords pointerCoords;
7201 pointerCoords.clear();
7202
7203 size_t numAxes = mAxes.size();
7204 for (size_t i = 0; i < numAxes; i++) {
7205 const Axis& axis = mAxes.valueAt(i);
7206 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7207 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7208 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7209 axis.highCurrentValue);
7210 }
7211 }
7212
7213 // Moving a joystick axis should not wake the device because joysticks can
7214 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7215 // button will likely wake the device.
7216 // TODO: Use the input device configuration to control this behavior more finely.
7217 uint32_t policyFlags = 0;
7218
7219 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007220 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007221 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7222 getListener()->notifyMotion(&args);
7223}
7224
7225void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7226 int32_t axis, float value) {
7227 pointerCoords->setAxisValue(axis, value);
7228 /* In order to ease the transition for developers from using the old axes
7229 * to the newer, more semantically correct axes, we'll continue to produce
7230 * values for the old axes as mirrors of the value of their corresponding
7231 * new axes. */
7232 int32_t compatAxis = getCompatAxis(axis);
7233 if (compatAxis >= 0) {
7234 pointerCoords->setAxisValue(compatAxis, value);
7235 }
7236}
7237
7238bool JoystickInputMapper::filterAxes(bool force) {
7239 bool atLeastOneSignificantChange = force;
7240 size_t numAxes = mAxes.size();
7241 for (size_t i = 0; i < numAxes; i++) {
7242 Axis& axis = mAxes.editValueAt(i);
7243 if (force || hasValueChangedSignificantly(axis.filter,
7244 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7245 axis.currentValue = axis.newValue;
7246 atLeastOneSignificantChange = true;
7247 }
7248 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7249 if (force || hasValueChangedSignificantly(axis.filter,
7250 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7251 axis.highCurrentValue = axis.highNewValue;
7252 atLeastOneSignificantChange = true;
7253 }
7254 }
7255 }
7256 return atLeastOneSignificantChange;
7257}
7258
7259bool JoystickInputMapper::hasValueChangedSignificantly(
7260 float filter, float newValue, float currentValue, float min, float max) {
7261 if (newValue != currentValue) {
7262 // Filter out small changes in value unless the value is converging on the axis
7263 // bounds or center point. This is intended to reduce the amount of information
7264 // sent to applications by particularly noisy joysticks (such as PS3).
7265 if (fabs(newValue - currentValue) > filter
7266 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7267 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7268 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7269 return true;
7270 }
7271 }
7272 return false;
7273}
7274
7275bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7276 float filter, float newValue, float currentValue, float thresholdValue) {
7277 float newDistance = fabs(newValue - thresholdValue);
7278 if (newDistance < filter) {
7279 float oldDistance = fabs(currentValue - thresholdValue);
7280 if (newDistance < oldDistance) {
7281 return true;
7282 }
7283 }
7284 return false;
7285}
7286
7287} // namespace android