blob: 72c45602ff120a0069a070fd38f445640238a4ef [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
Santos Cordonfa5cf462017-04-05 10:37:00 -0700230bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType,
231 const String8* uniqueDisplayId, DisplayViewport* outViewport) const {
232 const DisplayViewport* viewport = NULL;
233 if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != NULL) {
234 for (DisplayViewport currentViewport : mVirtualDisplays) {
235 if (currentViewport.uniqueId == *uniqueDisplayId) {
236 viewport = &currentViewport;
237 break;
238 }
239 }
240 } else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
241 viewport = &mExternalDisplay;
242 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
243 viewport = &mInternalDisplay;
244 }
245
246 if (viewport != NULL && viewport->displayId >= 0) {
247 *outViewport = *viewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248 return true;
249 }
250 return false;
251}
252
Santos Cordonfa5cf462017-04-05 10:37:00 -0700253void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType,
254 const DisplayViewport& viewport) {
255 if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
256 mExternalDisplay = viewport;
257 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
258 mInternalDisplay = viewport;
259 }
260}
261
262void InputReaderConfiguration::setVirtualDisplayViewports(
263 const Vector<DisplayViewport>& viewports) {
264 mVirtualDisplays = viewports;
265}
266
267void InputReaderConfiguration::dump(String8& dump) const {
268 dump.append(INDENT4 "ViewportInternal:\n");
269 dumpViewport(dump, mInternalDisplay);
270 dump.append(INDENT4 "ViewportExternal:\n");
271 dumpViewport(dump, mExternalDisplay);
272 dump.append(INDENT4 "ViewportVirtual:\n");
273 for (const DisplayViewport& viewport : mVirtualDisplays) {
274 dumpViewport(dump, viewport);
275 }
276}
277
278void InputReaderConfiguration::dumpViewport(String8& dump, const DisplayViewport& viewport) const {
279 dump.appendFormat(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', "
280 "logicalFrame=[%d, %d, %d, %d], "
281 "physicalFrame=[%d, %d, %d, %d], "
282 "deviceSize=[%d, %d]\n",
283 viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(),
284 viewport.logicalLeft, viewport.logicalTop,
285 viewport.logicalRight, viewport.logicalBottom,
286 viewport.physicalLeft, viewport.physicalTop,
287 viewport.physicalRight, viewport.physicalBottom,
288 viewport.deviceWidth, viewport.deviceHeight);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289}
290
291
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700292// -- TouchAffineTransformation --
293void TouchAffineTransformation::applyTo(float& x, float& y) const {
294 float newX, newY;
295 newX = x * x_scale + y * x_ymix + x_offset;
296 newY = x * y_xmix + y * y_scale + y_offset;
297
298 x = newX;
299 y = newY;
300}
301
302
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303// --- InputReader ---
304
305InputReader::InputReader(const sp<EventHubInterface>& eventHub,
306 const sp<InputReaderPolicyInterface>& policy,
307 const sp<InputListenerInterface>& listener) :
308 mContext(this), mEventHub(eventHub), mPolicy(policy),
309 mGlobalMetaState(0), mGeneration(1),
310 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
311 mConfigurationChangesToRefresh(0) {
312 mQueuedListener = new QueuedInputListener(listener);
313
314 { // acquire lock
315 AutoMutex _l(mLock);
316
317 refreshConfigurationLocked(0);
318 updateGlobalMetaStateLocked();
319 } // release lock
320}
321
322InputReader::~InputReader() {
323 for (size_t i = 0; i < mDevices.size(); i++) {
324 delete mDevices.valueAt(i);
325 }
326}
327
328void InputReader::loopOnce() {
329 int32_t oldGeneration;
330 int32_t timeoutMillis;
331 bool inputDevicesChanged = false;
332 Vector<InputDeviceInfo> inputDevices;
333 { // acquire lock
334 AutoMutex _l(mLock);
335
336 oldGeneration = mGeneration;
337 timeoutMillis = -1;
338
339 uint32_t changes = mConfigurationChangesToRefresh;
340 if (changes) {
341 mConfigurationChangesToRefresh = 0;
342 timeoutMillis = 0;
343 refreshConfigurationLocked(changes);
344 } else if (mNextTimeout != LLONG_MAX) {
345 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
346 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
347 }
348 } // release lock
349
350 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
351
352 { // acquire lock
353 AutoMutex _l(mLock);
354 mReaderIsAliveCondition.broadcast();
355
356 if (count) {
357 processEventsLocked(mEventBuffer, count);
358 }
359
360 if (mNextTimeout != LLONG_MAX) {
361 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
362 if (now >= mNextTimeout) {
363#if DEBUG_RAW_EVENTS
364 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
365#endif
366 mNextTimeout = LLONG_MAX;
367 timeoutExpiredLocked(now);
368 }
369 }
370
371 if (oldGeneration != mGeneration) {
372 inputDevicesChanged = true;
373 getInputDevicesLocked(inputDevices);
374 }
375 } // release lock
376
377 // Send out a message that the describes the changed input devices.
378 if (inputDevicesChanged) {
379 mPolicy->notifyInputDevicesChanged(inputDevices);
380 }
381
382 // Flush queued events out to the listener.
383 // This must happen outside of the lock because the listener could potentially call
384 // back into the InputReader's methods, such as getScanCodeState, or become blocked
385 // on another thread similarly waiting to acquire the InputReader lock thereby
386 // resulting in a deadlock. This situation is actually quite plausible because the
387 // listener is actually the input dispatcher, which calls into the window manager,
388 // which occasionally calls into the input reader.
389 mQueuedListener->flush();
390}
391
392void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
393 for (const RawEvent* rawEvent = rawEvents; count;) {
394 int32_t type = rawEvent->type;
395 size_t batchSize = 1;
396 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
397 int32_t deviceId = rawEvent->deviceId;
398 while (batchSize < count) {
399 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
400 || rawEvent[batchSize].deviceId != deviceId) {
401 break;
402 }
403 batchSize += 1;
404 }
405#if DEBUG_RAW_EVENTS
406 ALOGD("BatchSize: %d Count: %d", batchSize, count);
407#endif
408 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
409 } else {
410 switch (rawEvent->type) {
411 case EventHubInterface::DEVICE_ADDED:
412 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
413 break;
414 case EventHubInterface::DEVICE_REMOVED:
415 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
416 break;
417 case EventHubInterface::FINISHED_DEVICE_SCAN:
418 handleConfigurationChangedLocked(rawEvent->when);
419 break;
420 default:
421 ALOG_ASSERT(false); // can't happen
422 break;
423 }
424 }
425 count -= batchSize;
426 rawEvent += batchSize;
427 }
428}
429
430void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
431 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
432 if (deviceIndex >= 0) {
433 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
434 return;
435 }
436
437 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
438 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
439 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
440
441 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
442 device->configure(when, &mConfig, 0);
443 device->reset(when);
444
445 if (device->isIgnored()) {
446 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
447 identifier.name.string());
448 } else {
449 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
450 identifier.name.string(), device->getSources());
451 }
452
453 mDevices.add(deviceId, device);
454 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700455
456 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
457 notifyExternalStylusPresenceChanged();
458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459}
460
461void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
462 InputDevice* device = NULL;
463 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
464 if (deviceIndex < 0) {
465 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
466 return;
467 }
468
469 device = mDevices.valueAt(deviceIndex);
470 mDevices.removeItemsAt(deviceIndex, 1);
471 bumpGenerationLocked();
472
473 if (device->isIgnored()) {
474 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
475 device->getId(), device->getName().string());
476 } else {
477 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
478 device->getId(), device->getName().string(), device->getSources());
479 }
480
Michael Wright842500e2015-03-13 17:32:02 -0700481 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
482 notifyExternalStylusPresenceChanged();
483 }
484
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485 device->reset(when);
486 delete device;
487}
488
489InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
490 const InputDeviceIdentifier& identifier, uint32_t classes) {
491 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
492 controllerNumber, identifier, classes);
493
494 // External devices.
495 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
496 device->setExternal(true);
497 }
498
Tim Kilbourn063ff532015-04-08 10:26:18 -0700499 // Devices with mics.
500 if (classes & INPUT_DEVICE_CLASS_MIC) {
501 device->setMic(true);
502 }
503
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 // Switch-like devices.
505 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
506 device->addMapper(new SwitchInputMapper(device));
507 }
508
Prashant Malani1941ff52015-08-11 18:29:28 -0700509 // Scroll wheel-like devices.
510 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
511 device->addMapper(new RotaryEncoderInputMapper(device));
512 }
513
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 // Vibrator-like devices.
515 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
516 device->addMapper(new VibratorInputMapper(device));
517 }
518
519 // Keyboard-like devices.
520 uint32_t keyboardSource = 0;
521 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
522 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
523 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
524 }
525 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
526 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
527 }
528 if (classes & INPUT_DEVICE_CLASS_DPAD) {
529 keyboardSource |= AINPUT_SOURCE_DPAD;
530 }
531 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
532 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
533 }
534
535 if (keyboardSource != 0) {
536 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
537 }
538
539 // Cursor-like devices.
540 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
541 device->addMapper(new CursorInputMapper(device));
542 }
543
544 // Touchscreens and touchpad devices.
545 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
546 device->addMapper(new MultiTouchInputMapper(device));
547 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
548 device->addMapper(new SingleTouchInputMapper(device));
549 }
550
551 // Joystick-like devices.
552 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
553 device->addMapper(new JoystickInputMapper(device));
554 }
555
Michael Wright842500e2015-03-13 17:32:02 -0700556 // External stylus-like devices.
557 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
558 device->addMapper(new ExternalStylusInputMapper(device));
559 }
560
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 return device;
562}
563
564void InputReader::processEventsForDeviceLocked(int32_t deviceId,
565 const RawEvent* rawEvents, size_t count) {
566 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
567 if (deviceIndex < 0) {
568 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
569 return;
570 }
571
572 InputDevice* device = mDevices.valueAt(deviceIndex);
573 if (device->isIgnored()) {
574 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
575 return;
576 }
577
578 device->process(rawEvents, count);
579}
580
581void InputReader::timeoutExpiredLocked(nsecs_t when) {
582 for (size_t i = 0; i < mDevices.size(); i++) {
583 InputDevice* device = mDevices.valueAt(i);
584 if (!device->isIgnored()) {
585 device->timeoutExpired(when);
586 }
587 }
588}
589
590void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
591 // Reset global meta state because it depends on the list of all configured devices.
592 updateGlobalMetaStateLocked();
593
594 // Enqueue configuration changed.
595 NotifyConfigurationChangedArgs args(when);
596 mQueuedListener->notifyConfigurationChanged(&args);
597}
598
599void InputReader::refreshConfigurationLocked(uint32_t changes) {
600 mPolicy->getReaderConfiguration(&mConfig);
601 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
602
603 if (changes) {
604 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
605 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
606
607 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
608 mEventHub->requestReopenDevices();
609 } else {
610 for (size_t i = 0; i < mDevices.size(); i++) {
611 InputDevice* device = mDevices.valueAt(i);
612 device->configure(now, &mConfig, changes);
613 }
614 }
615 }
616}
617
618void InputReader::updateGlobalMetaStateLocked() {
619 mGlobalMetaState = 0;
620
621 for (size_t i = 0; i < mDevices.size(); i++) {
622 InputDevice* device = mDevices.valueAt(i);
623 mGlobalMetaState |= device->getMetaState();
624 }
625}
626
627int32_t InputReader::getGlobalMetaStateLocked() {
628 return mGlobalMetaState;
629}
630
Michael Wright842500e2015-03-13 17:32:02 -0700631void InputReader::notifyExternalStylusPresenceChanged() {
632 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
633}
634
635void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
636 for (size_t i = 0; i < mDevices.size(); i++) {
637 InputDevice* device = mDevices.valueAt(i);
638 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
639 outDevices.push();
640 device->getDeviceInfo(&outDevices.editTop());
641 }
642 }
643}
644
645void InputReader::dispatchExternalStylusState(const StylusState& state) {
646 for (size_t i = 0; i < mDevices.size(); i++) {
647 InputDevice* device = mDevices.valueAt(i);
648 device->updateExternalStylusState(state);
649 }
650}
651
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
653 mDisableVirtualKeysTimeout = time;
654}
655
656bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
657 InputDevice* device, int32_t keyCode, int32_t scanCode) {
658 if (now < mDisableVirtualKeysTimeout) {
659 ALOGI("Dropping virtual key from device %s because virtual keys are "
660 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
661 device->getName().string(),
662 (mDisableVirtualKeysTimeout - now) * 0.000001,
663 keyCode, scanCode);
664 return true;
665 } else {
666 return false;
667 }
668}
669
670void InputReader::fadePointerLocked() {
671 for (size_t i = 0; i < mDevices.size(); i++) {
672 InputDevice* device = mDevices.valueAt(i);
673 device->fadePointer();
674 }
675}
676
677void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
678 if (when < mNextTimeout) {
679 mNextTimeout = when;
680 mEventHub->wake();
681 }
682}
683
684int32_t InputReader::bumpGenerationLocked() {
685 return ++mGeneration;
686}
687
688void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
689 AutoMutex _l(mLock);
690 getInputDevicesLocked(outInputDevices);
691}
692
693void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
694 outInputDevices.clear();
695
696 size_t numDevices = mDevices.size();
697 for (size_t i = 0; i < numDevices; i++) {
698 InputDevice* device = mDevices.valueAt(i);
699 if (!device->isIgnored()) {
700 outInputDevices.push();
701 device->getDeviceInfo(&outInputDevices.editTop());
702 }
703 }
704}
705
706int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
707 int32_t keyCode) {
708 AutoMutex _l(mLock);
709
710 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
711}
712
713int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
714 int32_t scanCode) {
715 AutoMutex _l(mLock);
716
717 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
718}
719
720int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
721 AutoMutex _l(mLock);
722
723 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
724}
725
726int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
727 GetStateFunc getStateFunc) {
728 int32_t result = AKEY_STATE_UNKNOWN;
729 if (deviceId >= 0) {
730 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
731 if (deviceIndex >= 0) {
732 InputDevice* device = mDevices.valueAt(deviceIndex);
733 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
734 result = (device->*getStateFunc)(sourceMask, code);
735 }
736 }
737 } else {
738 size_t numDevices = mDevices.size();
739 for (size_t i = 0; i < numDevices; i++) {
740 InputDevice* device = mDevices.valueAt(i);
741 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
742 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
743 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
744 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
745 if (currentResult >= AKEY_STATE_DOWN) {
746 return currentResult;
747 } else if (currentResult == AKEY_STATE_UP) {
748 result = currentResult;
749 }
750 }
751 }
752 }
753 return result;
754}
755
Andrii Kulian763a3a42016-03-08 10:46:16 -0800756void InputReader::toggleCapsLockState(int32_t deviceId) {
757 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
758 if (deviceIndex < 0) {
759 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
760 return;
761 }
762
763 InputDevice* device = mDevices.valueAt(deviceIndex);
764 if (device->isIgnored()) {
765 return;
766 }
767
768 device->updateMetaState(AKEYCODE_CAPS_LOCK);
769}
770
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
772 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
773 AutoMutex _l(mLock);
774
775 memset(outFlags, 0, numCodes);
776 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
777}
778
779bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
780 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
781 bool result = false;
782 if (deviceId >= 0) {
783 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
784 if (deviceIndex >= 0) {
785 InputDevice* device = mDevices.valueAt(deviceIndex);
786 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
787 result = device->markSupportedKeyCodes(sourceMask,
788 numCodes, keyCodes, outFlags);
789 }
790 }
791 } else {
792 size_t numDevices = mDevices.size();
793 for (size_t i = 0; i < numDevices; i++) {
794 InputDevice* device = mDevices.valueAt(i);
795 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
796 result |= device->markSupportedKeyCodes(sourceMask,
797 numCodes, keyCodes, outFlags);
798 }
799 }
800 }
801 return result;
802}
803
804void InputReader::requestRefreshConfiguration(uint32_t changes) {
805 AutoMutex _l(mLock);
806
807 if (changes) {
808 bool needWake = !mConfigurationChangesToRefresh;
809 mConfigurationChangesToRefresh |= changes;
810
811 if (needWake) {
812 mEventHub->wake();
813 }
814 }
815}
816
817void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
818 ssize_t repeat, int32_t token) {
819 AutoMutex _l(mLock);
820
821 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
822 if (deviceIndex >= 0) {
823 InputDevice* device = mDevices.valueAt(deviceIndex);
824 device->vibrate(pattern, patternSize, repeat, token);
825 }
826}
827
828void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
829 AutoMutex _l(mLock);
830
831 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
832 if (deviceIndex >= 0) {
833 InputDevice* device = mDevices.valueAt(deviceIndex);
834 device->cancelVibrate(token);
835 }
836}
837
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700838bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
839 AutoMutex _l(mLock);
840
841 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
842 if (deviceIndex >= 0) {
843 InputDevice* device = mDevices.valueAt(deviceIndex);
844 return device->isEnabled();
845 }
846 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
847 return false;
848}
849
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850void InputReader::dump(String8& dump) {
851 AutoMutex _l(mLock);
852
853 mEventHub->dump(dump);
854 dump.append("\n");
855
856 dump.append("Input Reader State:\n");
857
858 for (size_t i = 0; i < mDevices.size(); i++) {
859 mDevices.valueAt(i)->dump(dump);
860 }
861
862 dump.append(INDENT "Configuration:\n");
863 dump.append(INDENT2 "ExcludedDeviceNames: [");
864 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
865 if (i != 0) {
866 dump.append(", ");
867 }
868 dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
869 }
870 dump.append("]\n");
871 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
872 mConfig.virtualKeyQuietTime * 0.000001f);
873
874 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
875 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
876 mConfig.pointerVelocityControlParameters.scale,
877 mConfig.pointerVelocityControlParameters.lowThreshold,
878 mConfig.pointerVelocityControlParameters.highThreshold,
879 mConfig.pointerVelocityControlParameters.acceleration);
880
881 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
882 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
883 mConfig.wheelVelocityControlParameters.scale,
884 mConfig.wheelVelocityControlParameters.lowThreshold,
885 mConfig.wheelVelocityControlParameters.highThreshold,
886 mConfig.wheelVelocityControlParameters.acceleration);
887
888 dump.appendFormat(INDENT2 "PointerGesture:\n");
889 dump.appendFormat(INDENT3 "Enabled: %s\n",
890 toString(mConfig.pointerGesturesEnabled));
891 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
892 mConfig.pointerGestureQuietInterval * 0.000001f);
893 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
894 mConfig.pointerGestureDragMinSwitchSpeed);
895 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
896 mConfig.pointerGestureTapInterval * 0.000001f);
897 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
898 mConfig.pointerGestureTapDragInterval * 0.000001f);
899 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
900 mConfig.pointerGestureTapSlop);
901 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
902 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
903 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
904 mConfig.pointerGestureMultitouchMinDistance);
905 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
906 mConfig.pointerGestureSwipeTransitionAngleCosine);
907 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
908 mConfig.pointerGestureSwipeMaxWidthRatio);
909 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
910 mConfig.pointerGestureMovementSpeedRatio);
911 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
912 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700913
914 dump.append(INDENT3 "Viewports:\n");
915 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916}
917
918void InputReader::monitor() {
919 // Acquire and release the lock to ensure that the reader has not deadlocked.
920 mLock.lock();
921 mEventHub->wake();
922 mReaderIsAliveCondition.wait(mLock);
923 mLock.unlock();
924
925 // Check the EventHub
926 mEventHub->monitor();
927}
928
929
930// --- InputReader::ContextImpl ---
931
932InputReader::ContextImpl::ContextImpl(InputReader* reader) :
933 mReader(reader) {
934}
935
936void InputReader::ContextImpl::updateGlobalMetaState() {
937 // lock is already held by the input loop
938 mReader->updateGlobalMetaStateLocked();
939}
940
941int32_t InputReader::ContextImpl::getGlobalMetaState() {
942 // lock is already held by the input loop
943 return mReader->getGlobalMetaStateLocked();
944}
945
946void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
947 // lock is already held by the input loop
948 mReader->disableVirtualKeysUntilLocked(time);
949}
950
951bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
952 InputDevice* device, int32_t keyCode, int32_t scanCode) {
953 // lock is already held by the input loop
954 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
955}
956
957void InputReader::ContextImpl::fadePointer() {
958 // lock is already held by the input loop
959 mReader->fadePointerLocked();
960}
961
962void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
963 // lock is already held by the input loop
964 mReader->requestTimeoutAtTimeLocked(when);
965}
966
967int32_t InputReader::ContextImpl::bumpGeneration() {
968 // lock is already held by the input loop
969 return mReader->bumpGenerationLocked();
970}
971
Michael Wright842500e2015-03-13 17:32:02 -0700972void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
973 // lock is already held by whatever called refreshConfigurationLocked
974 mReader->getExternalStylusDevicesLocked(outDevices);
975}
976
977void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
978 mReader->dispatchExternalStylusState(state);
979}
980
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
982 return mReader->mPolicy.get();
983}
984
985InputListenerInterface* InputReader::ContextImpl::getListener() {
986 return mReader->mQueuedListener.get();
987}
988
989EventHubInterface* InputReader::ContextImpl::getEventHub() {
990 return mReader->mEventHub.get();
991}
992
993
994// --- InputReaderThread ---
995
996InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
997 Thread(/*canCallJava*/ true), mReader(reader) {
998}
999
1000InputReaderThread::~InputReaderThread() {
1001}
1002
1003bool InputReaderThread::threadLoop() {
1004 mReader->loopOnce();
1005 return true;
1006}
1007
1008
1009// --- InputDevice ---
1010
1011InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1012 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1013 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1014 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001015 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016}
1017
1018InputDevice::~InputDevice() {
1019 size_t numMappers = mMappers.size();
1020 for (size_t i = 0; i < numMappers; i++) {
1021 delete mMappers[i];
1022 }
1023 mMappers.clear();
1024}
1025
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001026bool InputDevice::isEnabled() {
1027 return getEventHub()->isDeviceEnabled(mId);
1028}
1029
1030void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1031 if (isEnabled() == enabled) {
1032 return;
1033 }
1034
1035 if (enabled) {
1036 getEventHub()->enableDevice(mId);
1037 reset(when);
1038 } else {
1039 reset(when);
1040 getEventHub()->disableDevice(mId);
1041 }
1042 // Must change generation to flag this device as changed
1043 bumpGeneration();
1044}
1045
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046void InputDevice::dump(String8& dump) {
1047 InputDeviceInfo deviceInfo;
1048 getDeviceInfo(& deviceInfo);
1049
1050 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
1051 deviceInfo.getDisplayName().string());
1052 dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
1053 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Tim Kilbourn063ff532015-04-08 10:26:18 -07001054 dump.appendFormat(INDENT2 "HasMic: %s\n", toString(mHasMic));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1056 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
1057
1058 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1059 if (!ranges.isEmpty()) {
1060 dump.append(INDENT2 "Motion Ranges:\n");
1061 for (size_t i = 0; i < ranges.size(); i++) {
1062 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1063 const char* label = getAxisLabel(range.axis);
1064 char name[32];
1065 if (label) {
1066 strncpy(name, label, sizeof(name));
1067 name[sizeof(name) - 1] = '\0';
1068 } else {
1069 snprintf(name, sizeof(name), "%d", range.axis);
1070 }
1071 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
1072 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1073 name, range.source, range.min, range.max, range.flat, range.fuzz,
1074 range.resolution);
1075 }
1076 }
1077
1078 size_t numMappers = mMappers.size();
1079 for (size_t i = 0; i < numMappers; i++) {
1080 InputMapper* mapper = mMappers[i];
1081 mapper->dump(dump);
1082 }
1083}
1084
1085void InputDevice::addMapper(InputMapper* mapper) {
1086 mMappers.add(mapper);
1087}
1088
1089void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1090 mSources = 0;
1091
1092 if (!isIgnored()) {
1093 if (!changes) { // first time only
1094 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1095 }
1096
1097 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1098 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1099 sp<KeyCharacterMap> keyboardLayout =
1100 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1101 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1102 bumpGeneration();
1103 }
1104 }
1105 }
1106
1107 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1108 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1109 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1110 if (mAlias != alias) {
1111 mAlias = alias;
1112 bumpGeneration();
1113 }
1114 }
1115 }
1116
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001117 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1118 ssize_t index = config->disabledDevices.indexOf(mId);
1119 bool enabled = index < 0;
1120 setEnabled(enabled, when);
1121 }
1122
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 size_t numMappers = mMappers.size();
1124 for (size_t i = 0; i < numMappers; i++) {
1125 InputMapper* mapper = mMappers[i];
1126 mapper->configure(when, config, changes);
1127 mSources |= mapper->getSources();
1128 }
1129 }
1130}
1131
1132void InputDevice::reset(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->reset(when);
1137 }
1138
1139 mContext->updateGlobalMetaState();
1140
1141 notifyReset(when);
1142}
1143
1144void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1145 // Process all of the events in order for each mapper.
1146 // We cannot simply ask each mapper to process them in bulk because mappers may
1147 // have side-effects that must be interleaved. For example, joystick movement events and
1148 // gamepad button presses are handled by different mappers but they should be dispatched
1149 // in the order received.
1150 size_t numMappers = mMappers.size();
1151 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
1152#if DEBUG_RAW_EVENTS
1153 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
1154 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1155 rawEvent->when);
1156#endif
1157
1158 if (mDropUntilNextSync) {
1159 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1160 mDropUntilNextSync = false;
1161#if DEBUG_RAW_EVENTS
1162 ALOGD("Recovered from input event buffer overrun.");
1163#endif
1164 } else {
1165#if DEBUG_RAW_EVENTS
1166 ALOGD("Dropped input event while waiting for next input sync.");
1167#endif
1168 }
1169 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1170 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1171 mDropUntilNextSync = true;
1172 reset(rawEvent->when);
1173 } else {
1174 for (size_t i = 0; i < numMappers; i++) {
1175 InputMapper* mapper = mMappers[i];
1176 mapper->process(rawEvent);
1177 }
1178 }
1179 }
1180}
1181
1182void InputDevice::timeoutExpired(nsecs_t when) {
1183 size_t numMappers = mMappers.size();
1184 for (size_t i = 0; i < numMappers; i++) {
1185 InputMapper* mapper = mMappers[i];
1186 mapper->timeoutExpired(when);
1187 }
1188}
1189
Michael Wright842500e2015-03-13 17:32:02 -07001190void InputDevice::updateExternalStylusState(const StylusState& state) {
1191 size_t numMappers = mMappers.size();
1192 for (size_t i = 0; i < numMappers; i++) {
1193 InputMapper* mapper = mMappers[i];
1194 mapper->updateExternalStylusState(state);
1195 }
1196}
1197
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1199 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001200 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 size_t numMappers = mMappers.size();
1202 for (size_t i = 0; i < numMappers; i++) {
1203 InputMapper* mapper = mMappers[i];
1204 mapper->populateDeviceInfo(outDeviceInfo);
1205 }
1206}
1207
1208int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1209 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1210}
1211
1212int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1213 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1214}
1215
1216int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1217 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1218}
1219
1220int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1221 int32_t result = AKEY_STATE_UNKNOWN;
1222 size_t numMappers = mMappers.size();
1223 for (size_t i = 0; i < numMappers; i++) {
1224 InputMapper* mapper = mMappers[i];
1225 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1226 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1227 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1228 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1229 if (currentResult >= AKEY_STATE_DOWN) {
1230 return currentResult;
1231 } else if (currentResult == AKEY_STATE_UP) {
1232 result = currentResult;
1233 }
1234 }
1235 }
1236 return result;
1237}
1238
1239bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1240 const int32_t* keyCodes, uint8_t* outFlags) {
1241 bool result = false;
1242 size_t numMappers = mMappers.size();
1243 for (size_t i = 0; i < numMappers; i++) {
1244 InputMapper* mapper = mMappers[i];
1245 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1246 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1247 }
1248 }
1249 return result;
1250}
1251
1252void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1253 int32_t token) {
1254 size_t numMappers = mMappers.size();
1255 for (size_t i = 0; i < numMappers; i++) {
1256 InputMapper* mapper = mMappers[i];
1257 mapper->vibrate(pattern, patternSize, repeat, token);
1258 }
1259}
1260
1261void InputDevice::cancelVibrate(int32_t token) {
1262 size_t numMappers = mMappers.size();
1263 for (size_t i = 0; i < numMappers; i++) {
1264 InputMapper* mapper = mMappers[i];
1265 mapper->cancelVibrate(token);
1266 }
1267}
1268
Jeff Brownc9aa6282015-02-11 19:03:28 -08001269void InputDevice::cancelTouch(nsecs_t when) {
1270 size_t numMappers = mMappers.size();
1271 for (size_t i = 0; i < numMappers; i++) {
1272 InputMapper* mapper = mMappers[i];
1273 mapper->cancelTouch(when);
1274 }
1275}
1276
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277int32_t InputDevice::getMetaState() {
1278 int32_t result = 0;
1279 size_t numMappers = mMappers.size();
1280 for (size_t i = 0; i < numMappers; i++) {
1281 InputMapper* mapper = mMappers[i];
1282 result |= mapper->getMetaState();
1283 }
1284 return result;
1285}
1286
Andrii Kulian763a3a42016-03-08 10:46:16 -08001287void InputDevice::updateMetaState(int32_t keyCode) {
1288 size_t numMappers = mMappers.size();
1289 for (size_t i = 0; i < numMappers; i++) {
1290 mMappers[i]->updateMetaState(keyCode);
1291 }
1292}
1293
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294void InputDevice::fadePointer() {
1295 size_t numMappers = mMappers.size();
1296 for (size_t i = 0; i < numMappers; i++) {
1297 InputMapper* mapper = mMappers[i];
1298 mapper->fadePointer();
1299 }
1300}
1301
1302void InputDevice::bumpGeneration() {
1303 mGeneration = mContext->bumpGeneration();
1304}
1305
1306void InputDevice::notifyReset(nsecs_t when) {
1307 NotifyDeviceResetArgs args(when, mId);
1308 mContext->getListener()->notifyDeviceReset(&args);
1309}
1310
1311
1312// --- CursorButtonAccumulator ---
1313
1314CursorButtonAccumulator::CursorButtonAccumulator() {
1315 clearButtons();
1316}
1317
1318void CursorButtonAccumulator::reset(InputDevice* device) {
1319 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1320 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1321 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1322 mBtnBack = device->isKeyPressed(BTN_BACK);
1323 mBtnSide = device->isKeyPressed(BTN_SIDE);
1324 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1325 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1326 mBtnTask = device->isKeyPressed(BTN_TASK);
1327}
1328
1329void CursorButtonAccumulator::clearButtons() {
1330 mBtnLeft = 0;
1331 mBtnRight = 0;
1332 mBtnMiddle = 0;
1333 mBtnBack = 0;
1334 mBtnSide = 0;
1335 mBtnForward = 0;
1336 mBtnExtra = 0;
1337 mBtnTask = 0;
1338}
1339
1340void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1341 if (rawEvent->type == EV_KEY) {
1342 switch (rawEvent->code) {
1343 case BTN_LEFT:
1344 mBtnLeft = rawEvent->value;
1345 break;
1346 case BTN_RIGHT:
1347 mBtnRight = rawEvent->value;
1348 break;
1349 case BTN_MIDDLE:
1350 mBtnMiddle = rawEvent->value;
1351 break;
1352 case BTN_BACK:
1353 mBtnBack = rawEvent->value;
1354 break;
1355 case BTN_SIDE:
1356 mBtnSide = rawEvent->value;
1357 break;
1358 case BTN_FORWARD:
1359 mBtnForward = rawEvent->value;
1360 break;
1361 case BTN_EXTRA:
1362 mBtnExtra = rawEvent->value;
1363 break;
1364 case BTN_TASK:
1365 mBtnTask = rawEvent->value;
1366 break;
1367 }
1368 }
1369}
1370
1371uint32_t CursorButtonAccumulator::getButtonState() const {
1372 uint32_t result = 0;
1373 if (mBtnLeft) {
1374 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1375 }
1376 if (mBtnRight) {
1377 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1378 }
1379 if (mBtnMiddle) {
1380 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1381 }
1382 if (mBtnBack || mBtnSide) {
1383 result |= AMOTION_EVENT_BUTTON_BACK;
1384 }
1385 if (mBtnForward || mBtnExtra) {
1386 result |= AMOTION_EVENT_BUTTON_FORWARD;
1387 }
1388 return result;
1389}
1390
1391
1392// --- CursorMotionAccumulator ---
1393
1394CursorMotionAccumulator::CursorMotionAccumulator() {
1395 clearRelativeAxes();
1396}
1397
1398void CursorMotionAccumulator::reset(InputDevice* device) {
1399 clearRelativeAxes();
1400}
1401
1402void CursorMotionAccumulator::clearRelativeAxes() {
1403 mRelX = 0;
1404 mRelY = 0;
1405}
1406
1407void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1408 if (rawEvent->type == EV_REL) {
1409 switch (rawEvent->code) {
1410 case REL_X:
1411 mRelX = rawEvent->value;
1412 break;
1413 case REL_Y:
1414 mRelY = rawEvent->value;
1415 break;
1416 }
1417 }
1418}
1419
1420void CursorMotionAccumulator::finishSync() {
1421 clearRelativeAxes();
1422}
1423
1424
1425// --- CursorScrollAccumulator ---
1426
1427CursorScrollAccumulator::CursorScrollAccumulator() :
1428 mHaveRelWheel(false), mHaveRelHWheel(false) {
1429 clearRelativeAxes();
1430}
1431
1432void CursorScrollAccumulator::configure(InputDevice* device) {
1433 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1434 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1435}
1436
1437void CursorScrollAccumulator::reset(InputDevice* device) {
1438 clearRelativeAxes();
1439}
1440
1441void CursorScrollAccumulator::clearRelativeAxes() {
1442 mRelWheel = 0;
1443 mRelHWheel = 0;
1444}
1445
1446void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1447 if (rawEvent->type == EV_REL) {
1448 switch (rawEvent->code) {
1449 case REL_WHEEL:
1450 mRelWheel = rawEvent->value;
1451 break;
1452 case REL_HWHEEL:
1453 mRelHWheel = rawEvent->value;
1454 break;
1455 }
1456 }
1457}
1458
1459void CursorScrollAccumulator::finishSync() {
1460 clearRelativeAxes();
1461}
1462
1463
1464// --- TouchButtonAccumulator ---
1465
1466TouchButtonAccumulator::TouchButtonAccumulator() :
1467 mHaveBtnTouch(false), mHaveStylus(false) {
1468 clearButtons();
1469}
1470
1471void TouchButtonAccumulator::configure(InputDevice* device) {
1472 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1473 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1474 || device->hasKey(BTN_TOOL_RUBBER)
1475 || device->hasKey(BTN_TOOL_BRUSH)
1476 || device->hasKey(BTN_TOOL_PENCIL)
1477 || device->hasKey(BTN_TOOL_AIRBRUSH);
1478}
1479
1480void TouchButtonAccumulator::reset(InputDevice* device) {
1481 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1482 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001483 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1484 mBtnStylus2 =
1485 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1487 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1488 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1489 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1490 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1491 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1492 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1493 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1494 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1495 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1496 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1497}
1498
1499void TouchButtonAccumulator::clearButtons() {
1500 mBtnTouch = 0;
1501 mBtnStylus = 0;
1502 mBtnStylus2 = 0;
1503 mBtnToolFinger = 0;
1504 mBtnToolPen = 0;
1505 mBtnToolRubber = 0;
1506 mBtnToolBrush = 0;
1507 mBtnToolPencil = 0;
1508 mBtnToolAirbrush = 0;
1509 mBtnToolMouse = 0;
1510 mBtnToolLens = 0;
1511 mBtnToolDoubleTap = 0;
1512 mBtnToolTripleTap = 0;
1513 mBtnToolQuadTap = 0;
1514}
1515
1516void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1517 if (rawEvent->type == EV_KEY) {
1518 switch (rawEvent->code) {
1519 case BTN_TOUCH:
1520 mBtnTouch = rawEvent->value;
1521 break;
1522 case BTN_STYLUS:
1523 mBtnStylus = rawEvent->value;
1524 break;
1525 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001526 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 mBtnStylus2 = rawEvent->value;
1528 break;
1529 case BTN_TOOL_FINGER:
1530 mBtnToolFinger = rawEvent->value;
1531 break;
1532 case BTN_TOOL_PEN:
1533 mBtnToolPen = rawEvent->value;
1534 break;
1535 case BTN_TOOL_RUBBER:
1536 mBtnToolRubber = rawEvent->value;
1537 break;
1538 case BTN_TOOL_BRUSH:
1539 mBtnToolBrush = rawEvent->value;
1540 break;
1541 case BTN_TOOL_PENCIL:
1542 mBtnToolPencil = rawEvent->value;
1543 break;
1544 case BTN_TOOL_AIRBRUSH:
1545 mBtnToolAirbrush = rawEvent->value;
1546 break;
1547 case BTN_TOOL_MOUSE:
1548 mBtnToolMouse = rawEvent->value;
1549 break;
1550 case BTN_TOOL_LENS:
1551 mBtnToolLens = rawEvent->value;
1552 break;
1553 case BTN_TOOL_DOUBLETAP:
1554 mBtnToolDoubleTap = rawEvent->value;
1555 break;
1556 case BTN_TOOL_TRIPLETAP:
1557 mBtnToolTripleTap = rawEvent->value;
1558 break;
1559 case BTN_TOOL_QUADTAP:
1560 mBtnToolQuadTap = rawEvent->value;
1561 break;
1562 }
1563 }
1564}
1565
1566uint32_t TouchButtonAccumulator::getButtonState() const {
1567 uint32_t result = 0;
1568 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001569 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001572 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 }
1574 return result;
1575}
1576
1577int32_t TouchButtonAccumulator::getToolType() const {
1578 if (mBtnToolMouse || mBtnToolLens) {
1579 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1580 }
1581 if (mBtnToolRubber) {
1582 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1583 }
1584 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1585 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1586 }
1587 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1588 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1589 }
1590 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1591}
1592
1593bool TouchButtonAccumulator::isToolActive() const {
1594 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1595 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1596 || mBtnToolMouse || mBtnToolLens
1597 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1598}
1599
1600bool TouchButtonAccumulator::isHovering() const {
1601 return mHaveBtnTouch && !mBtnTouch;
1602}
1603
1604bool TouchButtonAccumulator::hasStylus() const {
1605 return mHaveStylus;
1606}
1607
1608
1609// --- RawPointerAxes ---
1610
1611RawPointerAxes::RawPointerAxes() {
1612 clear();
1613}
1614
1615void RawPointerAxes::clear() {
1616 x.clear();
1617 y.clear();
1618 pressure.clear();
1619 touchMajor.clear();
1620 touchMinor.clear();
1621 toolMajor.clear();
1622 toolMinor.clear();
1623 orientation.clear();
1624 distance.clear();
1625 tiltX.clear();
1626 tiltY.clear();
1627 trackingId.clear();
1628 slot.clear();
1629}
1630
1631
1632// --- RawPointerData ---
1633
1634RawPointerData::RawPointerData() {
1635 clear();
1636}
1637
1638void RawPointerData::clear() {
1639 pointerCount = 0;
1640 clearIdBits();
1641}
1642
1643void RawPointerData::copyFrom(const RawPointerData& other) {
1644 pointerCount = other.pointerCount;
1645 hoveringIdBits = other.hoveringIdBits;
1646 touchingIdBits = other.touchingIdBits;
1647
1648 for (uint32_t i = 0; i < pointerCount; i++) {
1649 pointers[i] = other.pointers[i];
1650
1651 int id = pointers[i].id;
1652 idToIndex[id] = other.idToIndex[id];
1653 }
1654}
1655
1656void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1657 float x = 0, y = 0;
1658 uint32_t count = touchingIdBits.count();
1659 if (count) {
1660 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1661 uint32_t id = idBits.clearFirstMarkedBit();
1662 const Pointer& pointer = pointerForId(id);
1663 x += pointer.x;
1664 y += pointer.y;
1665 }
1666 x /= count;
1667 y /= count;
1668 }
1669 *outX = x;
1670 *outY = y;
1671}
1672
1673
1674// --- CookedPointerData ---
1675
1676CookedPointerData::CookedPointerData() {
1677 clear();
1678}
1679
1680void CookedPointerData::clear() {
1681 pointerCount = 0;
1682 hoveringIdBits.clear();
1683 touchingIdBits.clear();
1684}
1685
1686void CookedPointerData::copyFrom(const CookedPointerData& other) {
1687 pointerCount = other.pointerCount;
1688 hoveringIdBits = other.hoveringIdBits;
1689 touchingIdBits = other.touchingIdBits;
1690
1691 for (uint32_t i = 0; i < pointerCount; i++) {
1692 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1693 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1694
1695 int id = pointerProperties[i].id;
1696 idToIndex[id] = other.idToIndex[id];
1697 }
1698}
1699
1700
1701// --- SingleTouchMotionAccumulator ---
1702
1703SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1704 clearAbsoluteAxes();
1705}
1706
1707void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1708 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1709 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1710 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1711 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1712 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1713 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1714 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1715}
1716
1717void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1718 mAbsX = 0;
1719 mAbsY = 0;
1720 mAbsPressure = 0;
1721 mAbsToolWidth = 0;
1722 mAbsDistance = 0;
1723 mAbsTiltX = 0;
1724 mAbsTiltY = 0;
1725}
1726
1727void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1728 if (rawEvent->type == EV_ABS) {
1729 switch (rawEvent->code) {
1730 case ABS_X:
1731 mAbsX = rawEvent->value;
1732 break;
1733 case ABS_Y:
1734 mAbsY = rawEvent->value;
1735 break;
1736 case ABS_PRESSURE:
1737 mAbsPressure = rawEvent->value;
1738 break;
1739 case ABS_TOOL_WIDTH:
1740 mAbsToolWidth = rawEvent->value;
1741 break;
1742 case ABS_DISTANCE:
1743 mAbsDistance = rawEvent->value;
1744 break;
1745 case ABS_TILT_X:
1746 mAbsTiltX = rawEvent->value;
1747 break;
1748 case ABS_TILT_Y:
1749 mAbsTiltY = rawEvent->value;
1750 break;
1751 }
1752 }
1753}
1754
1755
1756// --- MultiTouchMotionAccumulator ---
1757
1758MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1759 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1760 mHaveStylus(false) {
1761}
1762
1763MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1764 delete[] mSlots;
1765}
1766
1767void MultiTouchMotionAccumulator::configure(InputDevice* device,
1768 size_t slotCount, bool usingSlotsProtocol) {
1769 mSlotCount = slotCount;
1770 mUsingSlotsProtocol = usingSlotsProtocol;
1771 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1772
1773 delete[] mSlots;
1774 mSlots = new Slot[slotCount];
1775}
1776
1777void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1778 // Unfortunately there is no way to read the initial contents of the slots.
1779 // So when we reset the accumulator, we must assume they are all zeroes.
1780 if (mUsingSlotsProtocol) {
1781 // Query the driver for the current slot index and use it as the initial slot
1782 // before we start reading events from the device. It is possible that the
1783 // current slot index will not be the same as it was when the first event was
1784 // written into the evdev buffer, which means the input mapper could start
1785 // out of sync with the initial state of the events in the evdev buffer.
1786 // In the extremely unlikely case that this happens, the data from
1787 // two slots will be confused until the next ABS_MT_SLOT event is received.
1788 // This can cause the touch point to "jump", but at least there will be
1789 // no stuck touches.
1790 int32_t initialSlot;
1791 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1792 ABS_MT_SLOT, &initialSlot);
1793 if (status) {
1794 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1795 initialSlot = -1;
1796 }
1797 clearSlots(initialSlot);
1798 } else {
1799 clearSlots(-1);
1800 }
1801}
1802
1803void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1804 if (mSlots) {
1805 for (size_t i = 0; i < mSlotCount; i++) {
1806 mSlots[i].clear();
1807 }
1808 }
1809 mCurrentSlot = initialSlot;
1810}
1811
1812void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1813 if (rawEvent->type == EV_ABS) {
1814 bool newSlot = false;
1815 if (mUsingSlotsProtocol) {
1816 if (rawEvent->code == ABS_MT_SLOT) {
1817 mCurrentSlot = rawEvent->value;
1818 newSlot = true;
1819 }
1820 } else if (mCurrentSlot < 0) {
1821 mCurrentSlot = 0;
1822 }
1823
1824 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1825#if DEBUG_POINTERS
1826 if (newSlot) {
1827 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1828 "should be between 0 and %d; ignoring this slot.",
1829 mCurrentSlot, mSlotCount - 1);
1830 }
1831#endif
1832 } else {
1833 Slot* slot = &mSlots[mCurrentSlot];
1834
1835 switch (rawEvent->code) {
1836 case ABS_MT_POSITION_X:
1837 slot->mInUse = true;
1838 slot->mAbsMTPositionX = rawEvent->value;
1839 break;
1840 case ABS_MT_POSITION_Y:
1841 slot->mInUse = true;
1842 slot->mAbsMTPositionY = rawEvent->value;
1843 break;
1844 case ABS_MT_TOUCH_MAJOR:
1845 slot->mInUse = true;
1846 slot->mAbsMTTouchMajor = rawEvent->value;
1847 break;
1848 case ABS_MT_TOUCH_MINOR:
1849 slot->mInUse = true;
1850 slot->mAbsMTTouchMinor = rawEvent->value;
1851 slot->mHaveAbsMTTouchMinor = true;
1852 break;
1853 case ABS_MT_WIDTH_MAJOR:
1854 slot->mInUse = true;
1855 slot->mAbsMTWidthMajor = rawEvent->value;
1856 break;
1857 case ABS_MT_WIDTH_MINOR:
1858 slot->mInUse = true;
1859 slot->mAbsMTWidthMinor = rawEvent->value;
1860 slot->mHaveAbsMTWidthMinor = true;
1861 break;
1862 case ABS_MT_ORIENTATION:
1863 slot->mInUse = true;
1864 slot->mAbsMTOrientation = rawEvent->value;
1865 break;
1866 case ABS_MT_TRACKING_ID:
1867 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1868 // The slot is no longer in use but it retains its previous contents,
1869 // which may be reused for subsequent touches.
1870 slot->mInUse = false;
1871 } else {
1872 slot->mInUse = true;
1873 slot->mAbsMTTrackingId = rawEvent->value;
1874 }
1875 break;
1876 case ABS_MT_PRESSURE:
1877 slot->mInUse = true;
1878 slot->mAbsMTPressure = rawEvent->value;
1879 break;
1880 case ABS_MT_DISTANCE:
1881 slot->mInUse = true;
1882 slot->mAbsMTDistance = rawEvent->value;
1883 break;
1884 case ABS_MT_TOOL_TYPE:
1885 slot->mInUse = true;
1886 slot->mAbsMTToolType = rawEvent->value;
1887 slot->mHaveAbsMTToolType = true;
1888 break;
1889 }
1890 }
1891 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1892 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1893 mCurrentSlot += 1;
1894 }
1895}
1896
1897void MultiTouchMotionAccumulator::finishSync() {
1898 if (!mUsingSlotsProtocol) {
1899 clearSlots(-1);
1900 }
1901}
1902
1903bool MultiTouchMotionAccumulator::hasStylus() const {
1904 return mHaveStylus;
1905}
1906
1907
1908// --- MultiTouchMotionAccumulator::Slot ---
1909
1910MultiTouchMotionAccumulator::Slot::Slot() {
1911 clear();
1912}
1913
1914void MultiTouchMotionAccumulator::Slot::clear() {
1915 mInUse = false;
1916 mHaveAbsMTTouchMinor = false;
1917 mHaveAbsMTWidthMinor = false;
1918 mHaveAbsMTToolType = false;
1919 mAbsMTPositionX = 0;
1920 mAbsMTPositionY = 0;
1921 mAbsMTTouchMajor = 0;
1922 mAbsMTTouchMinor = 0;
1923 mAbsMTWidthMajor = 0;
1924 mAbsMTWidthMinor = 0;
1925 mAbsMTOrientation = 0;
1926 mAbsMTTrackingId = -1;
1927 mAbsMTPressure = 0;
1928 mAbsMTDistance = 0;
1929 mAbsMTToolType = 0;
1930}
1931
1932int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1933 if (mHaveAbsMTToolType) {
1934 switch (mAbsMTToolType) {
1935 case MT_TOOL_FINGER:
1936 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1937 case MT_TOOL_PEN:
1938 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1939 }
1940 }
1941 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1942}
1943
1944
1945// --- InputMapper ---
1946
1947InputMapper::InputMapper(InputDevice* device) :
1948 mDevice(device), mContext(device->getContext()) {
1949}
1950
1951InputMapper::~InputMapper() {
1952}
1953
1954void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1955 info->addSource(getSources());
1956}
1957
1958void InputMapper::dump(String8& dump) {
1959}
1960
1961void InputMapper::configure(nsecs_t when,
1962 const InputReaderConfiguration* config, uint32_t changes) {
1963}
1964
1965void InputMapper::reset(nsecs_t when) {
1966}
1967
1968void InputMapper::timeoutExpired(nsecs_t when) {
1969}
1970
1971int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1972 return AKEY_STATE_UNKNOWN;
1973}
1974
1975int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1976 return AKEY_STATE_UNKNOWN;
1977}
1978
1979int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1980 return AKEY_STATE_UNKNOWN;
1981}
1982
1983bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1984 const int32_t* keyCodes, uint8_t* outFlags) {
1985 return false;
1986}
1987
1988void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1989 int32_t token) {
1990}
1991
1992void InputMapper::cancelVibrate(int32_t token) {
1993}
1994
Jeff Brownc9aa6282015-02-11 19:03:28 -08001995void InputMapper::cancelTouch(nsecs_t when) {
1996}
1997
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998int32_t InputMapper::getMetaState() {
1999 return 0;
2000}
2001
Andrii Kulian763a3a42016-03-08 10:46:16 -08002002void InputMapper::updateMetaState(int32_t keyCode) {
2003}
2004
Michael Wright842500e2015-03-13 17:32:02 -07002005void InputMapper::updateExternalStylusState(const StylusState& state) {
2006
2007}
2008
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009void InputMapper::fadePointer() {
2010}
2011
2012status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2013 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2014}
2015
2016void InputMapper::bumpGeneration() {
2017 mDevice->bumpGeneration();
2018}
2019
2020void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
2021 const RawAbsoluteAxisInfo& axis, const char* name) {
2022 if (axis.valid) {
2023 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
2024 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2025 } else {
2026 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
2027 }
2028}
2029
Michael Wright842500e2015-03-13 17:32:02 -07002030void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
2031 dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
2032 dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
2033 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
2034 dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
2035}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
2037// --- SwitchInputMapper ---
2038
2039SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002040 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041}
2042
2043SwitchInputMapper::~SwitchInputMapper() {
2044}
2045
2046uint32_t SwitchInputMapper::getSources() {
2047 return AINPUT_SOURCE_SWITCH;
2048}
2049
2050void SwitchInputMapper::process(const RawEvent* rawEvent) {
2051 switch (rawEvent->type) {
2052 case EV_SW:
2053 processSwitch(rawEvent->code, rawEvent->value);
2054 break;
2055
2056 case EV_SYN:
2057 if (rawEvent->code == SYN_REPORT) {
2058 sync(rawEvent->when);
2059 }
2060 }
2061}
2062
2063void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2064 if (switchCode >= 0 && switchCode < 32) {
2065 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002066 mSwitchValues |= 1 << switchCode;
2067 } else {
2068 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
2070 mUpdatedSwitchMask |= 1 << switchCode;
2071 }
2072}
2073
2074void SwitchInputMapper::sync(nsecs_t when) {
2075 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002076 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002077 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 getListener()->notifySwitch(&args);
2079
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 mUpdatedSwitchMask = 0;
2081 }
2082}
2083
2084int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2085 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2086}
2087
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002088void SwitchInputMapper::dump(String8& dump) {
2089 dump.append(INDENT2 "Switch Input Mapper:\n");
2090 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
2091}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092
2093// --- VibratorInputMapper ---
2094
2095VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2096 InputMapper(device), mVibrating(false) {
2097}
2098
2099VibratorInputMapper::~VibratorInputMapper() {
2100}
2101
2102uint32_t VibratorInputMapper::getSources() {
2103 return 0;
2104}
2105
2106void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2107 InputMapper::populateDeviceInfo(info);
2108
2109 info->setVibrator(true);
2110}
2111
2112void VibratorInputMapper::process(const RawEvent* rawEvent) {
2113 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2114}
2115
2116void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2117 int32_t token) {
2118#if DEBUG_VIBRATOR
2119 String8 patternStr;
2120 for (size_t i = 0; i < patternSize; i++) {
2121 if (i != 0) {
2122 patternStr.append(", ");
2123 }
2124 patternStr.appendFormat("%lld", pattern[i]);
2125 }
2126 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
2127 getDeviceId(), patternStr.string(), repeat, token);
2128#endif
2129
2130 mVibrating = true;
2131 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2132 mPatternSize = patternSize;
2133 mRepeat = repeat;
2134 mToken = token;
2135 mIndex = -1;
2136
2137 nextStep();
2138}
2139
2140void VibratorInputMapper::cancelVibrate(int32_t token) {
2141#if DEBUG_VIBRATOR
2142 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2143#endif
2144
2145 if (mVibrating && mToken == token) {
2146 stopVibrating();
2147 }
2148}
2149
2150void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2151 if (mVibrating) {
2152 if (when >= mNextStepTime) {
2153 nextStep();
2154 } else {
2155 getContext()->requestTimeoutAtTime(mNextStepTime);
2156 }
2157 }
2158}
2159
2160void VibratorInputMapper::nextStep() {
2161 mIndex += 1;
2162 if (size_t(mIndex) >= mPatternSize) {
2163 if (mRepeat < 0) {
2164 // We are done.
2165 stopVibrating();
2166 return;
2167 }
2168 mIndex = mRepeat;
2169 }
2170
2171 bool vibratorOn = mIndex & 1;
2172 nsecs_t duration = mPattern[mIndex];
2173 if (vibratorOn) {
2174#if DEBUG_VIBRATOR
2175 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
2176 getDeviceId(), duration);
2177#endif
2178 getEventHub()->vibrate(getDeviceId(), duration);
2179 } else {
2180#if DEBUG_VIBRATOR
2181 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2182#endif
2183 getEventHub()->cancelVibrate(getDeviceId());
2184 }
2185 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2186 mNextStepTime = now + duration;
2187 getContext()->requestTimeoutAtTime(mNextStepTime);
2188#if DEBUG_VIBRATOR
2189 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2190#endif
2191}
2192
2193void VibratorInputMapper::stopVibrating() {
2194 mVibrating = false;
2195#if DEBUG_VIBRATOR
2196 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2197#endif
2198 getEventHub()->cancelVibrate(getDeviceId());
2199}
2200
2201void VibratorInputMapper::dump(String8& dump) {
2202 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2203 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2204}
2205
2206
2207// --- KeyboardInputMapper ---
2208
2209KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2210 uint32_t source, int32_t keyboardType) :
2211 InputMapper(device), mSource(source),
2212 mKeyboardType(keyboardType) {
2213}
2214
2215KeyboardInputMapper::~KeyboardInputMapper() {
2216}
2217
2218uint32_t KeyboardInputMapper::getSources() {
2219 return mSource;
2220}
2221
2222void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2223 InputMapper::populateDeviceInfo(info);
2224
2225 info->setKeyboardType(mKeyboardType);
2226 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2227}
2228
2229void KeyboardInputMapper::dump(String8& dump) {
2230 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2231 dumpParameters(dump);
2232 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2233 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002234 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002236 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237}
2238
2239
2240void KeyboardInputMapper::configure(nsecs_t when,
2241 const InputReaderConfiguration* config, uint32_t changes) {
2242 InputMapper::configure(when, config, changes);
2243
2244 if (!changes) { // first time only
2245 // Configure basic parameters.
2246 configureParameters();
2247 }
2248
2249 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2250 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2251 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002252 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 mOrientation = v.orientation;
2254 } else {
2255 mOrientation = DISPLAY_ORIENTATION_0;
2256 }
2257 } else {
2258 mOrientation = DISPLAY_ORIENTATION_0;
2259 }
2260 }
2261}
2262
2263void KeyboardInputMapper::configureParameters() {
2264 mParameters.orientationAware = false;
2265 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
2266 mParameters.orientationAware);
2267
2268 mParameters.hasAssociatedDisplay = false;
2269 if (mParameters.orientationAware) {
2270 mParameters.hasAssociatedDisplay = true;
2271 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002272
2273 mParameters.handlesKeyRepeat = false;
2274 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.handlesKeyRepeat"),
2275 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276}
2277
2278void KeyboardInputMapper::dumpParameters(String8& dump) {
2279 dump.append(INDENT3 "Parameters:\n");
2280 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2281 toString(mParameters.hasAssociatedDisplay));
2282 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2283 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002284 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2285 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286}
2287
2288void KeyboardInputMapper::reset(nsecs_t when) {
2289 mMetaState = AMETA_NONE;
2290 mDownTime = 0;
2291 mKeyDowns.clear();
2292 mCurrentHidUsage = 0;
2293
2294 resetLedState();
2295
2296 InputMapper::reset(when);
2297}
2298
2299void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2300 switch (rawEvent->type) {
2301 case EV_KEY: {
2302 int32_t scanCode = rawEvent->code;
2303 int32_t usageCode = mCurrentHidUsage;
2304 mCurrentHidUsage = 0;
2305
2306 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002307 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309 break;
2310 }
2311 case EV_MSC: {
2312 if (rawEvent->code == MSC_SCAN) {
2313 mCurrentHidUsage = rawEvent->value;
2314 }
2315 break;
2316 }
2317 case EV_SYN: {
2318 if (rawEvent->code == SYN_REPORT) {
2319 mCurrentHidUsage = 0;
2320 }
2321 }
2322 }
2323}
2324
2325bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2326 return scanCode < BTN_MOUSE
2327 || scanCode >= KEY_OK
2328 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2329 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2330}
2331
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002332void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2333 int32_t usageCode) {
2334 int32_t keyCode;
2335 int32_t keyMetaState;
2336 uint32_t policyFlags;
2337
2338 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2339 &keyCode, &keyMetaState, &policyFlags)) {
2340 keyCode = AKEYCODE_UNKNOWN;
2341 keyMetaState = mMetaState;
2342 policyFlags = 0;
2343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344
2345 if (down) {
2346 // Rotate key codes according to orientation if needed.
2347 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2348 keyCode = rotateKeyCode(keyCode, mOrientation);
2349 }
2350
2351 // Add key down.
2352 ssize_t keyDownIndex = findKeyDown(scanCode);
2353 if (keyDownIndex >= 0) {
2354 // key repeat, be sure to use same keycode as before in case of rotation
2355 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2356 } else {
2357 // key down
2358 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2359 && mContext->shouldDropVirtualKey(when,
2360 getDevice(), keyCode, scanCode)) {
2361 return;
2362 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002363 if (policyFlags & POLICY_FLAG_GESTURE) {
2364 mDevice->cancelTouch(when);
2365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366
2367 mKeyDowns.push();
2368 KeyDown& keyDown = mKeyDowns.editTop();
2369 keyDown.keyCode = keyCode;
2370 keyDown.scanCode = scanCode;
2371 }
2372
2373 mDownTime = when;
2374 } else {
2375 // Remove key down.
2376 ssize_t keyDownIndex = findKeyDown(scanCode);
2377 if (keyDownIndex >= 0) {
2378 // key up, be sure to use same keycode as before in case of rotation
2379 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2380 mKeyDowns.removeAt(size_t(keyDownIndex));
2381 } else {
2382 // key was not actually down
2383 ALOGI("Dropping key up from device %s because the key was not down. "
2384 "keyCode=%d, scanCode=%d",
2385 getDeviceName().string(), keyCode, scanCode);
2386 return;
2387 }
2388 }
2389
Andrii Kulian763a3a42016-03-08 10:46:16 -08002390 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002391 // If global meta state changed send it along with the key.
2392 // If it has not changed then we'll use what keymap gave us,
2393 // since key replacement logic might temporarily reset a few
2394 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002395 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 }
2397
2398 nsecs_t downTime = mDownTime;
2399
2400 // Key down on external an keyboard should wake the device.
2401 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2402 // For internal keyboards, the key layout file should specify the policy flags for
2403 // each wake key individually.
2404 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright872db4f2014-04-22 15:03:51 -07002405 if (down && getDevice()->isExternal()) {
2406 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
2408
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002409 if (mParameters.handlesKeyRepeat) {
2410 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2411 }
2412
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2414 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002415 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 getListener()->notifyKey(&args);
2417}
2418
2419ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2420 size_t n = mKeyDowns.size();
2421 for (size_t i = 0; i < n; i++) {
2422 if (mKeyDowns[i].scanCode == scanCode) {
2423 return i;
2424 }
2425 }
2426 return -1;
2427}
2428
2429int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2430 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2431}
2432
2433int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2434 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2435}
2436
2437bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2438 const int32_t* keyCodes, uint8_t* outFlags) {
2439 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2440}
2441
2442int32_t KeyboardInputMapper::getMetaState() {
2443 return mMetaState;
2444}
2445
Andrii Kulian763a3a42016-03-08 10:46:16 -08002446void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2447 updateMetaStateIfNeeded(keyCode, false);
2448}
2449
2450bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2451 int32_t oldMetaState = mMetaState;
2452 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2453 bool metaStateChanged = oldMetaState != newMetaState;
2454 if (metaStateChanged) {
2455 mMetaState = newMetaState;
2456 updateLedState(false);
2457
2458 getContext()->updateGlobalMetaState();
2459 }
2460
2461 return metaStateChanged;
2462}
2463
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464void KeyboardInputMapper::resetLedState() {
2465 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2466 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2467 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2468
2469 updateLedState(true);
2470}
2471
2472void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2473 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2474 ledState.on = false;
2475}
2476
2477void KeyboardInputMapper::updateLedState(bool reset) {
2478 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2479 AMETA_CAPS_LOCK_ON, reset);
2480 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2481 AMETA_NUM_LOCK_ON, reset);
2482 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2483 AMETA_SCROLL_LOCK_ON, reset);
2484}
2485
2486void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2487 int32_t led, int32_t modifier, bool reset) {
2488 if (ledState.avail) {
2489 bool desiredState = (mMetaState & modifier) != 0;
2490 if (reset || ledState.on != desiredState) {
2491 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2492 ledState.on = desiredState;
2493 }
2494 }
2495}
2496
2497
2498// --- CursorInputMapper ---
2499
2500CursorInputMapper::CursorInputMapper(InputDevice* device) :
2501 InputMapper(device) {
2502}
2503
2504CursorInputMapper::~CursorInputMapper() {
2505}
2506
2507uint32_t CursorInputMapper::getSources() {
2508 return mSource;
2509}
2510
2511void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2512 InputMapper::populateDeviceInfo(info);
2513
2514 if (mParameters.mode == Parameters::MODE_POINTER) {
2515 float minX, minY, maxX, maxY;
2516 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2517 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2518 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2519 }
2520 } else {
2521 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2522 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2523 }
2524 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2525
2526 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2527 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2528 }
2529 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2530 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2531 }
2532}
2533
2534void CursorInputMapper::dump(String8& dump) {
2535 dump.append(INDENT2 "Cursor Input Mapper:\n");
2536 dumpParameters(dump);
2537 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2538 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2539 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2540 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2541 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2542 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2543 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2544 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2545 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2546 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2547 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2548 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2549 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002550 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551}
2552
2553void CursorInputMapper::configure(nsecs_t when,
2554 const InputReaderConfiguration* config, uint32_t changes) {
2555 InputMapper::configure(when, config, changes);
2556
2557 if (!changes) { // first time only
2558 mCursorScrollAccumulator.configure(getDevice());
2559
2560 // Configure basic parameters.
2561 configureParameters();
2562
2563 // Configure device mode.
2564 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002565 case Parameters::MODE_POINTER_RELATIVE:
2566 // Should not happen during first time configuration.
2567 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2568 mParameters.mode = Parameters::MODE_POINTER;
2569 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 case Parameters::MODE_POINTER:
2571 mSource = AINPUT_SOURCE_MOUSE;
2572 mXPrecision = 1.0f;
2573 mYPrecision = 1.0f;
2574 mXScale = 1.0f;
2575 mYScale = 1.0f;
2576 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2577 break;
2578 case Parameters::MODE_NAVIGATION:
2579 mSource = AINPUT_SOURCE_TRACKBALL;
2580 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2581 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2582 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2583 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2584 break;
2585 }
2586
2587 mVWheelScale = 1.0f;
2588 mHWheelScale = 1.0f;
2589 }
2590
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002591 if ((!changes && config->pointerCapture)
2592 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2593 if (config->pointerCapture) {
2594 if (mParameters.mode == Parameters::MODE_POINTER) {
2595 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2596 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2597 // Keep PointerController around in order to preserve the pointer position.
2598 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2599 } else {
2600 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2601 }
2602 } else {
2603 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2604 mParameters.mode = Parameters::MODE_POINTER;
2605 mSource = AINPUT_SOURCE_MOUSE;
2606 } else {
2607 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2608 }
2609 }
2610 bumpGeneration();
2611 if (changes) {
2612 getDevice()->notifyReset(when);
2613 }
2614 }
2615
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2617 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2618 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2619 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2620 }
2621
2622 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2623 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2624 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002625 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 mOrientation = v.orientation;
2627 } else {
2628 mOrientation = DISPLAY_ORIENTATION_0;
2629 }
2630 } else {
2631 mOrientation = DISPLAY_ORIENTATION_0;
2632 }
2633 bumpGeneration();
2634 }
2635}
2636
2637void CursorInputMapper::configureParameters() {
2638 mParameters.mode = Parameters::MODE_POINTER;
2639 String8 cursorModeString;
2640 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2641 if (cursorModeString == "navigation") {
2642 mParameters.mode = Parameters::MODE_NAVIGATION;
2643 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2644 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2645 }
2646 }
2647
2648 mParameters.orientationAware = false;
2649 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2650 mParameters.orientationAware);
2651
2652 mParameters.hasAssociatedDisplay = false;
2653 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2654 mParameters.hasAssociatedDisplay = true;
2655 }
2656}
2657
2658void CursorInputMapper::dumpParameters(String8& dump) {
2659 dump.append(INDENT3 "Parameters:\n");
2660 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2661 toString(mParameters.hasAssociatedDisplay));
2662
2663 switch (mParameters.mode) {
2664 case Parameters::MODE_POINTER:
2665 dump.append(INDENT4 "Mode: pointer\n");
2666 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002667 case Parameters::MODE_POINTER_RELATIVE:
2668 dump.append(INDENT4 "Mode: relative pointer\n");
2669 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 case Parameters::MODE_NAVIGATION:
2671 dump.append(INDENT4 "Mode: navigation\n");
2672 break;
2673 default:
2674 ALOG_ASSERT(false);
2675 }
2676
2677 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2678 toString(mParameters.orientationAware));
2679}
2680
2681void CursorInputMapper::reset(nsecs_t when) {
2682 mButtonState = 0;
2683 mDownTime = 0;
2684
2685 mPointerVelocityControl.reset();
2686 mWheelXVelocityControl.reset();
2687 mWheelYVelocityControl.reset();
2688
2689 mCursorButtonAccumulator.reset(getDevice());
2690 mCursorMotionAccumulator.reset(getDevice());
2691 mCursorScrollAccumulator.reset(getDevice());
2692
2693 InputMapper::reset(when);
2694}
2695
2696void CursorInputMapper::process(const RawEvent* rawEvent) {
2697 mCursorButtonAccumulator.process(rawEvent);
2698 mCursorMotionAccumulator.process(rawEvent);
2699 mCursorScrollAccumulator.process(rawEvent);
2700
2701 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2702 sync(rawEvent->when);
2703 }
2704}
2705
2706void CursorInputMapper::sync(nsecs_t when) {
2707 int32_t lastButtonState = mButtonState;
2708 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2709 mButtonState = currentButtonState;
2710
2711 bool wasDown = isPointerDown(lastButtonState);
2712 bool down = isPointerDown(currentButtonState);
2713 bool downChanged;
2714 if (!wasDown && down) {
2715 mDownTime = when;
2716 downChanged = true;
2717 } else if (wasDown && !down) {
2718 downChanged = true;
2719 } else {
2720 downChanged = false;
2721 }
2722 nsecs_t downTime = mDownTime;
2723 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002724 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2725 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
2727 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2728 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2729 bool moved = deltaX != 0 || deltaY != 0;
2730
2731 // Rotate delta according to orientation if needed.
2732 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2733 && (deltaX != 0.0f || deltaY != 0.0f)) {
2734 rotateDelta(mOrientation, &deltaX, &deltaY);
2735 }
2736
2737 // Move the pointer.
2738 PointerProperties pointerProperties;
2739 pointerProperties.clear();
2740 pointerProperties.id = 0;
2741 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2742
2743 PointerCoords pointerCoords;
2744 pointerCoords.clear();
2745
2746 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2747 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2748 bool scrolled = vscroll != 0 || hscroll != 0;
2749
2750 mWheelYVelocityControl.move(when, NULL, &vscroll);
2751 mWheelXVelocityControl.move(when, &hscroll, NULL);
2752
2753 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2754
2755 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002756 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 if (moved || scrolled || buttonsChanged) {
2758 mPointerController->setPresentation(
2759 PointerControllerInterface::PRESENTATION_POINTER);
2760
2761 if (moved) {
2762 mPointerController->move(deltaX, deltaY);
2763 }
2764
2765 if (buttonsChanged) {
2766 mPointerController->setButtonState(currentButtonState);
2767 }
2768
2769 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2770 }
2771
2772 float x, y;
2773 mPointerController->getPosition(&x, &y);
2774 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2775 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002776 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2777 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 displayId = ADISPLAY_ID_DEFAULT;
2779 } else {
2780 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2781 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2782 displayId = ADISPLAY_ID_NONE;
2783 }
2784
2785 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2786
2787 // Moving an external trackball or mouse should wake the device.
2788 // We don't do this for internal cursor devices to prevent them from waking up
2789 // the device in your pocket.
2790 // TODO: Use the input device configuration to control this behavior more finely.
2791 uint32_t policyFlags = 0;
2792 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002793 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 }
2795
2796 // Synthesize key down from buttons if needed.
2797 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2798 policyFlags, lastButtonState, currentButtonState);
2799
2800 // Send motion event.
2801 if (downChanged || moved || scrolled || buttonsChanged) {
2802 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002803 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 int32_t motionEventAction;
2805 if (downChanged) {
2806 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002807 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2809 } else {
2810 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2811 }
2812
Michael Wright7b159c92015-05-14 14:48:03 +01002813 if (buttonsReleased) {
2814 BitSet32 released(buttonsReleased);
2815 while (!released.isEmpty()) {
2816 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2817 buttonState &= ~actionButton;
2818 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2819 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2820 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2821 displayId, 1, &pointerProperties, &pointerCoords,
2822 mXPrecision, mYPrecision, downTime);
2823 getListener()->notifyMotion(&releaseArgs);
2824 }
2825 }
2826
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002828 motionEventAction, 0, 0, metaState, currentButtonState,
2829 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 displayId, 1, &pointerProperties, &pointerCoords,
2831 mXPrecision, mYPrecision, downTime);
2832 getListener()->notifyMotion(&args);
2833
Michael Wright7b159c92015-05-14 14:48:03 +01002834 if (buttonsPressed) {
2835 BitSet32 pressed(buttonsPressed);
2836 while (!pressed.isEmpty()) {
2837 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2838 buttonState |= actionButton;
2839 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2840 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2841 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2842 displayId, 1, &pointerProperties, &pointerCoords,
2843 mXPrecision, mYPrecision, downTime);
2844 getListener()->notifyMotion(&pressArgs);
2845 }
2846 }
2847
2848 ALOG_ASSERT(buttonState == currentButtonState);
2849
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 // Send hover move after UP to tell the application that the mouse is hovering now.
2851 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002852 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002854 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2856 displayId, 1, &pointerProperties, &pointerCoords,
2857 mXPrecision, mYPrecision, downTime);
2858 getListener()->notifyMotion(&hoverArgs);
2859 }
2860
2861 // Send scroll events.
2862 if (scrolled) {
2863 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2864 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2865
2866 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002867 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 AMOTION_EVENT_EDGE_FLAG_NONE,
2869 displayId, 1, &pointerProperties, &pointerCoords,
2870 mXPrecision, mYPrecision, downTime);
2871 getListener()->notifyMotion(&scrollArgs);
2872 }
2873 }
2874
2875 // Synthesize key up from buttons if needed.
2876 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2877 policyFlags, lastButtonState, currentButtonState);
2878
2879 mCursorMotionAccumulator.finishSync();
2880 mCursorScrollAccumulator.finishSync();
2881}
2882
2883int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2884 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2885 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2886 } else {
2887 return AKEY_STATE_UNKNOWN;
2888 }
2889}
2890
2891void CursorInputMapper::fadePointer() {
2892 if (mPointerController != NULL) {
2893 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2894 }
2895}
2896
Prashant Malani1941ff52015-08-11 18:29:28 -07002897// --- RotaryEncoderInputMapper ---
2898
2899RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002900 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002901 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2902}
2903
2904RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2905}
2906
2907uint32_t RotaryEncoderInputMapper::getSources() {
2908 return mSource;
2909}
2910
2911void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2912 InputMapper::populateDeviceInfo(info);
2913
2914 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002915 float res = 0.0f;
2916 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2917 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2918 }
2919 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2920 mScalingFactor)) {
2921 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2922 "default to 1.0!\n");
2923 mScalingFactor = 1.0f;
2924 }
2925 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2926 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002927 }
2928}
2929
2930void RotaryEncoderInputMapper::dump(String8& dump) {
2931 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2932 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2933 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2934}
2935
2936void RotaryEncoderInputMapper::configure(nsecs_t when,
2937 const InputReaderConfiguration* config, uint32_t changes) {
2938 InputMapper::configure(when, config, changes);
2939 if (!changes) {
2940 mRotaryEncoderScrollAccumulator.configure(getDevice());
2941 }
Ivan Podogovad437252016-09-29 16:29:55 +01002942 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2943 DisplayViewport v;
2944 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
2945 mOrientation = v.orientation;
2946 } else {
2947 mOrientation = DISPLAY_ORIENTATION_0;
2948 }
2949 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002950}
2951
2952void RotaryEncoderInputMapper::reset(nsecs_t when) {
2953 mRotaryEncoderScrollAccumulator.reset(getDevice());
2954
2955 InputMapper::reset(when);
2956}
2957
2958void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2959 mRotaryEncoderScrollAccumulator.process(rawEvent);
2960
2961 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2962 sync(rawEvent->when);
2963 }
2964}
2965
2966void RotaryEncoderInputMapper::sync(nsecs_t when) {
2967 PointerCoords pointerCoords;
2968 pointerCoords.clear();
2969
2970 PointerProperties pointerProperties;
2971 pointerProperties.clear();
2972 pointerProperties.id = 0;
2973 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2974
2975 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2976 bool scrolled = scroll != 0;
2977
2978 // This is not a pointer, so it's not associated with a display.
2979 int32_t displayId = ADISPLAY_ID_NONE;
2980
2981 // Moving the rotary encoder should wake the device (if specified).
2982 uint32_t policyFlags = 0;
2983 if (scrolled && getDevice()->isExternal()) {
2984 policyFlags |= POLICY_FLAG_WAKE;
2985 }
2986
Ivan Podogovad437252016-09-29 16:29:55 +01002987 if (mOrientation == DISPLAY_ORIENTATION_180) {
2988 scroll = -scroll;
2989 }
2990
Prashant Malani1941ff52015-08-11 18:29:28 -07002991 // Send motion event.
2992 if (scrolled) {
2993 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002994 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002995
2996 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2997 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2998 AMOTION_EVENT_EDGE_FLAG_NONE,
2999 displayId, 1, &pointerProperties, &pointerCoords,
3000 0, 0, 0);
3001 getListener()->notifyMotion(&scrollArgs);
3002 }
3003
3004 mRotaryEncoderScrollAccumulator.finishSync();
3005}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
3007// --- TouchInputMapper ---
3008
3009TouchInputMapper::TouchInputMapper(InputDevice* device) :
3010 InputMapper(device),
3011 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3012 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3013 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3014}
3015
3016TouchInputMapper::~TouchInputMapper() {
3017}
3018
3019uint32_t TouchInputMapper::getSources() {
3020 return mSource;
3021}
3022
3023void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3024 InputMapper::populateDeviceInfo(info);
3025
3026 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3027 info->addMotionRange(mOrientedRanges.x);
3028 info->addMotionRange(mOrientedRanges.y);
3029 info->addMotionRange(mOrientedRanges.pressure);
3030
3031 if (mOrientedRanges.haveSize) {
3032 info->addMotionRange(mOrientedRanges.size);
3033 }
3034
3035 if (mOrientedRanges.haveTouchSize) {
3036 info->addMotionRange(mOrientedRanges.touchMajor);
3037 info->addMotionRange(mOrientedRanges.touchMinor);
3038 }
3039
3040 if (mOrientedRanges.haveToolSize) {
3041 info->addMotionRange(mOrientedRanges.toolMajor);
3042 info->addMotionRange(mOrientedRanges.toolMinor);
3043 }
3044
3045 if (mOrientedRanges.haveOrientation) {
3046 info->addMotionRange(mOrientedRanges.orientation);
3047 }
3048
3049 if (mOrientedRanges.haveDistance) {
3050 info->addMotionRange(mOrientedRanges.distance);
3051 }
3052
3053 if (mOrientedRanges.haveTilt) {
3054 info->addMotionRange(mOrientedRanges.tilt);
3055 }
3056
3057 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3058 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3059 0.0f);
3060 }
3061 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3062 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3063 0.0f);
3064 }
3065 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3066 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3067 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3068 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3069 x.fuzz, x.resolution);
3070 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3071 y.fuzz, y.resolution);
3072 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3073 x.fuzz, x.resolution);
3074 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3075 y.fuzz, y.resolution);
3076 }
3077 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3078 }
3079}
3080
3081void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003082 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 dumpParameters(dump);
3084 dumpVirtualKeys(dump);
3085 dumpRawPointerAxes(dump);
3086 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003087 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 dumpSurface(dump);
3089
3090 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3091 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3092 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3093 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3094 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3095 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3096 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3097 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3098 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3099 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3100 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3101 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3102 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3103 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3104 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3105 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3106 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3107
Michael Wright7b159c92015-05-14 14:48:03 +01003108 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003110 mLastRawState.rawPointerData.pointerCount);
3111 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3112 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3114 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3115 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3116 "toolType=%d, isHovering=%s\n", i,
3117 pointer.id, pointer.x, pointer.y, pointer.pressure,
3118 pointer.touchMajor, pointer.touchMinor,
3119 pointer.toolMajor, pointer.toolMinor,
3120 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3121 pointer.toolType, toString(pointer.isHovering));
3122 }
3123
Michael Wright7b159c92015-05-14 14:48:03 +01003124 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003126 mLastCookedState.cookedPointerData.pointerCount);
3127 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3128 const PointerProperties& pointerProperties =
3129 mLastCookedState.cookedPointerData.pointerProperties[i];
3130 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3132 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3133 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3134 "toolType=%d, isHovering=%s\n", i,
3135 pointerProperties.id,
3136 pointerCoords.getX(),
3137 pointerCoords.getY(),
3138 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3139 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3140 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3141 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3142 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3143 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3144 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3145 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3146 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003147 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149
Michael Wright842500e2015-03-13 17:32:02 -07003150 dump.append(INDENT3 "Stylus Fusion:\n");
3151 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3152 toString(mExternalStylusConnected));
3153 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3154 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003155 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003156 dump.append(INDENT3 "External Stylus State:\n");
3157 dumpStylusState(dump, mExternalStylusState);
3158
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 if (mDeviceMode == DEVICE_MODE_POINTER) {
3160 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3161 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3162 mPointerXMovementScale);
3163 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3164 mPointerYMovementScale);
3165 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3166 mPointerXZoomScale);
3167 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3168 mPointerYZoomScale);
3169 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3170 mPointerGestureMaxSwipeWidth);
3171 }
3172}
3173
Santos Cordonfa5cf462017-04-05 10:37:00 -07003174const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3175 switch (deviceMode) {
3176 case DEVICE_MODE_DISABLED:
3177 return "disabled";
3178 case DEVICE_MODE_DIRECT:
3179 return "direct";
3180 case DEVICE_MODE_UNSCALED:
3181 return "unscaled";
3182 case DEVICE_MODE_NAVIGATION:
3183 return "navigation";
3184 case DEVICE_MODE_POINTER:
3185 return "pointer";
3186 }
3187 return "unknown";
3188}
3189
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190void TouchInputMapper::configure(nsecs_t when,
3191 const InputReaderConfiguration* config, uint32_t changes) {
3192 InputMapper::configure(when, config, changes);
3193
3194 mConfig = *config;
3195
3196 if (!changes) { // first time only
3197 // Configure basic parameters.
3198 configureParameters();
3199
3200 // Configure common accumulators.
3201 mCursorScrollAccumulator.configure(getDevice());
3202 mTouchButtonAccumulator.configure(getDevice());
3203
3204 // Configure absolute axis information.
3205 configureRawPointerAxes();
3206
3207 // Prepare input device calibration.
3208 parseCalibration();
3209 resolveCalibration();
3210 }
3211
Michael Wright842500e2015-03-13 17:32:02 -07003212 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003213 // Update location calibration to reflect current settings
3214 updateAffineTransformation();
3215 }
3216
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3218 // Update pointer speed.
3219 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3220 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3221 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3222 }
3223
3224 bool resetNeeded = false;
3225 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3226 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003227 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3228 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 // Configure device sources, surface dimensions, orientation and
3230 // scaling factors.
3231 configureSurface(when, &resetNeeded);
3232 }
3233
3234 if (changes && resetNeeded) {
3235 // Send reset, unless this is the first time the device has been configured,
3236 // in which case the reader will call reset itself after all mappers are ready.
3237 getDevice()->notifyReset(when);
3238 }
3239}
3240
Michael Wright842500e2015-03-13 17:32:02 -07003241void TouchInputMapper::resolveExternalStylusPresence() {
3242 Vector<InputDeviceInfo> devices;
3243 mContext->getExternalStylusDevices(devices);
3244 mExternalStylusConnected = !devices.isEmpty();
3245
3246 if (!mExternalStylusConnected) {
3247 resetExternalStylus();
3248 }
3249}
3250
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251void TouchInputMapper::configureParameters() {
3252 // Use the pointer presentation mode for devices that do not support distinct
3253 // multitouch. The spot-based presentation relies on being able to accurately
3254 // locate two or more fingers on the touch pad.
3255 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003256 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
3258 String8 gestureModeString;
3259 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3260 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003261 if (gestureModeString == "single-touch") {
3262 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3263 } else if (gestureModeString == "multi-touch") {
3264 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 } else if (gestureModeString != "default") {
3266 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3267 }
3268 }
3269
3270 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3271 // The device is a touch screen.
3272 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3273 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3274 // The device is a pointing device like a track pad.
3275 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3276 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3277 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3278 // The device is a cursor device with a touch pad attached.
3279 // By default don't use the touch pad to move the pointer.
3280 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3281 } else {
3282 // The device is a touch pad of unknown purpose.
3283 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3284 }
3285
3286 mParameters.hasButtonUnderPad=
3287 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3288
3289 String8 deviceTypeString;
3290 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3291 deviceTypeString)) {
3292 if (deviceTypeString == "touchScreen") {
3293 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3294 } else if (deviceTypeString == "touchPad") {
3295 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3296 } else if (deviceTypeString == "touchNavigation") {
3297 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3298 } else if (deviceTypeString == "pointer") {
3299 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3300 } else if (deviceTypeString != "default") {
3301 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3302 }
3303 }
3304
3305 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3306 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3307 mParameters.orientationAware);
3308
3309 mParameters.hasAssociatedDisplay = false;
3310 mParameters.associatedDisplayIsExternal = false;
3311 if (mParameters.orientationAware
3312 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3313 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3314 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003315 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3316 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3317 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3318 mParameters.uniqueDisplayId);
3319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003321
3322 // Initial downs on external touch devices should wake the device.
3323 // Normally we don't do this for internal touch screens to prevent them from waking
3324 // up in your pocket but you can enable it using the input device configuration.
3325 mParameters.wake = getDevice()->isExternal();
3326 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3327 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328}
3329
3330void TouchInputMapper::dumpParameters(String8& dump) {
3331 dump.append(INDENT3 "Parameters:\n");
3332
3333 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003334 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3335 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003337 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3338 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 break;
3340 default:
3341 assert(false);
3342 }
3343
3344 switch (mParameters.deviceType) {
3345 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3346 dump.append(INDENT4 "DeviceType: touchScreen\n");
3347 break;
3348 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3349 dump.append(INDENT4 "DeviceType: touchPad\n");
3350 break;
3351 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3352 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3353 break;
3354 case Parameters::DEVICE_TYPE_POINTER:
3355 dump.append(INDENT4 "DeviceType: pointer\n");
3356 break;
3357 default:
3358 ALOG_ASSERT(false);
3359 }
3360
Santos Cordonfa5cf462017-04-05 10:37:00 -07003361 dump.appendFormat(
3362 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003364 toString(mParameters.associatedDisplayIsExternal),
3365 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3367 toString(mParameters.orientationAware));
3368}
3369
3370void TouchInputMapper::configureRawPointerAxes() {
3371 mRawPointerAxes.clear();
3372}
3373
3374void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3375 dump.append(INDENT3 "Raw Touch Axes:\n");
3376 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3377 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3378 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3379 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3380 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3381 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3382 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3383 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3384 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3385 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3386 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3387 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3388 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3389}
3390
Michael Wright842500e2015-03-13 17:32:02 -07003391bool TouchInputMapper::hasExternalStylus() const {
3392 return mExternalStylusConnected;
3393}
3394
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3396 int32_t oldDeviceMode = mDeviceMode;
3397
Michael Wright842500e2015-03-13 17:32:02 -07003398 resolveExternalStylusPresence();
3399
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 // Determine device mode.
3401 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3402 && mConfig.pointerGesturesEnabled) {
3403 mSource = AINPUT_SOURCE_MOUSE;
3404 mDeviceMode = DEVICE_MODE_POINTER;
3405 if (hasStylus()) {
3406 mSource |= AINPUT_SOURCE_STYLUS;
3407 }
3408 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3409 && mParameters.hasAssociatedDisplay) {
3410 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3411 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003412 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 mSource |= AINPUT_SOURCE_STYLUS;
3414 }
Michael Wright2f78b682015-06-12 15:25:08 +01003415 if (hasExternalStylus()) {
3416 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3419 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3420 mDeviceMode = DEVICE_MODE_NAVIGATION;
3421 } else {
3422 mSource = AINPUT_SOURCE_TOUCHPAD;
3423 mDeviceMode = DEVICE_MODE_UNSCALED;
3424 }
3425
3426 // Ensure we have valid X and Y axes.
3427 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3428 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3429 "The device will be inoperable.", getDeviceName().string());
3430 mDeviceMode = DEVICE_MODE_DISABLED;
3431 return;
3432 }
3433
3434 // Raw width and height in the natural orientation.
3435 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3436 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3437
3438 // Get associated display dimensions.
3439 DisplayViewport newViewport;
3440 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003441 const String8* uniqueDisplayId = NULL;
3442 ViewportType viewportTypeToUse;
3443
3444 if (mParameters.associatedDisplayIsExternal) {
3445 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3446 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3447 // If the IDC file specified a unique display Id, then it expects to be linked to a
3448 // virtual display with the same unique ID.
3449 uniqueDisplayId = &mParameters.uniqueDisplayId;
3450 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3451 } else {
3452 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3453 }
3454
3455 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3457 "display. The device will be inoperable until the display size "
3458 "becomes available.",
3459 getDeviceName().string());
3460 mDeviceMode = DEVICE_MODE_DISABLED;
3461 return;
3462 }
3463 } else {
3464 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3465 }
3466 bool viewportChanged = mViewport != newViewport;
3467 if (viewportChanged) {
3468 mViewport = newViewport;
3469
3470 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3471 // Convert rotated viewport to natural surface coordinates.
3472 int32_t naturalLogicalWidth, naturalLogicalHeight;
3473 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3474 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3475 int32_t naturalDeviceWidth, naturalDeviceHeight;
3476 switch (mViewport.orientation) {
3477 case DISPLAY_ORIENTATION_90:
3478 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3479 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3480 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3481 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3482 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3483 naturalPhysicalTop = mViewport.physicalLeft;
3484 naturalDeviceWidth = mViewport.deviceHeight;
3485 naturalDeviceHeight = mViewport.deviceWidth;
3486 break;
3487 case DISPLAY_ORIENTATION_180:
3488 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3489 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3490 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3491 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3492 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3493 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3494 naturalDeviceWidth = mViewport.deviceWidth;
3495 naturalDeviceHeight = mViewport.deviceHeight;
3496 break;
3497 case DISPLAY_ORIENTATION_270:
3498 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3499 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3500 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3501 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3502 naturalPhysicalLeft = mViewport.physicalTop;
3503 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3504 naturalDeviceWidth = mViewport.deviceHeight;
3505 naturalDeviceHeight = mViewport.deviceWidth;
3506 break;
3507 case DISPLAY_ORIENTATION_0:
3508 default:
3509 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3510 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3511 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3512 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3513 naturalPhysicalLeft = mViewport.physicalLeft;
3514 naturalPhysicalTop = mViewport.physicalTop;
3515 naturalDeviceWidth = mViewport.deviceWidth;
3516 naturalDeviceHeight = mViewport.deviceHeight;
3517 break;
3518 }
3519
3520 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3521 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3522 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3523 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3524
3525 mSurfaceOrientation = mParameters.orientationAware ?
3526 mViewport.orientation : DISPLAY_ORIENTATION_0;
3527 } else {
3528 mSurfaceWidth = rawWidth;
3529 mSurfaceHeight = rawHeight;
3530 mSurfaceLeft = 0;
3531 mSurfaceTop = 0;
3532 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3533 }
3534 }
3535
3536 // If moving between pointer modes, need to reset some state.
3537 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3538 if (deviceModeChanged) {
3539 mOrientedRanges.clear();
3540 }
3541
3542 // Create pointer controller if needed.
3543 if (mDeviceMode == DEVICE_MODE_POINTER ||
3544 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3545 if (mPointerController == NULL) {
3546 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3547 }
3548 } else {
3549 mPointerController.clear();
3550 }
3551
3552 if (viewportChanged || deviceModeChanged) {
3553 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3554 "display id %d",
3555 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3556 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3557
3558 // Configure X and Y factors.
3559 mXScale = float(mSurfaceWidth) / rawWidth;
3560 mYScale = float(mSurfaceHeight) / rawHeight;
3561 mXTranslate = -mSurfaceLeft;
3562 mYTranslate = -mSurfaceTop;
3563 mXPrecision = 1.0f / mXScale;
3564 mYPrecision = 1.0f / mYScale;
3565
3566 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3567 mOrientedRanges.x.source = mSource;
3568 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3569 mOrientedRanges.y.source = mSource;
3570
3571 configureVirtualKeys();
3572
3573 // Scale factor for terms that are not oriented in a particular axis.
3574 // If the pixels are square then xScale == yScale otherwise we fake it
3575 // by choosing an average.
3576 mGeometricScale = avg(mXScale, mYScale);
3577
3578 // Size of diagonal axis.
3579 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3580
3581 // Size factors.
3582 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3583 if (mRawPointerAxes.touchMajor.valid
3584 && mRawPointerAxes.touchMajor.maxValue != 0) {
3585 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3586 } else if (mRawPointerAxes.toolMajor.valid
3587 && mRawPointerAxes.toolMajor.maxValue != 0) {
3588 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3589 } else {
3590 mSizeScale = 0.0f;
3591 }
3592
3593 mOrientedRanges.haveTouchSize = true;
3594 mOrientedRanges.haveToolSize = true;
3595 mOrientedRanges.haveSize = true;
3596
3597 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3598 mOrientedRanges.touchMajor.source = mSource;
3599 mOrientedRanges.touchMajor.min = 0;
3600 mOrientedRanges.touchMajor.max = diagonalSize;
3601 mOrientedRanges.touchMajor.flat = 0;
3602 mOrientedRanges.touchMajor.fuzz = 0;
3603 mOrientedRanges.touchMajor.resolution = 0;
3604
3605 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3606 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3607
3608 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3609 mOrientedRanges.toolMajor.source = mSource;
3610 mOrientedRanges.toolMajor.min = 0;
3611 mOrientedRanges.toolMajor.max = diagonalSize;
3612 mOrientedRanges.toolMajor.flat = 0;
3613 mOrientedRanges.toolMajor.fuzz = 0;
3614 mOrientedRanges.toolMajor.resolution = 0;
3615
3616 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3617 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3618
3619 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3620 mOrientedRanges.size.source = mSource;
3621 mOrientedRanges.size.min = 0;
3622 mOrientedRanges.size.max = 1.0;
3623 mOrientedRanges.size.flat = 0;
3624 mOrientedRanges.size.fuzz = 0;
3625 mOrientedRanges.size.resolution = 0;
3626 } else {
3627 mSizeScale = 0.0f;
3628 }
3629
3630 // Pressure factors.
3631 mPressureScale = 0;
3632 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3633 || mCalibration.pressureCalibration
3634 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3635 if (mCalibration.havePressureScale) {
3636 mPressureScale = mCalibration.pressureScale;
3637 } else if (mRawPointerAxes.pressure.valid
3638 && mRawPointerAxes.pressure.maxValue != 0) {
3639 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3640 }
3641 }
3642
3643 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3644 mOrientedRanges.pressure.source = mSource;
3645 mOrientedRanges.pressure.min = 0;
3646 mOrientedRanges.pressure.max = 1.0;
3647 mOrientedRanges.pressure.flat = 0;
3648 mOrientedRanges.pressure.fuzz = 0;
3649 mOrientedRanges.pressure.resolution = 0;
3650
3651 // Tilt
3652 mTiltXCenter = 0;
3653 mTiltXScale = 0;
3654 mTiltYCenter = 0;
3655 mTiltYScale = 0;
3656 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3657 if (mHaveTilt) {
3658 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3659 mRawPointerAxes.tiltX.maxValue);
3660 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3661 mRawPointerAxes.tiltY.maxValue);
3662 mTiltXScale = M_PI / 180;
3663 mTiltYScale = M_PI / 180;
3664
3665 mOrientedRanges.haveTilt = true;
3666
3667 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3668 mOrientedRanges.tilt.source = mSource;
3669 mOrientedRanges.tilt.min = 0;
3670 mOrientedRanges.tilt.max = M_PI_2;
3671 mOrientedRanges.tilt.flat = 0;
3672 mOrientedRanges.tilt.fuzz = 0;
3673 mOrientedRanges.tilt.resolution = 0;
3674 }
3675
3676 // Orientation
3677 mOrientationScale = 0;
3678 if (mHaveTilt) {
3679 mOrientedRanges.haveOrientation = true;
3680
3681 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3682 mOrientedRanges.orientation.source = mSource;
3683 mOrientedRanges.orientation.min = -M_PI;
3684 mOrientedRanges.orientation.max = M_PI;
3685 mOrientedRanges.orientation.flat = 0;
3686 mOrientedRanges.orientation.fuzz = 0;
3687 mOrientedRanges.orientation.resolution = 0;
3688 } else if (mCalibration.orientationCalibration !=
3689 Calibration::ORIENTATION_CALIBRATION_NONE) {
3690 if (mCalibration.orientationCalibration
3691 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3692 if (mRawPointerAxes.orientation.valid) {
3693 if (mRawPointerAxes.orientation.maxValue > 0) {
3694 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3695 } else if (mRawPointerAxes.orientation.minValue < 0) {
3696 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3697 } else {
3698 mOrientationScale = 0;
3699 }
3700 }
3701 }
3702
3703 mOrientedRanges.haveOrientation = true;
3704
3705 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3706 mOrientedRanges.orientation.source = mSource;
3707 mOrientedRanges.orientation.min = -M_PI_2;
3708 mOrientedRanges.orientation.max = M_PI_2;
3709 mOrientedRanges.orientation.flat = 0;
3710 mOrientedRanges.orientation.fuzz = 0;
3711 mOrientedRanges.orientation.resolution = 0;
3712 }
3713
3714 // Distance
3715 mDistanceScale = 0;
3716 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3717 if (mCalibration.distanceCalibration
3718 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3719 if (mCalibration.haveDistanceScale) {
3720 mDistanceScale = mCalibration.distanceScale;
3721 } else {
3722 mDistanceScale = 1.0f;
3723 }
3724 }
3725
3726 mOrientedRanges.haveDistance = true;
3727
3728 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3729 mOrientedRanges.distance.source = mSource;
3730 mOrientedRanges.distance.min =
3731 mRawPointerAxes.distance.minValue * mDistanceScale;
3732 mOrientedRanges.distance.max =
3733 mRawPointerAxes.distance.maxValue * mDistanceScale;
3734 mOrientedRanges.distance.flat = 0;
3735 mOrientedRanges.distance.fuzz =
3736 mRawPointerAxes.distance.fuzz * mDistanceScale;
3737 mOrientedRanges.distance.resolution = 0;
3738 }
3739
3740 // Compute oriented precision, scales and ranges.
3741 // Note that the maximum value reported is an inclusive maximum value so it is one
3742 // unit less than the total width or height of surface.
3743 switch (mSurfaceOrientation) {
3744 case DISPLAY_ORIENTATION_90:
3745 case DISPLAY_ORIENTATION_270:
3746 mOrientedXPrecision = mYPrecision;
3747 mOrientedYPrecision = mXPrecision;
3748
3749 mOrientedRanges.x.min = mYTranslate;
3750 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3751 mOrientedRanges.x.flat = 0;
3752 mOrientedRanges.x.fuzz = 0;
3753 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3754
3755 mOrientedRanges.y.min = mXTranslate;
3756 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3757 mOrientedRanges.y.flat = 0;
3758 mOrientedRanges.y.fuzz = 0;
3759 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3760 break;
3761
3762 default:
3763 mOrientedXPrecision = mXPrecision;
3764 mOrientedYPrecision = mYPrecision;
3765
3766 mOrientedRanges.x.min = mXTranslate;
3767 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3768 mOrientedRanges.x.flat = 0;
3769 mOrientedRanges.x.fuzz = 0;
3770 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3771
3772 mOrientedRanges.y.min = mYTranslate;
3773 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3774 mOrientedRanges.y.flat = 0;
3775 mOrientedRanges.y.fuzz = 0;
3776 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3777 break;
3778 }
3779
Jason Gerecke71b16e82014-03-10 09:47:59 -07003780 // Location
3781 updateAffineTransformation();
3782
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 if (mDeviceMode == DEVICE_MODE_POINTER) {
3784 // Compute pointer gesture detection parameters.
3785 float rawDiagonal = hypotf(rawWidth, rawHeight);
3786 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3787
3788 // Scale movements such that one whole swipe of the touch pad covers a
3789 // given area relative to the diagonal size of the display when no acceleration
3790 // is applied.
3791 // Assume that the touch pad has a square aspect ratio such that movements in
3792 // X and Y of the same number of raw units cover the same physical distance.
3793 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3794 * displayDiagonal / rawDiagonal;
3795 mPointerYMovementScale = mPointerXMovementScale;
3796
3797 // Scale zooms to cover a smaller range of the display than movements do.
3798 // This value determines the area around the pointer that is affected by freeform
3799 // pointer gestures.
3800 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3801 * displayDiagonal / rawDiagonal;
3802 mPointerYZoomScale = mPointerXZoomScale;
3803
3804 // Max width between pointers to detect a swipe gesture is more than some fraction
3805 // of the diagonal axis of the touch pad. Touches that are wider than this are
3806 // translated into freeform gestures.
3807 mPointerGestureMaxSwipeWidth =
3808 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3809
3810 // Abort current pointer usages because the state has changed.
3811 abortPointerUsage(when, 0 /*policyFlags*/);
3812 }
3813
3814 // Inform the dispatcher about the changes.
3815 *outResetNeeded = true;
3816 bumpGeneration();
3817 }
3818}
3819
3820void TouchInputMapper::dumpSurface(String8& dump) {
3821 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3822 "logicalFrame=[%d, %d, %d, %d], "
3823 "physicalFrame=[%d, %d, %d, %d], "
3824 "deviceSize=[%d, %d]\n",
3825 mViewport.displayId, mViewport.orientation,
3826 mViewport.logicalLeft, mViewport.logicalTop,
3827 mViewport.logicalRight, mViewport.logicalBottom,
3828 mViewport.physicalLeft, mViewport.physicalTop,
3829 mViewport.physicalRight, mViewport.physicalBottom,
3830 mViewport.deviceWidth, mViewport.deviceHeight);
3831
3832 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3833 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3834 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3835 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3836 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3837}
3838
3839void TouchInputMapper::configureVirtualKeys() {
3840 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3841 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3842
3843 mVirtualKeys.clear();
3844
3845 if (virtualKeyDefinitions.size() == 0) {
3846 return;
3847 }
3848
3849 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3850
3851 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3852 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3853 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3854 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3855
3856 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3857 const VirtualKeyDefinition& virtualKeyDefinition =
3858 virtualKeyDefinitions[i];
3859
3860 mVirtualKeys.add();
3861 VirtualKey& virtualKey = mVirtualKeys.editTop();
3862
3863 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3864 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003865 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003867 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3868 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3870 virtualKey.scanCode);
3871 mVirtualKeys.pop(); // drop the key
3872 continue;
3873 }
3874
3875 virtualKey.keyCode = keyCode;
3876 virtualKey.flags = flags;
3877
3878 // convert the key definition's display coordinates into touch coordinates for a hit box
3879 int32_t halfWidth = virtualKeyDefinition.width / 2;
3880 int32_t halfHeight = virtualKeyDefinition.height / 2;
3881
3882 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3883 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3884 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3885 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3886 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3887 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3888 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3889 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3890 }
3891}
3892
3893void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3894 if (!mVirtualKeys.isEmpty()) {
3895 dump.append(INDENT3 "Virtual Keys:\n");
3896
3897 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3898 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003899 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3901 i, virtualKey.scanCode, virtualKey.keyCode,
3902 virtualKey.hitLeft, virtualKey.hitRight,
3903 virtualKey.hitTop, virtualKey.hitBottom);
3904 }
3905 }
3906}
3907
3908void TouchInputMapper::parseCalibration() {
3909 const PropertyMap& in = getDevice()->getConfiguration();
3910 Calibration& out = mCalibration;
3911
3912 // Size
3913 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3914 String8 sizeCalibrationString;
3915 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3916 if (sizeCalibrationString == "none") {
3917 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3918 } else if (sizeCalibrationString == "geometric") {
3919 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3920 } else if (sizeCalibrationString == "diameter") {
3921 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3922 } else if (sizeCalibrationString == "box") {
3923 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3924 } else if (sizeCalibrationString == "area") {
3925 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3926 } else if (sizeCalibrationString != "default") {
3927 ALOGW("Invalid value for touch.size.calibration: '%s'",
3928 sizeCalibrationString.string());
3929 }
3930 }
3931
3932 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3933 out.sizeScale);
3934 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3935 out.sizeBias);
3936 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3937 out.sizeIsSummed);
3938
3939 // Pressure
3940 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3941 String8 pressureCalibrationString;
3942 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3943 if (pressureCalibrationString == "none") {
3944 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3945 } else if (pressureCalibrationString == "physical") {
3946 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3947 } else if (pressureCalibrationString == "amplitude") {
3948 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3949 } else if (pressureCalibrationString != "default") {
3950 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3951 pressureCalibrationString.string());
3952 }
3953 }
3954
3955 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3956 out.pressureScale);
3957
3958 // Orientation
3959 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3960 String8 orientationCalibrationString;
3961 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3962 if (orientationCalibrationString == "none") {
3963 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3964 } else if (orientationCalibrationString == "interpolated") {
3965 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3966 } else if (orientationCalibrationString == "vector") {
3967 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3968 } else if (orientationCalibrationString != "default") {
3969 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3970 orientationCalibrationString.string());
3971 }
3972 }
3973
3974 // Distance
3975 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3976 String8 distanceCalibrationString;
3977 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3978 if (distanceCalibrationString == "none") {
3979 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3980 } else if (distanceCalibrationString == "scaled") {
3981 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3982 } else if (distanceCalibrationString != "default") {
3983 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3984 distanceCalibrationString.string());
3985 }
3986 }
3987
3988 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3989 out.distanceScale);
3990
3991 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3992 String8 coverageCalibrationString;
3993 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3994 if (coverageCalibrationString == "none") {
3995 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3996 } else if (coverageCalibrationString == "box") {
3997 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3998 } else if (coverageCalibrationString != "default") {
3999 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4000 coverageCalibrationString.string());
4001 }
4002 }
4003}
4004
4005void TouchInputMapper::resolveCalibration() {
4006 // Size
4007 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4008 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4009 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4010 }
4011 } else {
4012 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4013 }
4014
4015 // Pressure
4016 if (mRawPointerAxes.pressure.valid) {
4017 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4018 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4019 }
4020 } else {
4021 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4022 }
4023
4024 // Orientation
4025 if (mRawPointerAxes.orientation.valid) {
4026 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4027 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4028 }
4029 } else {
4030 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4031 }
4032
4033 // Distance
4034 if (mRawPointerAxes.distance.valid) {
4035 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4036 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4037 }
4038 } else {
4039 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4040 }
4041
4042 // Coverage
4043 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4044 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4045 }
4046}
4047
4048void TouchInputMapper::dumpCalibration(String8& dump) {
4049 dump.append(INDENT3 "Calibration:\n");
4050
4051 // Size
4052 switch (mCalibration.sizeCalibration) {
4053 case Calibration::SIZE_CALIBRATION_NONE:
4054 dump.append(INDENT4 "touch.size.calibration: none\n");
4055 break;
4056 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4057 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4058 break;
4059 case Calibration::SIZE_CALIBRATION_DIAMETER:
4060 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4061 break;
4062 case Calibration::SIZE_CALIBRATION_BOX:
4063 dump.append(INDENT4 "touch.size.calibration: box\n");
4064 break;
4065 case Calibration::SIZE_CALIBRATION_AREA:
4066 dump.append(INDENT4 "touch.size.calibration: area\n");
4067 break;
4068 default:
4069 ALOG_ASSERT(false);
4070 }
4071
4072 if (mCalibration.haveSizeScale) {
4073 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4074 mCalibration.sizeScale);
4075 }
4076
4077 if (mCalibration.haveSizeBias) {
4078 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4079 mCalibration.sizeBias);
4080 }
4081
4082 if (mCalibration.haveSizeIsSummed) {
4083 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4084 toString(mCalibration.sizeIsSummed));
4085 }
4086
4087 // Pressure
4088 switch (mCalibration.pressureCalibration) {
4089 case Calibration::PRESSURE_CALIBRATION_NONE:
4090 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4091 break;
4092 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4093 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4094 break;
4095 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4096 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4097 break;
4098 default:
4099 ALOG_ASSERT(false);
4100 }
4101
4102 if (mCalibration.havePressureScale) {
4103 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4104 mCalibration.pressureScale);
4105 }
4106
4107 // Orientation
4108 switch (mCalibration.orientationCalibration) {
4109 case Calibration::ORIENTATION_CALIBRATION_NONE:
4110 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4111 break;
4112 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4113 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4114 break;
4115 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4116 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4117 break;
4118 default:
4119 ALOG_ASSERT(false);
4120 }
4121
4122 // Distance
4123 switch (mCalibration.distanceCalibration) {
4124 case Calibration::DISTANCE_CALIBRATION_NONE:
4125 dump.append(INDENT4 "touch.distance.calibration: none\n");
4126 break;
4127 case Calibration::DISTANCE_CALIBRATION_SCALED:
4128 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4129 break;
4130 default:
4131 ALOG_ASSERT(false);
4132 }
4133
4134 if (mCalibration.haveDistanceScale) {
4135 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4136 mCalibration.distanceScale);
4137 }
4138
4139 switch (mCalibration.coverageCalibration) {
4140 case Calibration::COVERAGE_CALIBRATION_NONE:
4141 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4142 break;
4143 case Calibration::COVERAGE_CALIBRATION_BOX:
4144 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4145 break;
4146 default:
4147 ALOG_ASSERT(false);
4148 }
4149}
4150
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004151void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4152 dump.append(INDENT3 "Affine Transformation:\n");
4153
4154 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4155 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4156 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4157 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4158 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4159 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4160}
4161
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004162void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004163 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4164 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004165}
4166
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167void TouchInputMapper::reset(nsecs_t when) {
4168 mCursorButtonAccumulator.reset(getDevice());
4169 mCursorScrollAccumulator.reset(getDevice());
4170 mTouchButtonAccumulator.reset(getDevice());
4171
4172 mPointerVelocityControl.reset();
4173 mWheelXVelocityControl.reset();
4174 mWheelYVelocityControl.reset();
4175
Michael Wright842500e2015-03-13 17:32:02 -07004176 mRawStatesPending.clear();
4177 mCurrentRawState.clear();
4178 mCurrentCookedState.clear();
4179 mLastRawState.clear();
4180 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 mPointerUsage = POINTER_USAGE_NONE;
4182 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004183 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004184 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 mDownTime = 0;
4186
4187 mCurrentVirtualKey.down = false;
4188
4189 mPointerGesture.reset();
4190 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004191 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192
4193 if (mPointerController != NULL) {
4194 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4195 mPointerController->clearSpots();
4196 }
4197
4198 InputMapper::reset(when);
4199}
4200
Michael Wright842500e2015-03-13 17:32:02 -07004201void TouchInputMapper::resetExternalStylus() {
4202 mExternalStylusState.clear();
4203 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004204 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004205 mExternalStylusDataPending = false;
4206}
4207
Michael Wright43fd19f2015-04-21 19:02:58 +01004208void TouchInputMapper::clearStylusDataPendingFlags() {
4209 mExternalStylusDataPending = false;
4210 mExternalStylusFusionTimeout = LLONG_MAX;
4211}
4212
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213void TouchInputMapper::process(const RawEvent* rawEvent) {
4214 mCursorButtonAccumulator.process(rawEvent);
4215 mCursorScrollAccumulator.process(rawEvent);
4216 mTouchButtonAccumulator.process(rawEvent);
4217
4218 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4219 sync(rawEvent->when);
4220 }
4221}
4222
4223void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004224 const RawState* last = mRawStatesPending.isEmpty() ?
4225 &mCurrentRawState : &mRawStatesPending.top();
4226
4227 // Push a new state.
4228 mRawStatesPending.push();
4229 RawState* next = &mRawStatesPending.editTop();
4230 next->clear();
4231 next->when = when;
4232
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004234 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 | mCursorButtonAccumulator.getButtonState();
4236
Michael Wright842500e2015-03-13 17:32:02 -07004237 // Sync scroll
4238 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4239 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 mCursorScrollAccumulator.finishSync();
4241
Michael Wright842500e2015-03-13 17:32:02 -07004242 // Sync touch
4243 syncTouch(when, next);
4244
4245 // Assign pointer ids.
4246 if (!mHavePointerIds) {
4247 assignPointerIds(last, next);
4248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249
4250#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004251 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4252 "hovering ids 0x%08x -> 0x%08x",
4253 last->rawPointerData.pointerCount,
4254 next->rawPointerData.pointerCount,
4255 last->rawPointerData.touchingIdBits.value,
4256 next->rawPointerData.touchingIdBits.value,
4257 last->rawPointerData.hoveringIdBits.value,
4258 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259#endif
4260
Michael Wright842500e2015-03-13 17:32:02 -07004261 processRawTouches(false /*timeout*/);
4262}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263
Michael Wright842500e2015-03-13 17:32:02 -07004264void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4266 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004267 mCurrentRawState.clear();
4268 mRawStatesPending.clear();
4269 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 }
4271
Michael Wright842500e2015-03-13 17:32:02 -07004272 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4273 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4274 // touching the current state will only observe the events that have been dispatched to the
4275 // rest of the pipeline.
4276 const size_t N = mRawStatesPending.size();
4277 size_t count;
4278 for(count = 0; count < N; count++) {
4279 const RawState& next = mRawStatesPending[count];
4280
4281 // A failure to assign the stylus id means that we're waiting on stylus data
4282 // and so should defer the rest of the pipeline.
4283 if (assignExternalStylusId(next, timeout)) {
4284 break;
4285 }
4286
4287 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004288 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004289 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004290 if (mCurrentRawState.when < mLastRawState.when) {
4291 mCurrentRawState.when = mLastRawState.when;
4292 }
Michael Wright842500e2015-03-13 17:32:02 -07004293 cookAndDispatch(mCurrentRawState.when);
4294 }
4295 if (count != 0) {
4296 mRawStatesPending.removeItemsAt(0, count);
4297 }
4298
Michael Wright842500e2015-03-13 17:32:02 -07004299 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004300 if (timeout) {
4301 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4302 clearStylusDataPendingFlags();
4303 mCurrentRawState.copyFrom(mLastRawState);
4304#if DEBUG_STYLUS_FUSION
4305 ALOGD("Timeout expired, synthesizing event with new stylus data");
4306#endif
4307 cookAndDispatch(when);
4308 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4309 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4310 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4311 }
Michael Wright842500e2015-03-13 17:32:02 -07004312 }
4313}
4314
4315void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4316 // Always start with a clean state.
4317 mCurrentCookedState.clear();
4318
4319 // Apply stylus buttons to current raw state.
4320 applyExternalStylusButtonState(when);
4321
4322 // Handle policy on initial down or hover events.
4323 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4324 && mCurrentRawState.rawPointerData.pointerCount != 0;
4325
4326 uint32_t policyFlags = 0;
4327 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4328 if (initialDown || buttonsPressed) {
4329 // If this is a touch screen, hide the pointer on an initial down.
4330 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4331 getContext()->fadePointer();
4332 }
4333
4334 if (mParameters.wake) {
4335 policyFlags |= POLICY_FLAG_WAKE;
4336 }
4337 }
4338
4339 // Consume raw off-screen touches before cooking pointer data.
4340 // If touches are consumed, subsequent code will not receive any pointer data.
4341 if (consumeRawTouches(when, policyFlags)) {
4342 mCurrentRawState.rawPointerData.clear();
4343 }
4344
4345 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4346 // with cooked pointer data that has the same ids and indices as the raw data.
4347 // The following code can use either the raw or cooked data, as needed.
4348 cookPointerData();
4349
4350 // Apply stylus pressure to current cooked state.
4351 applyExternalStylusTouchState(when);
4352
4353 // Synthesize key down from raw buttons if needed.
4354 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004355 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004356
4357 // Dispatch the touches either directly or by translation through a pointer on screen.
4358 if (mDeviceMode == DEVICE_MODE_POINTER) {
4359 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4360 !idBits.isEmpty(); ) {
4361 uint32_t id = idBits.clearFirstMarkedBit();
4362 const RawPointerData::Pointer& pointer =
4363 mCurrentRawState.rawPointerData.pointerForId(id);
4364 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4365 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4366 mCurrentCookedState.stylusIdBits.markBit(id);
4367 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4368 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4369 mCurrentCookedState.fingerIdBits.markBit(id);
4370 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4371 mCurrentCookedState.mouseIdBits.markBit(id);
4372 }
4373 }
4374 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4375 !idBits.isEmpty(); ) {
4376 uint32_t id = idBits.clearFirstMarkedBit();
4377 const RawPointerData::Pointer& pointer =
4378 mCurrentRawState.rawPointerData.pointerForId(id);
4379 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4380 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4381 mCurrentCookedState.stylusIdBits.markBit(id);
4382 }
4383 }
4384
4385 // Stylus takes precedence over all tools, then mouse, then finger.
4386 PointerUsage pointerUsage = mPointerUsage;
4387 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4388 mCurrentCookedState.mouseIdBits.clear();
4389 mCurrentCookedState.fingerIdBits.clear();
4390 pointerUsage = POINTER_USAGE_STYLUS;
4391 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4392 mCurrentCookedState.fingerIdBits.clear();
4393 pointerUsage = POINTER_USAGE_MOUSE;
4394 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4395 isPointerDown(mCurrentRawState.buttonState)) {
4396 pointerUsage = POINTER_USAGE_GESTURES;
4397 }
4398
4399 dispatchPointerUsage(when, policyFlags, pointerUsage);
4400 } else {
4401 if (mDeviceMode == DEVICE_MODE_DIRECT
4402 && mConfig.showTouches && mPointerController != NULL) {
4403 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4404 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4405
4406 mPointerController->setButtonState(mCurrentRawState.buttonState);
4407 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4408 mCurrentCookedState.cookedPointerData.idToIndex,
4409 mCurrentCookedState.cookedPointerData.touchingIdBits);
4410 }
4411
Michael Wright8e812822015-06-22 16:18:21 +01004412 if (!mCurrentMotionAborted) {
4413 dispatchButtonRelease(when, policyFlags);
4414 dispatchHoverExit(when, policyFlags);
4415 dispatchTouches(when, policyFlags);
4416 dispatchHoverEnterAndMove(when, policyFlags);
4417 dispatchButtonPress(when, policyFlags);
4418 }
4419
4420 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4421 mCurrentMotionAborted = false;
4422 }
Michael Wright842500e2015-03-13 17:32:02 -07004423 }
4424
4425 // Synthesize key up from raw buttons if needed.
4426 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004427 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
4429 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004430 mCurrentRawState.rawVScroll = 0;
4431 mCurrentRawState.rawHScroll = 0;
4432
4433 // Copy current touch to last touch in preparation for the next cycle.
4434 mLastRawState.copyFrom(mCurrentRawState);
4435 mLastCookedState.copyFrom(mCurrentCookedState);
4436}
4437
4438void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004439 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004440 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4441 }
4442}
4443
4444void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004445 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4446 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004447
Michael Wright53dca3a2015-04-23 17:39:53 +01004448 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4449 float pressure = mExternalStylusState.pressure;
4450 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4451 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4452 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4453 }
4454 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4455 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4456
4457 PointerProperties& properties =
4458 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004459 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4460 properties.toolType = mExternalStylusState.toolType;
4461 }
4462 }
4463}
4464
4465bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4466 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4467 return false;
4468 }
4469
4470 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4471 && state.rawPointerData.pointerCount != 0;
4472 if (initialDown) {
4473 if (mExternalStylusState.pressure != 0.0f) {
4474#if DEBUG_STYLUS_FUSION
4475 ALOGD("Have both stylus and touch data, beginning fusion");
4476#endif
4477 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4478 } else if (timeout) {
4479#if DEBUG_STYLUS_FUSION
4480 ALOGD("Timeout expired, assuming touch is not a stylus.");
4481#endif
4482 resetExternalStylus();
4483 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004484 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4485 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004486 }
4487#if DEBUG_STYLUS_FUSION
4488 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004489 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004490#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004491 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004492 return true;
4493 }
4494 }
4495
4496 // Check if the stylus pointer has gone up.
4497 if (mExternalStylusId != -1 &&
4498 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4499#if DEBUG_STYLUS_FUSION
4500 ALOGD("Stylus pointer is going up");
4501#endif
4502 mExternalStylusId = -1;
4503 }
4504
4505 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506}
4507
4508void TouchInputMapper::timeoutExpired(nsecs_t when) {
4509 if (mDeviceMode == DEVICE_MODE_POINTER) {
4510 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4511 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4512 }
Michael Wright842500e2015-03-13 17:32:02 -07004513 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004514 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004515 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004516 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4517 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004518 }
4519 }
4520}
4521
4522void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004523 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004524 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004525 // We're either in the middle of a fused stream of data or we're waiting on data before
4526 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4527 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004528 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004529 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 }
4531}
4532
4533bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4534 // Check for release of a virtual key.
4535 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004536 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 // Pointer went up while virtual key was down.
4538 mCurrentVirtualKey.down = false;
4539 if (!mCurrentVirtualKey.ignored) {
4540#if DEBUG_VIRTUAL_KEYS
4541 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4542 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4543#endif
4544 dispatchVirtualKey(when, policyFlags,
4545 AKEY_EVENT_ACTION_UP,
4546 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4547 }
4548 return true;
4549 }
4550
Michael Wright842500e2015-03-13 17:32:02 -07004551 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4552 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4553 const RawPointerData::Pointer& pointer =
4554 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4556 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4557 // Pointer is still within the space of the virtual key.
4558 return true;
4559 }
4560 }
4561
4562 // Pointer left virtual key area or another pointer also went down.
4563 // Send key cancellation but do not consume the touch yet.
4564 // This is useful when the user swipes through from the virtual key area
4565 // into the main display surface.
4566 mCurrentVirtualKey.down = false;
4567 if (!mCurrentVirtualKey.ignored) {
4568#if DEBUG_VIRTUAL_KEYS
4569 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4570 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4571#endif
4572 dispatchVirtualKey(when, policyFlags,
4573 AKEY_EVENT_ACTION_UP,
4574 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4575 | AKEY_EVENT_FLAG_CANCELED);
4576 }
4577 }
4578
Michael Wright842500e2015-03-13 17:32:02 -07004579 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4580 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004582 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4583 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4585 // If exactly one pointer went down, check for virtual key hit.
4586 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004587 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4589 if (virtualKey) {
4590 mCurrentVirtualKey.down = true;
4591 mCurrentVirtualKey.downTime = when;
4592 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4593 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4594 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4595 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4596
4597 if (!mCurrentVirtualKey.ignored) {
4598#if DEBUG_VIRTUAL_KEYS
4599 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4600 mCurrentVirtualKey.keyCode,
4601 mCurrentVirtualKey.scanCode);
4602#endif
4603 dispatchVirtualKey(when, policyFlags,
4604 AKEY_EVENT_ACTION_DOWN,
4605 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4606 }
4607 }
4608 }
4609 return true;
4610 }
4611 }
4612
4613 // Disable all virtual key touches that happen within a short time interval of the
4614 // most recent touch within the screen area. The idea is to filter out stray
4615 // virtual key presses when interacting with the touch screen.
4616 //
4617 // Problems we're trying to solve:
4618 //
4619 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4620 // virtual key area that is implemented by a separate touch panel and accidentally
4621 // triggers a virtual key.
4622 //
4623 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4624 // area and accidentally triggers a virtual key. This often happens when virtual keys
4625 // are layed out below the screen near to where the on screen keyboard's space bar
4626 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004627 if (mConfig.virtualKeyQuietTime > 0 &&
4628 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4630 }
4631 return false;
4632}
4633
4634void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4635 int32_t keyEventAction, int32_t keyEventFlags) {
4636 int32_t keyCode = mCurrentVirtualKey.keyCode;
4637 int32_t scanCode = mCurrentVirtualKey.scanCode;
4638 nsecs_t downTime = mCurrentVirtualKey.downTime;
4639 int32_t metaState = mContext->getGlobalMetaState();
4640 policyFlags |= POLICY_FLAG_VIRTUAL;
4641
4642 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4643 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4644 getListener()->notifyKey(&args);
4645}
4646
Michael Wright8e812822015-06-22 16:18:21 +01004647void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4648 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4649 if (!currentIdBits.isEmpty()) {
4650 int32_t metaState = getContext()->getGlobalMetaState();
4651 int32_t buttonState = mCurrentCookedState.buttonState;
4652 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4653 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4654 mCurrentCookedState.cookedPointerData.pointerProperties,
4655 mCurrentCookedState.cookedPointerData.pointerCoords,
4656 mCurrentCookedState.cookedPointerData.idToIndex,
4657 currentIdBits, -1,
4658 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4659 mCurrentMotionAborted = true;
4660 }
4661}
4662
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004664 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4665 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004667 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668
4669 if (currentIdBits == lastIdBits) {
4670 if (!currentIdBits.isEmpty()) {
4671 // No pointer id changes so this is a move event.
4672 // The listener takes care of batching moves so we don't have to deal with that here.
4673 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004674 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004676 mCurrentCookedState.cookedPointerData.pointerProperties,
4677 mCurrentCookedState.cookedPointerData.pointerCoords,
4678 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 currentIdBits, -1,
4680 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4681 }
4682 } else {
4683 // There may be pointers going up and pointers going down and pointers moving
4684 // all at the same time.
4685 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4686 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4687 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4688 BitSet32 dispatchedIdBits(lastIdBits.value);
4689
4690 // Update last coordinates of pointers that have moved so that we observe the new
4691 // pointer positions at the same time as other pointers that have just gone up.
4692 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004693 mCurrentCookedState.cookedPointerData.pointerProperties,
4694 mCurrentCookedState.cookedPointerData.pointerCoords,
4695 mCurrentCookedState.cookedPointerData.idToIndex,
4696 mLastCookedState.cookedPointerData.pointerProperties,
4697 mLastCookedState.cookedPointerData.pointerCoords,
4698 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004700 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 moveNeeded = true;
4702 }
4703
4704 // Dispatch pointer up events.
4705 while (!upIdBits.isEmpty()) {
4706 uint32_t upId = upIdBits.clearFirstMarkedBit();
4707
4708 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004709 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004710 mLastCookedState.cookedPointerData.pointerProperties,
4711 mLastCookedState.cookedPointerData.pointerCoords,
4712 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004713 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 dispatchedIdBits.clearBit(upId);
4715 }
4716
4717 // Dispatch move events if any of the remaining pointers moved from their old locations.
4718 // Although applications receive new locations as part of individual pointer up
4719 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004720 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4722 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004723 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004724 mCurrentCookedState.cookedPointerData.pointerProperties,
4725 mCurrentCookedState.cookedPointerData.pointerCoords,
4726 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004727 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729
4730 // Dispatch pointer down events using the new pointer locations.
4731 while (!downIdBits.isEmpty()) {
4732 uint32_t downId = downIdBits.clearFirstMarkedBit();
4733 dispatchedIdBits.markBit(downId);
4734
4735 if (dispatchedIdBits.count() == 1) {
4736 // First pointer is going down. Set down time.
4737 mDownTime = when;
4738 }
4739
4740 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004741 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004742 mCurrentCookedState.cookedPointerData.pointerProperties,
4743 mCurrentCookedState.cookedPointerData.pointerCoords,
4744 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004745 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 }
4747 }
4748}
4749
4750void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4751 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004752 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4753 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 int32_t metaState = getContext()->getGlobalMetaState();
4755 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004756 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004757 mLastCookedState.cookedPointerData.pointerProperties,
4758 mLastCookedState.cookedPointerData.pointerCoords,
4759 mLastCookedState.cookedPointerData.idToIndex,
4760 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4762 mSentHoverEnter = false;
4763 }
4764}
4765
4766void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004767 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4768 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 int32_t metaState = getContext()->getGlobalMetaState();
4770 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004771 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004772 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004773 mCurrentCookedState.cookedPointerData.pointerProperties,
4774 mCurrentCookedState.cookedPointerData.pointerCoords,
4775 mCurrentCookedState.cookedPointerData.idToIndex,
4776 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4778 mSentHoverEnter = true;
4779 }
4780
4781 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004782 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004783 mCurrentRawState.buttonState, 0,
4784 mCurrentCookedState.cookedPointerData.pointerProperties,
4785 mCurrentCookedState.cookedPointerData.pointerCoords,
4786 mCurrentCookedState.cookedPointerData.idToIndex,
4787 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4789 }
4790}
4791
Michael Wright7b159c92015-05-14 14:48:03 +01004792void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4793 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4794 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4795 const int32_t metaState = getContext()->getGlobalMetaState();
4796 int32_t buttonState = mLastCookedState.buttonState;
4797 while (!releasedButtons.isEmpty()) {
4798 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4799 buttonState &= ~actionButton;
4800 dispatchMotion(when, policyFlags, mSource,
4801 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4802 0, metaState, buttonState, 0,
4803 mCurrentCookedState.cookedPointerData.pointerProperties,
4804 mCurrentCookedState.cookedPointerData.pointerCoords,
4805 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4806 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4807 }
4808}
4809
4810void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4811 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4812 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4813 const int32_t metaState = getContext()->getGlobalMetaState();
4814 int32_t buttonState = mLastCookedState.buttonState;
4815 while (!pressedButtons.isEmpty()) {
4816 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4817 buttonState |= actionButton;
4818 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4819 0, metaState, buttonState, 0,
4820 mCurrentCookedState.cookedPointerData.pointerProperties,
4821 mCurrentCookedState.cookedPointerData.pointerCoords,
4822 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4823 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4824 }
4825}
4826
4827const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4828 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4829 return cookedPointerData.touchingIdBits;
4830 }
4831 return cookedPointerData.hoveringIdBits;
4832}
4833
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004835 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836
Michael Wright842500e2015-03-13 17:32:02 -07004837 mCurrentCookedState.cookedPointerData.clear();
4838 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4839 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4840 mCurrentRawState.rawPointerData.hoveringIdBits;
4841 mCurrentCookedState.cookedPointerData.touchingIdBits =
4842 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843
Michael Wright7b159c92015-05-14 14:48:03 +01004844 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4845 mCurrentCookedState.buttonState = 0;
4846 } else {
4847 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4848 }
4849
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 // Walk through the the active pointers and map device coordinates onto
4851 // surface coordinates and adjust for display orientation.
4852 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004853 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854
4855 // Size
4856 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4857 switch (mCalibration.sizeCalibration) {
4858 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4859 case Calibration::SIZE_CALIBRATION_DIAMETER:
4860 case Calibration::SIZE_CALIBRATION_BOX:
4861 case Calibration::SIZE_CALIBRATION_AREA:
4862 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4863 touchMajor = in.touchMajor;
4864 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4865 toolMajor = in.toolMajor;
4866 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4867 size = mRawPointerAxes.touchMinor.valid
4868 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4869 } else if (mRawPointerAxes.touchMajor.valid) {
4870 toolMajor = touchMajor = in.touchMajor;
4871 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4872 ? in.touchMinor : in.touchMajor;
4873 size = mRawPointerAxes.touchMinor.valid
4874 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4875 } else if (mRawPointerAxes.toolMajor.valid) {
4876 touchMajor = toolMajor = in.toolMajor;
4877 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4878 ? in.toolMinor : in.toolMajor;
4879 size = mRawPointerAxes.toolMinor.valid
4880 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4881 } else {
4882 ALOG_ASSERT(false, "No touch or tool axes. "
4883 "Size calibration should have been resolved to NONE.");
4884 touchMajor = 0;
4885 touchMinor = 0;
4886 toolMajor = 0;
4887 toolMinor = 0;
4888 size = 0;
4889 }
4890
4891 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004892 uint32_t touchingCount =
4893 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 if (touchingCount > 1) {
4895 touchMajor /= touchingCount;
4896 touchMinor /= touchingCount;
4897 toolMajor /= touchingCount;
4898 toolMinor /= touchingCount;
4899 size /= touchingCount;
4900 }
4901 }
4902
4903 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4904 touchMajor *= mGeometricScale;
4905 touchMinor *= mGeometricScale;
4906 toolMajor *= mGeometricScale;
4907 toolMinor *= mGeometricScale;
4908 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4909 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4910 touchMinor = touchMajor;
4911 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4912 toolMinor = toolMajor;
4913 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4914 touchMinor = touchMajor;
4915 toolMinor = toolMajor;
4916 }
4917
4918 mCalibration.applySizeScaleAndBias(&touchMajor);
4919 mCalibration.applySizeScaleAndBias(&touchMinor);
4920 mCalibration.applySizeScaleAndBias(&toolMajor);
4921 mCalibration.applySizeScaleAndBias(&toolMinor);
4922 size *= mSizeScale;
4923 break;
4924 default:
4925 touchMajor = 0;
4926 touchMinor = 0;
4927 toolMajor = 0;
4928 toolMinor = 0;
4929 size = 0;
4930 break;
4931 }
4932
4933 // Pressure
4934 float pressure;
4935 switch (mCalibration.pressureCalibration) {
4936 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4937 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4938 pressure = in.pressure * mPressureScale;
4939 break;
4940 default:
4941 pressure = in.isHovering ? 0 : 1;
4942 break;
4943 }
4944
4945 // Tilt and Orientation
4946 float tilt;
4947 float orientation;
4948 if (mHaveTilt) {
4949 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4950 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4951 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4952 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4953 } else {
4954 tilt = 0;
4955
4956 switch (mCalibration.orientationCalibration) {
4957 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4958 orientation = in.orientation * mOrientationScale;
4959 break;
4960 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4961 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4962 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4963 if (c1 != 0 || c2 != 0) {
4964 orientation = atan2f(c1, c2) * 0.5f;
4965 float confidence = hypotf(c1, c2);
4966 float scale = 1.0f + confidence / 16.0f;
4967 touchMajor *= scale;
4968 touchMinor /= scale;
4969 toolMajor *= scale;
4970 toolMinor /= scale;
4971 } else {
4972 orientation = 0;
4973 }
4974 break;
4975 }
4976 default:
4977 orientation = 0;
4978 }
4979 }
4980
4981 // Distance
4982 float distance;
4983 switch (mCalibration.distanceCalibration) {
4984 case Calibration::DISTANCE_CALIBRATION_SCALED:
4985 distance = in.distance * mDistanceScale;
4986 break;
4987 default:
4988 distance = 0;
4989 }
4990
4991 // Coverage
4992 int32_t rawLeft, rawTop, rawRight, rawBottom;
4993 switch (mCalibration.coverageCalibration) {
4994 case Calibration::COVERAGE_CALIBRATION_BOX:
4995 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4996 rawRight = in.toolMinor & 0x0000ffff;
4997 rawBottom = in.toolMajor & 0x0000ffff;
4998 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4999 break;
5000 default:
5001 rawLeft = rawTop = rawRight = rawBottom = 0;
5002 break;
5003 }
5004
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005005 // Adjust X,Y coords for device calibration
5006 // TODO: Adjust coverage coords?
5007 float xTransformed = in.x, yTransformed = in.y;
5008 mAffineTransform.applyTo(xTransformed, yTransformed);
5009
5010 // Adjust X, Y, and coverage coords for surface orientation.
5011 float x, y;
5012 float left, top, right, bottom;
5013
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 switch (mSurfaceOrientation) {
5015 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005016 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5017 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5019 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5020 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5021 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5022 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005023 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5025 }
5026 break;
5027 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005028 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5029 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5031 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5032 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5033 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5034 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005035 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5037 }
5038 break;
5039 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005040 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5041 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5043 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5044 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5045 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5046 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005047 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5049 }
5050 break;
5051 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005052 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5053 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005054 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5055 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5056 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5057 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5058 break;
5059 }
5060
5061 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005062 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 out.clear();
5064 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5065 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5066 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5067 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5068 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5069 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5070 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5071 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5072 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5073 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5074 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5075 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5076 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5077 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5078 } else {
5079 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5080 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5081 }
5082
5083 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005084 PointerProperties& properties =
5085 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 uint32_t id = in.id;
5087 properties.clear();
5088 properties.id = id;
5089 properties.toolType = in.toolType;
5090
5091 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005092 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 }
5094}
5095
5096void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5097 PointerUsage pointerUsage) {
5098 if (pointerUsage != mPointerUsage) {
5099 abortPointerUsage(when, policyFlags);
5100 mPointerUsage = pointerUsage;
5101 }
5102
5103 switch (mPointerUsage) {
5104 case POINTER_USAGE_GESTURES:
5105 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5106 break;
5107 case POINTER_USAGE_STYLUS:
5108 dispatchPointerStylus(when, policyFlags);
5109 break;
5110 case POINTER_USAGE_MOUSE:
5111 dispatchPointerMouse(when, policyFlags);
5112 break;
5113 default:
5114 break;
5115 }
5116}
5117
5118void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5119 switch (mPointerUsage) {
5120 case POINTER_USAGE_GESTURES:
5121 abortPointerGestures(when, policyFlags);
5122 break;
5123 case POINTER_USAGE_STYLUS:
5124 abortPointerStylus(when, policyFlags);
5125 break;
5126 case POINTER_USAGE_MOUSE:
5127 abortPointerMouse(when, policyFlags);
5128 break;
5129 default:
5130 break;
5131 }
5132
5133 mPointerUsage = POINTER_USAGE_NONE;
5134}
5135
5136void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5137 bool isTimeout) {
5138 // Update current gesture coordinates.
5139 bool cancelPreviousGesture, finishPreviousGesture;
5140 bool sendEvents = preparePointerGestures(when,
5141 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5142 if (!sendEvents) {
5143 return;
5144 }
5145 if (finishPreviousGesture) {
5146 cancelPreviousGesture = false;
5147 }
5148
5149 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005150 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5151 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 if (finishPreviousGesture || cancelPreviousGesture) {
5153 mPointerController->clearSpots();
5154 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005155
5156 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5157 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5158 mPointerGesture.currentGestureIdToIndex,
5159 mPointerGesture.currentGestureIdBits);
5160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 } else {
5162 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5163 }
5164
5165 // Show or hide the pointer if needed.
5166 switch (mPointerGesture.currentGestureMode) {
5167 case PointerGesture::NEUTRAL:
5168 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005169 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5170 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 // Remind the user of where the pointer is after finishing a gesture with spots.
5172 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5173 }
5174 break;
5175 case PointerGesture::TAP:
5176 case PointerGesture::TAP_DRAG:
5177 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5178 case PointerGesture::HOVER:
5179 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005180 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 // Unfade the pointer when the current gesture manipulates the
5182 // area directly under the pointer.
5183 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5184 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 case PointerGesture::FREEFORM:
5186 // Fade the pointer when the current gesture manipulates a different
5187 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005188 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5190 } else {
5191 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5192 }
5193 break;
5194 }
5195
5196 // Send events!
5197 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005198 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199
5200 // Update last coordinates of pointers that have moved so that we observe the new
5201 // pointer positions at the same time as other pointers that have just gone up.
5202 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5203 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5204 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5205 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5206 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5207 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5208 bool moveNeeded = false;
5209 if (down && !cancelPreviousGesture && !finishPreviousGesture
5210 && !mPointerGesture.lastGestureIdBits.isEmpty()
5211 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5212 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5213 & mPointerGesture.lastGestureIdBits.value);
5214 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5215 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5216 mPointerGesture.lastGestureProperties,
5217 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5218 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005219 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 moveNeeded = true;
5221 }
5222 }
5223
5224 // Send motion events for all pointers that went up or were canceled.
5225 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5226 if (!dispatchedGestureIdBits.isEmpty()) {
5227 if (cancelPreviousGesture) {
5228 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005229 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 AMOTION_EVENT_EDGE_FLAG_NONE,
5231 mPointerGesture.lastGestureProperties,
5232 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005233 dispatchedGestureIdBits, -1, 0,
5234 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235
5236 dispatchedGestureIdBits.clear();
5237 } else {
5238 BitSet32 upGestureIdBits;
5239 if (finishPreviousGesture) {
5240 upGestureIdBits = dispatchedGestureIdBits;
5241 } else {
5242 upGestureIdBits.value = dispatchedGestureIdBits.value
5243 & ~mPointerGesture.currentGestureIdBits.value;
5244 }
5245 while (!upGestureIdBits.isEmpty()) {
5246 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5247
5248 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005249 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5251 mPointerGesture.lastGestureProperties,
5252 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5253 dispatchedGestureIdBits, id,
5254 0, 0, mPointerGesture.downTime);
5255
5256 dispatchedGestureIdBits.clearBit(id);
5257 }
5258 }
5259 }
5260
5261 // Send motion events for all pointers that moved.
5262 if (moveNeeded) {
5263 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005264 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5265 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 mPointerGesture.currentGestureProperties,
5267 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5268 dispatchedGestureIdBits, -1,
5269 0, 0, mPointerGesture.downTime);
5270 }
5271
5272 // Send motion events for all pointers that went down.
5273 if (down) {
5274 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5275 & ~dispatchedGestureIdBits.value);
5276 while (!downGestureIdBits.isEmpty()) {
5277 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5278 dispatchedGestureIdBits.markBit(id);
5279
5280 if (dispatchedGestureIdBits.count() == 1) {
5281 mPointerGesture.downTime = when;
5282 }
5283
5284 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005285 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 mPointerGesture.currentGestureProperties,
5287 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5288 dispatchedGestureIdBits, id,
5289 0, 0, mPointerGesture.downTime);
5290 }
5291 }
5292
5293 // Send motion events for hover.
5294 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5295 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005296 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5298 mPointerGesture.currentGestureProperties,
5299 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5300 mPointerGesture.currentGestureIdBits, -1,
5301 0, 0, mPointerGesture.downTime);
5302 } else if (dispatchedGestureIdBits.isEmpty()
5303 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5304 // Synthesize a hover move event after all pointers go up to indicate that
5305 // the pointer is hovering again even if the user is not currently touching
5306 // the touch pad. This ensures that a view will receive a fresh hover enter
5307 // event after a tap.
5308 float x, y;
5309 mPointerController->getPosition(&x, &y);
5310
5311 PointerProperties pointerProperties;
5312 pointerProperties.clear();
5313 pointerProperties.id = 0;
5314 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5315
5316 PointerCoords pointerCoords;
5317 pointerCoords.clear();
5318 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5319 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5320
5321 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005322 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5324 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5325 0, 0, mPointerGesture.downTime);
5326 getListener()->notifyMotion(&args);
5327 }
5328
5329 // Update state.
5330 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5331 if (!down) {
5332 mPointerGesture.lastGestureIdBits.clear();
5333 } else {
5334 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5335 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5336 uint32_t id = idBits.clearFirstMarkedBit();
5337 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5338 mPointerGesture.lastGestureProperties[index].copyFrom(
5339 mPointerGesture.currentGestureProperties[index]);
5340 mPointerGesture.lastGestureCoords[index].copyFrom(
5341 mPointerGesture.currentGestureCoords[index]);
5342 mPointerGesture.lastGestureIdToIndex[id] = index;
5343 }
5344 }
5345}
5346
5347void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5348 // Cancel previously dispatches pointers.
5349 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5350 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005351 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005353 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 AMOTION_EVENT_EDGE_FLAG_NONE,
5355 mPointerGesture.lastGestureProperties,
5356 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5357 mPointerGesture.lastGestureIdBits, -1,
5358 0, 0, mPointerGesture.downTime);
5359 }
5360
5361 // Reset the current pointer gesture.
5362 mPointerGesture.reset();
5363 mPointerVelocityControl.reset();
5364
5365 // Remove any current spots.
5366 if (mPointerController != NULL) {
5367 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5368 mPointerController->clearSpots();
5369 }
5370}
5371
5372bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5373 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5374 *outCancelPreviousGesture = false;
5375 *outFinishPreviousGesture = false;
5376
5377 // Handle TAP timeout.
5378 if (isTimeout) {
5379#if DEBUG_GESTURES
5380 ALOGD("Gestures: Processing timeout");
5381#endif
5382
5383 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5384 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5385 // The tap/drag timeout has not yet expired.
5386 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5387 + mConfig.pointerGestureTapDragInterval);
5388 } else {
5389 // The tap is finished.
5390#if DEBUG_GESTURES
5391 ALOGD("Gestures: TAP finished");
5392#endif
5393 *outFinishPreviousGesture = true;
5394
5395 mPointerGesture.activeGestureId = -1;
5396 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5397 mPointerGesture.currentGestureIdBits.clear();
5398
5399 mPointerVelocityControl.reset();
5400 return true;
5401 }
5402 }
5403
5404 // We did not handle this timeout.
5405 return false;
5406 }
5407
Michael Wright842500e2015-03-13 17:32:02 -07005408 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5409 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410
5411 // Update the velocity tracker.
5412 {
5413 VelocityTracker::Position positions[MAX_POINTERS];
5414 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005415 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005417 const RawPointerData::Pointer& pointer =
5418 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 positions[count].x = pointer.x * mPointerXMovementScale;
5420 positions[count].y = pointer.y * mPointerYMovementScale;
5421 }
5422 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005423 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 }
5425
5426 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5427 // to NEUTRAL, then we should not generate tap event.
5428 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5429 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5430 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5431 mPointerGesture.resetTap();
5432 }
5433
5434 // Pick a new active touch id if needed.
5435 // Choose an arbitrary pointer that just went down, if there is one.
5436 // Otherwise choose an arbitrary remaining pointer.
5437 // This guarantees we always have an active touch id when there is at least one pointer.
5438 // We keep the same active touch id for as long as possible.
5439 bool activeTouchChanged = false;
5440 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5441 int32_t activeTouchId = lastActiveTouchId;
5442 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005443 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 activeTouchChanged = true;
5445 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005446 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 mPointerGesture.firstTouchTime = when;
5448 }
Michael Wright842500e2015-03-13 17:32:02 -07005449 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005451 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005453 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 } else {
5455 activeTouchId = mPointerGesture.activeTouchId = -1;
5456 }
5457 }
5458
5459 // Determine whether we are in quiet time.
5460 bool isQuietTime = false;
5461 if (activeTouchId < 0) {
5462 mPointerGesture.resetQuietTime();
5463 } else {
5464 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5465 if (!isQuietTime) {
5466 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5467 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5468 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5469 && currentFingerCount < 2) {
5470 // Enter quiet time when exiting swipe or freeform state.
5471 // This is to prevent accidentally entering the hover state and flinging the
5472 // pointer when finishing a swipe and there is still one pointer left onscreen.
5473 isQuietTime = true;
5474 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5475 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005476 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 // Enter quiet time when releasing the button and there are still two or more
5478 // fingers down. This may indicate that one finger was used to press the button
5479 // but it has not gone up yet.
5480 isQuietTime = true;
5481 }
5482 if (isQuietTime) {
5483 mPointerGesture.quietTime = when;
5484 }
5485 }
5486 }
5487
5488 // Switch states based on button and pointer state.
5489 if (isQuietTime) {
5490 // Case 1: Quiet time. (QUIET)
5491#if DEBUG_GESTURES
5492 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5493 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5494#endif
5495 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5496 *outFinishPreviousGesture = true;
5497 }
5498
5499 mPointerGesture.activeGestureId = -1;
5500 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5501 mPointerGesture.currentGestureIdBits.clear();
5502
5503 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005504 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5506 // The pointer follows the active touch point.
5507 // Emit DOWN, MOVE, UP events at the pointer location.
5508 //
5509 // Only the active touch matters; other fingers are ignored. This policy helps
5510 // to handle the case where the user places a second finger on the touch pad
5511 // to apply the necessary force to depress an integrated button below the surface.
5512 // We don't want the second finger to be delivered to applications.
5513 //
5514 // For this to work well, we need to make sure to track the pointer that is really
5515 // active. If the user first puts one finger down to click then adds another
5516 // finger to drag then the active pointer should switch to the finger that is
5517 // being dragged.
5518#if DEBUG_GESTURES
5519 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5520 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5521#endif
5522 // Reset state when just starting.
5523 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5524 *outFinishPreviousGesture = true;
5525 mPointerGesture.activeGestureId = 0;
5526 }
5527
5528 // Switch pointers if needed.
5529 // Find the fastest pointer and follow it.
5530 if (activeTouchId >= 0 && currentFingerCount > 1) {
5531 int32_t bestId = -1;
5532 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005533 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 uint32_t id = idBits.clearFirstMarkedBit();
5535 float vx, vy;
5536 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5537 float speed = hypotf(vx, vy);
5538 if (speed > bestSpeed) {
5539 bestId = id;
5540 bestSpeed = speed;
5541 }
5542 }
5543 }
5544 if (bestId >= 0 && bestId != activeTouchId) {
5545 mPointerGesture.activeTouchId = activeTouchId = bestId;
5546 activeTouchChanged = true;
5547#if DEBUG_GESTURES
5548 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5549 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5550#endif
5551 }
5552 }
5553
Jun Mukaifa1706a2015-12-03 01:14:46 -08005554 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005555 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005557 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005559 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005560 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5561 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562
5563 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5564 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5565
5566 // Move the pointer using a relative motion.
5567 // When using spots, the click will occur at the position of the anchor
5568 // spot and all other spots will move there.
5569 mPointerController->move(deltaX, deltaY);
5570 } else {
5571 mPointerVelocityControl.reset();
5572 }
5573
5574 float x, y;
5575 mPointerController->getPosition(&x, &y);
5576
5577 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5578 mPointerGesture.currentGestureIdBits.clear();
5579 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5580 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5581 mPointerGesture.currentGestureProperties[0].clear();
5582 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5583 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5584 mPointerGesture.currentGestureCoords[0].clear();
5585 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5586 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5587 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5588 } else if (currentFingerCount == 0) {
5589 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5590 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5591 *outFinishPreviousGesture = true;
5592 }
5593
5594 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5595 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5596 bool tapped = false;
5597 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5598 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5599 && lastFingerCount == 1) {
5600 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5601 float x, y;
5602 mPointerController->getPosition(&x, &y);
5603 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5604 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5605#if DEBUG_GESTURES
5606 ALOGD("Gestures: TAP");
5607#endif
5608
5609 mPointerGesture.tapUpTime = when;
5610 getContext()->requestTimeoutAtTime(when
5611 + mConfig.pointerGestureTapDragInterval);
5612
5613 mPointerGesture.activeGestureId = 0;
5614 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5615 mPointerGesture.currentGestureIdBits.clear();
5616 mPointerGesture.currentGestureIdBits.markBit(
5617 mPointerGesture.activeGestureId);
5618 mPointerGesture.currentGestureIdToIndex[
5619 mPointerGesture.activeGestureId] = 0;
5620 mPointerGesture.currentGestureProperties[0].clear();
5621 mPointerGesture.currentGestureProperties[0].id =
5622 mPointerGesture.activeGestureId;
5623 mPointerGesture.currentGestureProperties[0].toolType =
5624 AMOTION_EVENT_TOOL_TYPE_FINGER;
5625 mPointerGesture.currentGestureCoords[0].clear();
5626 mPointerGesture.currentGestureCoords[0].setAxisValue(
5627 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5628 mPointerGesture.currentGestureCoords[0].setAxisValue(
5629 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5630 mPointerGesture.currentGestureCoords[0].setAxisValue(
5631 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5632
5633 tapped = true;
5634 } else {
5635#if DEBUG_GESTURES
5636 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5637 x - mPointerGesture.tapX,
5638 y - mPointerGesture.tapY);
5639#endif
5640 }
5641 } else {
5642#if DEBUG_GESTURES
5643 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5644 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5645 (when - mPointerGesture.tapDownTime) * 0.000001f);
5646 } else {
5647 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5648 }
5649#endif
5650 }
5651 }
5652
5653 mPointerVelocityControl.reset();
5654
5655 if (!tapped) {
5656#if DEBUG_GESTURES
5657 ALOGD("Gestures: NEUTRAL");
5658#endif
5659 mPointerGesture.activeGestureId = -1;
5660 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5661 mPointerGesture.currentGestureIdBits.clear();
5662 }
5663 } else if (currentFingerCount == 1) {
5664 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5665 // The pointer follows the active touch point.
5666 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5667 // When in TAP_DRAG, emit MOVE events at the pointer location.
5668 ALOG_ASSERT(activeTouchId >= 0);
5669
5670 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5671 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5672 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5673 float x, y;
5674 mPointerController->getPosition(&x, &y);
5675 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5676 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5677 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5678 } else {
5679#if DEBUG_GESTURES
5680 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5681 x - mPointerGesture.tapX,
5682 y - mPointerGesture.tapY);
5683#endif
5684 }
5685 } else {
5686#if DEBUG_GESTURES
5687 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5688 (when - mPointerGesture.tapUpTime) * 0.000001f);
5689#endif
5690 }
5691 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5692 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5693 }
5694
Jun Mukaifa1706a2015-12-03 01:14:46 -08005695 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005696 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005697 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005698 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005700 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005701 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5702 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703
5704 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5705 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5706
5707 // Move the pointer using a relative motion.
5708 // When using spots, the hover or drag will occur at the position of the anchor spot.
5709 mPointerController->move(deltaX, deltaY);
5710 } else {
5711 mPointerVelocityControl.reset();
5712 }
5713
5714 bool down;
5715 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5716#if DEBUG_GESTURES
5717 ALOGD("Gestures: TAP_DRAG");
5718#endif
5719 down = true;
5720 } else {
5721#if DEBUG_GESTURES
5722 ALOGD("Gestures: HOVER");
5723#endif
5724 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5725 *outFinishPreviousGesture = true;
5726 }
5727 mPointerGesture.activeGestureId = 0;
5728 down = false;
5729 }
5730
5731 float x, y;
5732 mPointerController->getPosition(&x, &y);
5733
5734 mPointerGesture.currentGestureIdBits.clear();
5735 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5736 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5737 mPointerGesture.currentGestureProperties[0].clear();
5738 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5739 mPointerGesture.currentGestureProperties[0].toolType =
5740 AMOTION_EVENT_TOOL_TYPE_FINGER;
5741 mPointerGesture.currentGestureCoords[0].clear();
5742 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5743 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5744 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5745 down ? 1.0f : 0.0f);
5746
5747 if (lastFingerCount == 0 && currentFingerCount != 0) {
5748 mPointerGesture.resetTap();
5749 mPointerGesture.tapDownTime = when;
5750 mPointerGesture.tapX = x;
5751 mPointerGesture.tapY = y;
5752 }
5753 } else {
5754 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5755 // We need to provide feedback for each finger that goes down so we cannot wait
5756 // for the fingers to move before deciding what to do.
5757 //
5758 // The ambiguous case is deciding what to do when there are two fingers down but they
5759 // have not moved enough to determine whether they are part of a drag or part of a
5760 // freeform gesture, or just a press or long-press at the pointer location.
5761 //
5762 // When there are two fingers we start with the PRESS hypothesis and we generate a
5763 // down at the pointer location.
5764 //
5765 // When the two fingers move enough or when additional fingers are added, we make
5766 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5767 ALOG_ASSERT(activeTouchId >= 0);
5768
5769 bool settled = when >= mPointerGesture.firstTouchTime
5770 + mConfig.pointerGestureMultitouchSettleInterval;
5771 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5772 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5773 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5774 *outFinishPreviousGesture = true;
5775 } else if (!settled && currentFingerCount > lastFingerCount) {
5776 // Additional pointers have gone down but not yet settled.
5777 // Reset the gesture.
5778#if DEBUG_GESTURES
5779 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5780 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5781 + mConfig.pointerGestureMultitouchSettleInterval - when)
5782 * 0.000001f);
5783#endif
5784 *outCancelPreviousGesture = true;
5785 } else {
5786 // Continue previous gesture.
5787 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5788 }
5789
5790 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5791 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5792 mPointerGesture.activeGestureId = 0;
5793 mPointerGesture.referenceIdBits.clear();
5794 mPointerVelocityControl.reset();
5795
5796 // Use the centroid and pointer location as the reference points for the gesture.
5797#if DEBUG_GESTURES
5798 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5799 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5800 + mConfig.pointerGestureMultitouchSettleInterval - when)
5801 * 0.000001f);
5802#endif
Michael Wright842500e2015-03-13 17:32:02 -07005803 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804 &mPointerGesture.referenceTouchX,
5805 &mPointerGesture.referenceTouchY);
5806 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5807 &mPointerGesture.referenceGestureY);
5808 }
5809
5810 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005811 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5813 uint32_t id = idBits.clearFirstMarkedBit();
5814 mPointerGesture.referenceDeltas[id].dx = 0;
5815 mPointerGesture.referenceDeltas[id].dy = 0;
5816 }
Michael Wright842500e2015-03-13 17:32:02 -07005817 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818
5819 // Add delta for all fingers and calculate a common movement delta.
5820 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005821 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5822 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5824 bool first = (idBits == commonIdBits);
5825 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005826 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5827 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5829 delta.dx += cpd.x - lpd.x;
5830 delta.dy += cpd.y - lpd.y;
5831
5832 if (first) {
5833 commonDeltaX = delta.dx;
5834 commonDeltaY = delta.dy;
5835 } else {
5836 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5837 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5838 }
5839 }
5840
5841 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5842 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5843 float dist[MAX_POINTER_ID + 1];
5844 int32_t distOverThreshold = 0;
5845 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5846 uint32_t id = idBits.clearFirstMarkedBit();
5847 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5848 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5849 delta.dy * mPointerYZoomScale);
5850 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5851 distOverThreshold += 1;
5852 }
5853 }
5854
5855 // Only transition when at least two pointers have moved further than
5856 // the minimum distance threshold.
5857 if (distOverThreshold >= 2) {
5858 if (currentFingerCount > 2) {
5859 // There are more than two pointers, switch to FREEFORM.
5860#if DEBUG_GESTURES
5861 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5862 currentFingerCount);
5863#endif
5864 *outCancelPreviousGesture = true;
5865 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5866 } else {
5867 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005868 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869 uint32_t id1 = idBits.clearFirstMarkedBit();
5870 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005871 const RawPointerData::Pointer& p1 =
5872 mCurrentRawState.rawPointerData.pointerForId(id1);
5873 const RawPointerData::Pointer& p2 =
5874 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005875 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5876 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5877 // There are two pointers but they are too far apart for a SWIPE,
5878 // switch to FREEFORM.
5879#if DEBUG_GESTURES
5880 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5881 mutualDistance, mPointerGestureMaxSwipeWidth);
5882#endif
5883 *outCancelPreviousGesture = true;
5884 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5885 } else {
5886 // There are two pointers. Wait for both pointers to start moving
5887 // before deciding whether this is a SWIPE or FREEFORM gesture.
5888 float dist1 = dist[id1];
5889 float dist2 = dist[id2];
5890 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5891 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5892 // Calculate the dot product of the displacement vectors.
5893 // When the vectors are oriented in approximately the same direction,
5894 // the angle betweeen them is near zero and the cosine of the angle
5895 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5896 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5897 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5898 float dx1 = delta1.dx * mPointerXZoomScale;
5899 float dy1 = delta1.dy * mPointerYZoomScale;
5900 float dx2 = delta2.dx * mPointerXZoomScale;
5901 float dy2 = delta2.dy * mPointerYZoomScale;
5902 float dot = dx1 * dx2 + dy1 * dy2;
5903 float cosine = dot / (dist1 * dist2); // denominator always > 0
5904 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5905 // Pointers are moving in the same direction. Switch to SWIPE.
5906#if DEBUG_GESTURES
5907 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5908 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5909 "cosine %0.3f >= %0.3f",
5910 dist1, mConfig.pointerGestureMultitouchMinDistance,
5911 dist2, mConfig.pointerGestureMultitouchMinDistance,
5912 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5913#endif
5914 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5915 } else {
5916 // Pointers are moving in different directions. Switch to FREEFORM.
5917#if DEBUG_GESTURES
5918 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5919 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5920 "cosine %0.3f < %0.3f",
5921 dist1, mConfig.pointerGestureMultitouchMinDistance,
5922 dist2, mConfig.pointerGestureMultitouchMinDistance,
5923 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5924#endif
5925 *outCancelPreviousGesture = true;
5926 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5927 }
5928 }
5929 }
5930 }
5931 }
5932 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5933 // Switch from SWIPE to FREEFORM if additional pointers go down.
5934 // Cancel previous gesture.
5935 if (currentFingerCount > 2) {
5936#if DEBUG_GESTURES
5937 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5938 currentFingerCount);
5939#endif
5940 *outCancelPreviousGesture = true;
5941 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5942 }
5943 }
5944
5945 // Move the reference points based on the overall group motion of the fingers
5946 // except in PRESS mode while waiting for a transition to occur.
5947 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5948 && (commonDeltaX || commonDeltaY)) {
5949 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5950 uint32_t id = idBits.clearFirstMarkedBit();
5951 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5952 delta.dx = 0;
5953 delta.dy = 0;
5954 }
5955
5956 mPointerGesture.referenceTouchX += commonDeltaX;
5957 mPointerGesture.referenceTouchY += commonDeltaY;
5958
5959 commonDeltaX *= mPointerXMovementScale;
5960 commonDeltaY *= mPointerYMovementScale;
5961
5962 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5963 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5964
5965 mPointerGesture.referenceGestureX += commonDeltaX;
5966 mPointerGesture.referenceGestureY += commonDeltaY;
5967 }
5968
5969 // Report gestures.
5970 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5971 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5972 // PRESS or SWIPE mode.
5973#if DEBUG_GESTURES
5974 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5975 "activeGestureId=%d, currentTouchPointerCount=%d",
5976 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5977#endif
5978 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5979
5980 mPointerGesture.currentGestureIdBits.clear();
5981 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5982 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5983 mPointerGesture.currentGestureProperties[0].clear();
5984 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5985 mPointerGesture.currentGestureProperties[0].toolType =
5986 AMOTION_EVENT_TOOL_TYPE_FINGER;
5987 mPointerGesture.currentGestureCoords[0].clear();
5988 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5989 mPointerGesture.referenceGestureX);
5990 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5991 mPointerGesture.referenceGestureY);
5992 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5993 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5994 // FREEFORM mode.
5995#if DEBUG_GESTURES
5996 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5997 "activeGestureId=%d, currentTouchPointerCount=%d",
5998 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5999#endif
6000 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6001
6002 mPointerGesture.currentGestureIdBits.clear();
6003
6004 BitSet32 mappedTouchIdBits;
6005 BitSet32 usedGestureIdBits;
6006 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6007 // Initially, assign the active gesture id to the active touch point
6008 // if there is one. No other touch id bits are mapped yet.
6009 if (!*outCancelPreviousGesture) {
6010 mappedTouchIdBits.markBit(activeTouchId);
6011 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6012 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6013 mPointerGesture.activeGestureId;
6014 } else {
6015 mPointerGesture.activeGestureId = -1;
6016 }
6017 } else {
6018 // Otherwise, assume we mapped all touches from the previous frame.
6019 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006020 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6021 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6023
6024 // Check whether we need to choose a new active gesture id because the
6025 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006026 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6027 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 !upTouchIdBits.isEmpty(); ) {
6029 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6030 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6031 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6032 mPointerGesture.activeGestureId = -1;
6033 break;
6034 }
6035 }
6036 }
6037
6038#if DEBUG_GESTURES
6039 ALOGD("Gestures: FREEFORM follow up "
6040 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6041 "activeGestureId=%d",
6042 mappedTouchIdBits.value, usedGestureIdBits.value,
6043 mPointerGesture.activeGestureId);
6044#endif
6045
Michael Wright842500e2015-03-13 17:32:02 -07006046 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047 for (uint32_t i = 0; i < currentFingerCount; i++) {
6048 uint32_t touchId = idBits.clearFirstMarkedBit();
6049 uint32_t gestureId;
6050 if (!mappedTouchIdBits.hasBit(touchId)) {
6051 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6052 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6053#if DEBUG_GESTURES
6054 ALOGD("Gestures: FREEFORM "
6055 "new mapping for touch id %d -> gesture id %d",
6056 touchId, gestureId);
6057#endif
6058 } else {
6059 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6060#if DEBUG_GESTURES
6061 ALOGD("Gestures: FREEFORM "
6062 "existing mapping for touch id %d -> gesture id %d",
6063 touchId, gestureId);
6064#endif
6065 }
6066 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6067 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6068
6069 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006070 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6072 * mPointerXZoomScale;
6073 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6074 * mPointerYZoomScale;
6075 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6076
6077 mPointerGesture.currentGestureProperties[i].clear();
6078 mPointerGesture.currentGestureProperties[i].id = gestureId;
6079 mPointerGesture.currentGestureProperties[i].toolType =
6080 AMOTION_EVENT_TOOL_TYPE_FINGER;
6081 mPointerGesture.currentGestureCoords[i].clear();
6082 mPointerGesture.currentGestureCoords[i].setAxisValue(
6083 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6084 mPointerGesture.currentGestureCoords[i].setAxisValue(
6085 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6086 mPointerGesture.currentGestureCoords[i].setAxisValue(
6087 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6088 }
6089
6090 if (mPointerGesture.activeGestureId < 0) {
6091 mPointerGesture.activeGestureId =
6092 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6093#if DEBUG_GESTURES
6094 ALOGD("Gestures: FREEFORM new "
6095 "activeGestureId=%d", mPointerGesture.activeGestureId);
6096#endif
6097 }
6098 }
6099 }
6100
Michael Wright842500e2015-03-13 17:32:02 -07006101 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102
6103#if DEBUG_GESTURES
6104 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6105 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6106 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6107 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6108 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6109 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6110 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6111 uint32_t id = idBits.clearFirstMarkedBit();
6112 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6113 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6114 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6115 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6116 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6117 id, index, properties.toolType,
6118 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6119 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6120 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6121 }
6122 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6123 uint32_t id = idBits.clearFirstMarkedBit();
6124 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6125 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6126 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6127 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6128 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6129 id, index, properties.toolType,
6130 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6131 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6132 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6133 }
6134#endif
6135 return true;
6136}
6137
6138void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6139 mPointerSimple.currentCoords.clear();
6140 mPointerSimple.currentProperties.clear();
6141
6142 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006143 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6144 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6145 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6146 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6147 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148 mPointerController->setPosition(x, y);
6149
Michael Wright842500e2015-03-13 17:32:02 -07006150 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006151 down = !hovering;
6152
6153 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006154 mPointerSimple.currentCoords.copyFrom(
6155 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6157 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6158 mPointerSimple.currentProperties.id = 0;
6159 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006160 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161 } else {
6162 down = false;
6163 hovering = false;
6164 }
6165
6166 dispatchPointerSimple(when, policyFlags, down, hovering);
6167}
6168
6169void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6170 abortPointerSimple(when, policyFlags);
6171}
6172
6173void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6174 mPointerSimple.currentCoords.clear();
6175 mPointerSimple.currentProperties.clear();
6176
6177 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006178 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6179 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6180 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006181 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006182 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6183 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006184 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006185 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006186 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006187 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006188 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 * mPointerYMovementScale;
6190
6191 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6192 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6193
6194 mPointerController->move(deltaX, deltaY);
6195 } else {
6196 mPointerVelocityControl.reset();
6197 }
6198
Michael Wright842500e2015-03-13 17:32:02 -07006199 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200 hovering = !down;
6201
6202 float x, y;
6203 mPointerController->getPosition(&x, &y);
6204 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006205 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006206 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6207 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6208 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6209 hovering ? 0.0f : 1.0f);
6210 mPointerSimple.currentProperties.id = 0;
6211 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006212 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213 } else {
6214 mPointerVelocityControl.reset();
6215
6216 down = false;
6217 hovering = false;
6218 }
6219
6220 dispatchPointerSimple(when, policyFlags, down, hovering);
6221}
6222
6223void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6224 abortPointerSimple(when, policyFlags);
6225
6226 mPointerVelocityControl.reset();
6227}
6228
6229void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6230 bool down, bool hovering) {
6231 int32_t metaState = getContext()->getGlobalMetaState();
6232
6233 if (mPointerController != NULL) {
6234 if (down || hovering) {
6235 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6236 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006237 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6239 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6240 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6241 }
6242 }
6243
6244 if (mPointerSimple.down && !down) {
6245 mPointerSimple.down = false;
6246
6247 // Send up.
6248 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006249 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250 mViewport.displayId,
6251 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6252 mOrientedXPrecision, mOrientedYPrecision,
6253 mPointerSimple.downTime);
6254 getListener()->notifyMotion(&args);
6255 }
6256
6257 if (mPointerSimple.hovering && !hovering) {
6258 mPointerSimple.hovering = false;
6259
6260 // Send hover exit.
6261 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006262 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263 mViewport.displayId,
6264 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6265 mOrientedXPrecision, mOrientedYPrecision,
6266 mPointerSimple.downTime);
6267 getListener()->notifyMotion(&args);
6268 }
6269
6270 if (down) {
6271 if (!mPointerSimple.down) {
6272 mPointerSimple.down = true;
6273 mPointerSimple.downTime = when;
6274
6275 // Send down.
6276 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006277 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 mViewport.displayId,
6279 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6280 mOrientedXPrecision, mOrientedYPrecision,
6281 mPointerSimple.downTime);
6282 getListener()->notifyMotion(&args);
6283 }
6284
6285 // Send move.
6286 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006287 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006288 mViewport.displayId,
6289 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6290 mOrientedXPrecision, mOrientedYPrecision,
6291 mPointerSimple.downTime);
6292 getListener()->notifyMotion(&args);
6293 }
6294
6295 if (hovering) {
6296 if (!mPointerSimple.hovering) {
6297 mPointerSimple.hovering = true;
6298
6299 // Send hover enter.
6300 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006301 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006302 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006303 mViewport.displayId,
6304 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6305 mOrientedXPrecision, mOrientedYPrecision,
6306 mPointerSimple.downTime);
6307 getListener()->notifyMotion(&args);
6308 }
6309
6310 // Send hover move.
6311 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006312 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006313 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 mViewport.displayId,
6315 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6316 mOrientedXPrecision, mOrientedYPrecision,
6317 mPointerSimple.downTime);
6318 getListener()->notifyMotion(&args);
6319 }
6320
Michael Wright842500e2015-03-13 17:32:02 -07006321 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6322 float vscroll = mCurrentRawState.rawVScroll;
6323 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 mWheelYVelocityControl.move(when, NULL, &vscroll);
6325 mWheelXVelocityControl.move(when, &hscroll, NULL);
6326
6327 // Send scroll.
6328 PointerCoords pointerCoords;
6329 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6330 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6331 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6332
6333 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006334 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335 mViewport.displayId,
6336 1, &mPointerSimple.currentProperties, &pointerCoords,
6337 mOrientedXPrecision, mOrientedYPrecision,
6338 mPointerSimple.downTime);
6339 getListener()->notifyMotion(&args);
6340 }
6341
6342 // Save state.
6343 if (down || hovering) {
6344 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6345 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6346 } else {
6347 mPointerSimple.reset();
6348 }
6349}
6350
6351void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6352 mPointerSimple.currentCoords.clear();
6353 mPointerSimple.currentProperties.clear();
6354
6355 dispatchPointerSimple(when, policyFlags, false, false);
6356}
6357
6358void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006359 int32_t action, int32_t actionButton, int32_t flags,
6360 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006362 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6363 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 PointerCoords pointerCoords[MAX_POINTERS];
6365 PointerProperties pointerProperties[MAX_POINTERS];
6366 uint32_t pointerCount = 0;
6367 while (!idBits.isEmpty()) {
6368 uint32_t id = idBits.clearFirstMarkedBit();
6369 uint32_t index = idToIndex[id];
6370 pointerProperties[pointerCount].copyFrom(properties[index]);
6371 pointerCoords[pointerCount].copyFrom(coords[index]);
6372
6373 if (changedId >= 0 && id == uint32_t(changedId)) {
6374 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6375 }
6376
6377 pointerCount += 1;
6378 }
6379
6380 ALOG_ASSERT(pointerCount != 0);
6381
6382 if (changedId >= 0 && pointerCount == 1) {
6383 // Replace initial down and final up action.
6384 // We can compare the action without masking off the changed pointer index
6385 // because we know the index is 0.
6386 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6387 action = AMOTION_EVENT_ACTION_DOWN;
6388 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6389 action = AMOTION_EVENT_ACTION_UP;
6390 } else {
6391 // Can't happen.
6392 ALOG_ASSERT(false);
6393 }
6394 }
6395
6396 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006397 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006398 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6399 xPrecision, yPrecision, downTime);
6400 getListener()->notifyMotion(&args);
6401}
6402
6403bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6404 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6405 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6406 BitSet32 idBits) const {
6407 bool changed = false;
6408 while (!idBits.isEmpty()) {
6409 uint32_t id = idBits.clearFirstMarkedBit();
6410 uint32_t inIndex = inIdToIndex[id];
6411 uint32_t outIndex = outIdToIndex[id];
6412
6413 const PointerProperties& curInProperties = inProperties[inIndex];
6414 const PointerCoords& curInCoords = inCoords[inIndex];
6415 PointerProperties& curOutProperties = outProperties[outIndex];
6416 PointerCoords& curOutCoords = outCoords[outIndex];
6417
6418 if (curInProperties != curOutProperties) {
6419 curOutProperties.copyFrom(curInProperties);
6420 changed = true;
6421 }
6422
6423 if (curInCoords != curOutCoords) {
6424 curOutCoords.copyFrom(curInCoords);
6425 changed = true;
6426 }
6427 }
6428 return changed;
6429}
6430
6431void TouchInputMapper::fadePointer() {
6432 if (mPointerController != NULL) {
6433 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6434 }
6435}
6436
Jeff Brownc9aa6282015-02-11 19:03:28 -08006437void TouchInputMapper::cancelTouch(nsecs_t when) {
6438 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006439 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006440}
6441
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6443 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6444 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6445}
6446
6447const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6448 int32_t x, int32_t y) {
6449 size_t numVirtualKeys = mVirtualKeys.size();
6450 for (size_t i = 0; i < numVirtualKeys; i++) {
6451 const VirtualKey& virtualKey = mVirtualKeys[i];
6452
6453#if DEBUG_VIRTUAL_KEYS
6454 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6455 "left=%d, top=%d, right=%d, bottom=%d",
6456 x, y,
6457 virtualKey.keyCode, virtualKey.scanCode,
6458 virtualKey.hitLeft, virtualKey.hitTop,
6459 virtualKey.hitRight, virtualKey.hitBottom);
6460#endif
6461
6462 if (virtualKey.isHit(x, y)) {
6463 return & virtualKey;
6464 }
6465 }
6466
6467 return NULL;
6468}
6469
Michael Wright842500e2015-03-13 17:32:02 -07006470void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6471 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6472 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006473
Michael Wright842500e2015-03-13 17:32:02 -07006474 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006475
6476 if (currentPointerCount == 0) {
6477 // No pointers to assign.
6478 return;
6479 }
6480
6481 if (lastPointerCount == 0) {
6482 // All pointers are new.
6483 for (uint32_t i = 0; i < currentPointerCount; i++) {
6484 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006485 current->rawPointerData.pointers[i].id = id;
6486 current->rawPointerData.idToIndex[id] = i;
6487 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006488 }
6489 return;
6490 }
6491
6492 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006493 && current->rawPointerData.pointers[0].toolType
6494 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006496 uint32_t id = last->rawPointerData.pointers[0].id;
6497 current->rawPointerData.pointers[0].id = id;
6498 current->rawPointerData.idToIndex[id] = 0;
6499 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006500 return;
6501 }
6502
6503 // General case.
6504 // We build a heap of squared euclidean distances between current and last pointers
6505 // associated with the current and last pointer indices. Then, we find the best
6506 // match (by distance) for each current pointer.
6507 // The pointers must have the same tool type but it is possible for them to
6508 // transition from hovering to touching or vice-versa while retaining the same id.
6509 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6510
6511 uint32_t heapSize = 0;
6512 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6513 currentPointerIndex++) {
6514 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6515 lastPointerIndex++) {
6516 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006517 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006519 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006520 if (currentPointer.toolType == lastPointer.toolType) {
6521 int64_t deltaX = currentPointer.x - lastPointer.x;
6522 int64_t deltaY = currentPointer.y - lastPointer.y;
6523
6524 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6525
6526 // Insert new element into the heap (sift up).
6527 heap[heapSize].currentPointerIndex = currentPointerIndex;
6528 heap[heapSize].lastPointerIndex = lastPointerIndex;
6529 heap[heapSize].distance = distance;
6530 heapSize += 1;
6531 }
6532 }
6533 }
6534
6535 // Heapify
6536 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6537 startIndex -= 1;
6538 for (uint32_t parentIndex = startIndex; ;) {
6539 uint32_t childIndex = parentIndex * 2 + 1;
6540 if (childIndex >= heapSize) {
6541 break;
6542 }
6543
6544 if (childIndex + 1 < heapSize
6545 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6546 childIndex += 1;
6547 }
6548
6549 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6550 break;
6551 }
6552
6553 swap(heap[parentIndex], heap[childIndex]);
6554 parentIndex = childIndex;
6555 }
6556 }
6557
6558#if DEBUG_POINTER_ASSIGNMENT
6559 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6560 for (size_t i = 0; i < heapSize; i++) {
6561 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6562 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6563 heap[i].distance);
6564 }
6565#endif
6566
6567 // Pull matches out by increasing order of distance.
6568 // To avoid reassigning pointers that have already been matched, the loop keeps track
6569 // of which last and current pointers have been matched using the matchedXXXBits variables.
6570 // It also tracks the used pointer id bits.
6571 BitSet32 matchedLastBits(0);
6572 BitSet32 matchedCurrentBits(0);
6573 BitSet32 usedIdBits(0);
6574 bool first = true;
6575 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6576 while (heapSize > 0) {
6577 if (first) {
6578 // The first time through the loop, we just consume the root element of
6579 // the heap (the one with smallest distance).
6580 first = false;
6581 } else {
6582 // Previous iterations consumed the root element of the heap.
6583 // Pop root element off of the heap (sift down).
6584 heap[0] = heap[heapSize];
6585 for (uint32_t parentIndex = 0; ;) {
6586 uint32_t childIndex = parentIndex * 2 + 1;
6587 if (childIndex >= heapSize) {
6588 break;
6589 }
6590
6591 if (childIndex + 1 < heapSize
6592 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6593 childIndex += 1;
6594 }
6595
6596 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6597 break;
6598 }
6599
6600 swap(heap[parentIndex], heap[childIndex]);
6601 parentIndex = childIndex;
6602 }
6603
6604#if DEBUG_POINTER_ASSIGNMENT
6605 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6606 for (size_t i = 0; i < heapSize; i++) {
6607 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6608 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6609 heap[i].distance);
6610 }
6611#endif
6612 }
6613
6614 heapSize -= 1;
6615
6616 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6617 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6618
6619 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6620 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6621
6622 matchedCurrentBits.markBit(currentPointerIndex);
6623 matchedLastBits.markBit(lastPointerIndex);
6624
Michael Wright842500e2015-03-13 17:32:02 -07006625 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6626 current->rawPointerData.pointers[currentPointerIndex].id = id;
6627 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6628 current->rawPointerData.markIdBit(id,
6629 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 usedIdBits.markBit(id);
6631
6632#if DEBUG_POINTER_ASSIGNMENT
6633 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6634 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6635#endif
6636 break;
6637 }
6638 }
6639
6640 // Assign fresh ids to pointers that were not matched in the process.
6641 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6642 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6643 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6644
Michael Wright842500e2015-03-13 17:32:02 -07006645 current->rawPointerData.pointers[currentPointerIndex].id = id;
6646 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6647 current->rawPointerData.markIdBit(id,
6648 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006649
6650#if DEBUG_POINTER_ASSIGNMENT
6651 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6652 currentPointerIndex, id);
6653#endif
6654 }
6655}
6656
6657int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6658 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6659 return AKEY_STATE_VIRTUAL;
6660 }
6661
6662 size_t numVirtualKeys = mVirtualKeys.size();
6663 for (size_t i = 0; i < numVirtualKeys; i++) {
6664 const VirtualKey& virtualKey = mVirtualKeys[i];
6665 if (virtualKey.keyCode == keyCode) {
6666 return AKEY_STATE_UP;
6667 }
6668 }
6669
6670 return AKEY_STATE_UNKNOWN;
6671}
6672
6673int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6674 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6675 return AKEY_STATE_VIRTUAL;
6676 }
6677
6678 size_t numVirtualKeys = mVirtualKeys.size();
6679 for (size_t i = 0; i < numVirtualKeys; i++) {
6680 const VirtualKey& virtualKey = mVirtualKeys[i];
6681 if (virtualKey.scanCode == scanCode) {
6682 return AKEY_STATE_UP;
6683 }
6684 }
6685
6686 return AKEY_STATE_UNKNOWN;
6687}
6688
6689bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6690 const int32_t* keyCodes, uint8_t* outFlags) {
6691 size_t numVirtualKeys = mVirtualKeys.size();
6692 for (size_t i = 0; i < numVirtualKeys; i++) {
6693 const VirtualKey& virtualKey = mVirtualKeys[i];
6694
6695 for (size_t i = 0; i < numCodes; i++) {
6696 if (virtualKey.keyCode == keyCodes[i]) {
6697 outFlags[i] = 1;
6698 }
6699 }
6700 }
6701
6702 return true;
6703}
6704
6705
6706// --- SingleTouchInputMapper ---
6707
6708SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6709 TouchInputMapper(device) {
6710}
6711
6712SingleTouchInputMapper::~SingleTouchInputMapper() {
6713}
6714
6715void SingleTouchInputMapper::reset(nsecs_t when) {
6716 mSingleTouchMotionAccumulator.reset(getDevice());
6717
6718 TouchInputMapper::reset(when);
6719}
6720
6721void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6722 TouchInputMapper::process(rawEvent);
6723
6724 mSingleTouchMotionAccumulator.process(rawEvent);
6725}
6726
Michael Wright842500e2015-03-13 17:32:02 -07006727void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006728 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006729 outState->rawPointerData.pointerCount = 1;
6730 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006731
6732 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6733 && (mTouchButtonAccumulator.isHovering()
6734 || (mRawPointerAxes.pressure.valid
6735 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006736 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006737
Michael Wright842500e2015-03-13 17:32:02 -07006738 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006739 outPointer.id = 0;
6740 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6741 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6742 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6743 outPointer.touchMajor = 0;
6744 outPointer.touchMinor = 0;
6745 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6746 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6747 outPointer.orientation = 0;
6748 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6749 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6750 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6751 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6752 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6753 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6754 }
6755 outPointer.isHovering = isHovering;
6756 }
6757}
6758
6759void SingleTouchInputMapper::configureRawPointerAxes() {
6760 TouchInputMapper::configureRawPointerAxes();
6761
6762 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6763 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6764 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6765 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6766 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6767 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6768 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6769}
6770
6771bool SingleTouchInputMapper::hasStylus() const {
6772 return mTouchButtonAccumulator.hasStylus();
6773}
6774
6775
6776// --- MultiTouchInputMapper ---
6777
6778MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6779 TouchInputMapper(device) {
6780}
6781
6782MultiTouchInputMapper::~MultiTouchInputMapper() {
6783}
6784
6785void MultiTouchInputMapper::reset(nsecs_t when) {
6786 mMultiTouchMotionAccumulator.reset(getDevice());
6787
6788 mPointerIdBits.clear();
6789
6790 TouchInputMapper::reset(when);
6791}
6792
6793void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6794 TouchInputMapper::process(rawEvent);
6795
6796 mMultiTouchMotionAccumulator.process(rawEvent);
6797}
6798
Michael Wright842500e2015-03-13 17:32:02 -07006799void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006800 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6801 size_t outCount = 0;
6802 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006803 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006804
6805 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6806 const MultiTouchMotionAccumulator::Slot* inSlot =
6807 mMultiTouchMotionAccumulator.getSlot(inIndex);
6808 if (!inSlot->isInUse()) {
6809 continue;
6810 }
6811
6812 if (outCount >= MAX_POINTERS) {
6813#if DEBUG_POINTERS
6814 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6815 "ignoring the rest.",
6816 getDeviceName().string(), MAX_POINTERS);
6817#endif
6818 break; // too many fingers!
6819 }
6820
Michael Wright842500e2015-03-13 17:32:02 -07006821 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006822 outPointer.x = inSlot->getX();
6823 outPointer.y = inSlot->getY();
6824 outPointer.pressure = inSlot->getPressure();
6825 outPointer.touchMajor = inSlot->getTouchMajor();
6826 outPointer.touchMinor = inSlot->getTouchMinor();
6827 outPointer.toolMajor = inSlot->getToolMajor();
6828 outPointer.toolMinor = inSlot->getToolMinor();
6829 outPointer.orientation = inSlot->getOrientation();
6830 outPointer.distance = inSlot->getDistance();
6831 outPointer.tiltX = 0;
6832 outPointer.tiltY = 0;
6833
6834 outPointer.toolType = inSlot->getToolType();
6835 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6836 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6837 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6838 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6839 }
6840 }
6841
6842 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6843 && (mTouchButtonAccumulator.isHovering()
6844 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6845 outPointer.isHovering = isHovering;
6846
6847 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006848 if (mHavePointerIds) {
6849 int32_t trackingId = inSlot->getTrackingId();
6850 int32_t id = -1;
6851 if (trackingId >= 0) {
6852 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6853 uint32_t n = idBits.clearFirstMarkedBit();
6854 if (mPointerTrackingIdMap[n] == trackingId) {
6855 id = n;
6856 }
6857 }
6858
6859 if (id < 0 && !mPointerIdBits.isFull()) {
6860 id = mPointerIdBits.markFirstUnmarkedBit();
6861 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006862 }
Michael Wright842500e2015-03-13 17:32:02 -07006863 }
gaoshang1a632de2016-08-24 10:23:50 +08006864 if (id < 0) {
6865 mHavePointerIds = false;
6866 outState->rawPointerData.clearIdBits();
6867 newPointerIdBits.clear();
6868 } else {
6869 outPointer.id = id;
6870 outState->rawPointerData.idToIndex[id] = outCount;
6871 outState->rawPointerData.markIdBit(id, isHovering);
6872 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006873 }
Michael Wright842500e2015-03-13 17:32:02 -07006874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006875 outCount += 1;
6876 }
6877
Michael Wright842500e2015-03-13 17:32:02 -07006878 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006879 mPointerIdBits = newPointerIdBits;
6880
6881 mMultiTouchMotionAccumulator.finishSync();
6882}
6883
6884void MultiTouchInputMapper::configureRawPointerAxes() {
6885 TouchInputMapper::configureRawPointerAxes();
6886
6887 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6888 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6889 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6890 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6891 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6892 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6893 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6894 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6895 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6896 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6897 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6898
6899 if (mRawPointerAxes.trackingId.valid
6900 && mRawPointerAxes.slot.valid
6901 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6902 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6903 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006904 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6905 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006906 getDeviceName().string(), slotCount, MAX_SLOTS);
6907 slotCount = MAX_SLOTS;
6908 }
6909 mMultiTouchMotionAccumulator.configure(getDevice(),
6910 slotCount, true /*usingSlotsProtocol*/);
6911 } else {
6912 mMultiTouchMotionAccumulator.configure(getDevice(),
6913 MAX_POINTERS, false /*usingSlotsProtocol*/);
6914 }
6915}
6916
6917bool MultiTouchInputMapper::hasStylus() const {
6918 return mMultiTouchMotionAccumulator.hasStylus()
6919 || mTouchButtonAccumulator.hasStylus();
6920}
6921
Michael Wright842500e2015-03-13 17:32:02 -07006922// --- ExternalStylusInputMapper
6923
6924ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6925 InputMapper(device) {
6926
6927}
6928
6929uint32_t ExternalStylusInputMapper::getSources() {
6930 return AINPUT_SOURCE_STYLUS;
6931}
6932
6933void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6934 InputMapper::populateDeviceInfo(info);
6935 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6936 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6937}
6938
6939void ExternalStylusInputMapper::dump(String8& dump) {
6940 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6941 dump.append(INDENT3 "Raw Stylus Axes:\n");
6942 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6943 dump.append(INDENT3 "Stylus State:\n");
6944 dumpStylusState(dump, mStylusState);
6945}
6946
6947void ExternalStylusInputMapper::configure(nsecs_t when,
6948 const InputReaderConfiguration* config, uint32_t changes) {
6949 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6950 mTouchButtonAccumulator.configure(getDevice());
6951}
6952
6953void ExternalStylusInputMapper::reset(nsecs_t when) {
6954 InputDevice* device = getDevice();
6955 mSingleTouchMotionAccumulator.reset(device);
6956 mTouchButtonAccumulator.reset(device);
6957 InputMapper::reset(when);
6958}
6959
6960void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6961 mSingleTouchMotionAccumulator.process(rawEvent);
6962 mTouchButtonAccumulator.process(rawEvent);
6963
6964 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6965 sync(rawEvent->when);
6966 }
6967}
6968
6969void ExternalStylusInputMapper::sync(nsecs_t when) {
6970 mStylusState.clear();
6971
6972 mStylusState.when = when;
6973
Michael Wright45ccacf2015-04-21 19:01:58 +01006974 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6975 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6976 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6977 }
6978
Michael Wright842500e2015-03-13 17:32:02 -07006979 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6980 if (mRawPressureAxis.valid) {
6981 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6982 } else if (mTouchButtonAccumulator.isToolActive()) {
6983 mStylusState.pressure = 1.0f;
6984 } else {
6985 mStylusState.pressure = 0.0f;
6986 }
6987
6988 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07006989
6990 mContext->dispatchExternalStylusState(mStylusState);
6991}
6992
Michael Wrightd02c5b62014-02-10 15:10:22 -08006993
6994// --- JoystickInputMapper ---
6995
6996JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6997 InputMapper(device) {
6998}
6999
7000JoystickInputMapper::~JoystickInputMapper() {
7001}
7002
7003uint32_t JoystickInputMapper::getSources() {
7004 return AINPUT_SOURCE_JOYSTICK;
7005}
7006
7007void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7008 InputMapper::populateDeviceInfo(info);
7009
7010 for (size_t i = 0; i < mAxes.size(); i++) {
7011 const Axis& axis = mAxes.valueAt(i);
7012 addMotionRange(axis.axisInfo.axis, axis, info);
7013
7014 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7015 addMotionRange(axis.axisInfo.highAxis, axis, info);
7016
7017 }
7018 }
7019}
7020
7021void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7022 InputDeviceInfo* info) {
7023 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7024 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7025 /* In order to ease the transition for developers from using the old axes
7026 * to the newer, more semantically correct axes, we'll continue to register
7027 * the old axes as duplicates of their corresponding new ones. */
7028 int32_t compatAxis = getCompatAxis(axisId);
7029 if (compatAxis >= 0) {
7030 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7031 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7032 }
7033}
7034
7035/* A mapping from axes the joystick actually has to the axes that should be
7036 * artificially created for compatibility purposes.
7037 * Returns -1 if no compatibility axis is needed. */
7038int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7039 switch(axis) {
7040 case AMOTION_EVENT_AXIS_LTRIGGER:
7041 return AMOTION_EVENT_AXIS_BRAKE;
7042 case AMOTION_EVENT_AXIS_RTRIGGER:
7043 return AMOTION_EVENT_AXIS_GAS;
7044 }
7045 return -1;
7046}
7047
7048void JoystickInputMapper::dump(String8& dump) {
7049 dump.append(INDENT2 "Joystick Input Mapper:\n");
7050
7051 dump.append(INDENT3 "Axes:\n");
7052 size_t numAxes = mAxes.size();
7053 for (size_t i = 0; i < numAxes; i++) {
7054 const Axis& axis = mAxes.valueAt(i);
7055 const char* label = getAxisLabel(axis.axisInfo.axis);
7056 if (label) {
7057 dump.appendFormat(INDENT4 "%s", label);
7058 } else {
7059 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7060 }
7061 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7062 label = getAxisLabel(axis.axisInfo.highAxis);
7063 if (label) {
7064 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7065 } else {
7066 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7067 axis.axisInfo.splitValue);
7068 }
7069 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7070 dump.append(" (invert)");
7071 }
7072
7073 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7074 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7075 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7076 "highScale=%0.5f, highOffset=%0.5f\n",
7077 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7078 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7079 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7080 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7081 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7082 }
7083}
7084
7085void JoystickInputMapper::configure(nsecs_t when,
7086 const InputReaderConfiguration* config, uint32_t changes) {
7087 InputMapper::configure(when, config, changes);
7088
7089 if (!changes) { // first time only
7090 // Collect all axes.
7091 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7092 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7093 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7094 continue; // axis must be claimed by a different device
7095 }
7096
7097 RawAbsoluteAxisInfo rawAxisInfo;
7098 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7099 if (rawAxisInfo.valid) {
7100 // Map axis.
7101 AxisInfo axisInfo;
7102 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7103 if (!explicitlyMapped) {
7104 // Axis is not explicitly mapped, will choose a generic axis later.
7105 axisInfo.mode = AxisInfo::MODE_NORMAL;
7106 axisInfo.axis = -1;
7107 }
7108
7109 // Apply flat override.
7110 int32_t rawFlat = axisInfo.flatOverride < 0
7111 ? rawAxisInfo.flat : axisInfo.flatOverride;
7112
7113 // Calculate scaling factors and limits.
7114 Axis axis;
7115 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7116 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7117 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7118 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7119 scale, 0.0f, highScale, 0.0f,
7120 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7121 rawAxisInfo.resolution * scale);
7122 } else if (isCenteredAxis(axisInfo.axis)) {
7123 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7124 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7125 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7126 scale, offset, scale, offset,
7127 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7128 rawAxisInfo.resolution * scale);
7129 } else {
7130 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7131 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7132 scale, 0.0f, scale, 0.0f,
7133 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7134 rawAxisInfo.resolution * scale);
7135 }
7136
7137 // To eliminate noise while the joystick is at rest, filter out small variations
7138 // in axis values up front.
7139 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7140
7141 mAxes.add(abs, axis);
7142 }
7143 }
7144
7145 // If there are too many axes, start dropping them.
7146 // Prefer to keep explicitly mapped axes.
7147 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007148 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007149 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7150 pruneAxes(true);
7151 pruneAxes(false);
7152 }
7153
7154 // Assign generic axis ids to remaining axes.
7155 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7156 size_t numAxes = mAxes.size();
7157 for (size_t i = 0; i < numAxes; i++) {
7158 Axis& axis = mAxes.editValueAt(i);
7159 if (axis.axisInfo.axis < 0) {
7160 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7161 && haveAxis(nextGenericAxisId)) {
7162 nextGenericAxisId += 1;
7163 }
7164
7165 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7166 axis.axisInfo.axis = nextGenericAxisId;
7167 nextGenericAxisId += 1;
7168 } else {
7169 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7170 "have already been assigned to other axes.",
7171 getDeviceName().string(), mAxes.keyAt(i));
7172 mAxes.removeItemsAt(i--);
7173 numAxes -= 1;
7174 }
7175 }
7176 }
7177 }
7178}
7179
7180bool JoystickInputMapper::haveAxis(int32_t axisId) {
7181 size_t numAxes = mAxes.size();
7182 for (size_t i = 0; i < numAxes; i++) {
7183 const Axis& axis = mAxes.valueAt(i);
7184 if (axis.axisInfo.axis == axisId
7185 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7186 && axis.axisInfo.highAxis == axisId)) {
7187 return true;
7188 }
7189 }
7190 return false;
7191}
7192
7193void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7194 size_t i = mAxes.size();
7195 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7196 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7197 continue;
7198 }
7199 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7200 getDeviceName().string(), mAxes.keyAt(i));
7201 mAxes.removeItemsAt(i);
7202 }
7203}
7204
7205bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7206 switch (axis) {
7207 case AMOTION_EVENT_AXIS_X:
7208 case AMOTION_EVENT_AXIS_Y:
7209 case AMOTION_EVENT_AXIS_Z:
7210 case AMOTION_EVENT_AXIS_RX:
7211 case AMOTION_EVENT_AXIS_RY:
7212 case AMOTION_EVENT_AXIS_RZ:
7213 case AMOTION_EVENT_AXIS_HAT_X:
7214 case AMOTION_EVENT_AXIS_HAT_Y:
7215 case AMOTION_EVENT_AXIS_ORIENTATION:
7216 case AMOTION_EVENT_AXIS_RUDDER:
7217 case AMOTION_EVENT_AXIS_WHEEL:
7218 return true;
7219 default:
7220 return false;
7221 }
7222}
7223
7224void JoystickInputMapper::reset(nsecs_t when) {
7225 // Recenter all axes.
7226 size_t numAxes = mAxes.size();
7227 for (size_t i = 0; i < numAxes; i++) {
7228 Axis& axis = mAxes.editValueAt(i);
7229 axis.resetValue();
7230 }
7231
7232 InputMapper::reset(when);
7233}
7234
7235void JoystickInputMapper::process(const RawEvent* rawEvent) {
7236 switch (rawEvent->type) {
7237 case EV_ABS: {
7238 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7239 if (index >= 0) {
7240 Axis& axis = mAxes.editValueAt(index);
7241 float newValue, highNewValue;
7242 switch (axis.axisInfo.mode) {
7243 case AxisInfo::MODE_INVERT:
7244 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7245 * axis.scale + axis.offset;
7246 highNewValue = 0.0f;
7247 break;
7248 case AxisInfo::MODE_SPLIT:
7249 if (rawEvent->value < axis.axisInfo.splitValue) {
7250 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7251 * axis.scale + axis.offset;
7252 highNewValue = 0.0f;
7253 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7254 newValue = 0.0f;
7255 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7256 * axis.highScale + axis.highOffset;
7257 } else {
7258 newValue = 0.0f;
7259 highNewValue = 0.0f;
7260 }
7261 break;
7262 default:
7263 newValue = rawEvent->value * axis.scale + axis.offset;
7264 highNewValue = 0.0f;
7265 break;
7266 }
7267 axis.newValue = newValue;
7268 axis.highNewValue = highNewValue;
7269 }
7270 break;
7271 }
7272
7273 case EV_SYN:
7274 switch (rawEvent->code) {
7275 case SYN_REPORT:
7276 sync(rawEvent->when, false /*force*/);
7277 break;
7278 }
7279 break;
7280 }
7281}
7282
7283void JoystickInputMapper::sync(nsecs_t when, bool force) {
7284 if (!filterAxes(force)) {
7285 return;
7286 }
7287
7288 int32_t metaState = mContext->getGlobalMetaState();
7289 int32_t buttonState = 0;
7290
7291 PointerProperties pointerProperties;
7292 pointerProperties.clear();
7293 pointerProperties.id = 0;
7294 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7295
7296 PointerCoords pointerCoords;
7297 pointerCoords.clear();
7298
7299 size_t numAxes = mAxes.size();
7300 for (size_t i = 0; i < numAxes; i++) {
7301 const Axis& axis = mAxes.valueAt(i);
7302 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7303 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7304 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7305 axis.highCurrentValue);
7306 }
7307 }
7308
7309 // Moving a joystick axis should not wake the device because joysticks can
7310 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7311 // button will likely wake the device.
7312 // TODO: Use the input device configuration to control this behavior more finely.
7313 uint32_t policyFlags = 0;
7314
7315 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007316 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007317 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7318 getListener()->notifyMotion(&args);
7319}
7320
7321void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7322 int32_t axis, float value) {
7323 pointerCoords->setAxisValue(axis, value);
7324 /* In order to ease the transition for developers from using the old axes
7325 * to the newer, more semantically correct axes, we'll continue to produce
7326 * values for the old axes as mirrors of the value of their corresponding
7327 * new axes. */
7328 int32_t compatAxis = getCompatAxis(axis);
7329 if (compatAxis >= 0) {
7330 pointerCoords->setAxisValue(compatAxis, value);
7331 }
7332}
7333
7334bool JoystickInputMapper::filterAxes(bool force) {
7335 bool atLeastOneSignificantChange = force;
7336 size_t numAxes = mAxes.size();
7337 for (size_t i = 0; i < numAxes; i++) {
7338 Axis& axis = mAxes.editValueAt(i);
7339 if (force || hasValueChangedSignificantly(axis.filter,
7340 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7341 axis.currentValue = axis.newValue;
7342 atLeastOneSignificantChange = true;
7343 }
7344 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7345 if (force || hasValueChangedSignificantly(axis.filter,
7346 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7347 axis.highCurrentValue = axis.highNewValue;
7348 atLeastOneSignificantChange = true;
7349 }
7350 }
7351 }
7352 return atLeastOneSignificantChange;
7353}
7354
7355bool JoystickInputMapper::hasValueChangedSignificantly(
7356 float filter, float newValue, float currentValue, float min, float max) {
7357 if (newValue != currentValue) {
7358 // Filter out small changes in value unless the value is converging on the axis
7359 // bounds or center point. This is intended to reduce the amount of information
7360 // sent to applications by particularly noisy joysticks (such as PS3).
7361 if (fabs(newValue - currentValue) > filter
7362 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7363 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7364 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7365 return true;
7366 }
7367 }
7368 return false;
7369}
7370
7371bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7372 float filter, float newValue, float currentValue, float thresholdValue) {
7373 float newDistance = fabs(newValue - thresholdValue);
7374 if (newDistance < filter) {
7375 float oldDistance = fabs(currentValue - thresholdValue);
7376 if (newDistance < oldDistance) {
7377 return true;
7378 }
7379 }
7380 return false;
7381}
7382
7383} // namespace android