blob: 97565aa0005252283e51c151f5b07c1861e3d2fe [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) :
2900 InputMapper(device) {
2901 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 }
2942}
2943
2944void RotaryEncoderInputMapper::reset(nsecs_t when) {
2945 mRotaryEncoderScrollAccumulator.reset(getDevice());
2946
2947 InputMapper::reset(when);
2948}
2949
2950void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2951 mRotaryEncoderScrollAccumulator.process(rawEvent);
2952
2953 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2954 sync(rawEvent->when);
2955 }
2956}
2957
2958void RotaryEncoderInputMapper::sync(nsecs_t when) {
2959 PointerCoords pointerCoords;
2960 pointerCoords.clear();
2961
2962 PointerProperties pointerProperties;
2963 pointerProperties.clear();
2964 pointerProperties.id = 0;
2965 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2966
2967 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2968 bool scrolled = scroll != 0;
2969
2970 // This is not a pointer, so it's not associated with a display.
2971 int32_t displayId = ADISPLAY_ID_NONE;
2972
2973 // Moving the rotary encoder should wake the device (if specified).
2974 uint32_t policyFlags = 0;
2975 if (scrolled && getDevice()->isExternal()) {
2976 policyFlags |= POLICY_FLAG_WAKE;
2977 }
2978
2979 // Send motion event.
2980 if (scrolled) {
2981 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002982 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002983
2984 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2985 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2986 AMOTION_EVENT_EDGE_FLAG_NONE,
2987 displayId, 1, &pointerProperties, &pointerCoords,
2988 0, 0, 0);
2989 getListener()->notifyMotion(&scrollArgs);
2990 }
2991
2992 mRotaryEncoderScrollAccumulator.finishSync();
2993}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994
2995// --- TouchInputMapper ---
2996
2997TouchInputMapper::TouchInputMapper(InputDevice* device) :
2998 InputMapper(device),
2999 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3000 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3001 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3002}
3003
3004TouchInputMapper::~TouchInputMapper() {
3005}
3006
3007uint32_t TouchInputMapper::getSources() {
3008 return mSource;
3009}
3010
3011void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3012 InputMapper::populateDeviceInfo(info);
3013
3014 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3015 info->addMotionRange(mOrientedRanges.x);
3016 info->addMotionRange(mOrientedRanges.y);
3017 info->addMotionRange(mOrientedRanges.pressure);
3018
3019 if (mOrientedRanges.haveSize) {
3020 info->addMotionRange(mOrientedRanges.size);
3021 }
3022
3023 if (mOrientedRanges.haveTouchSize) {
3024 info->addMotionRange(mOrientedRanges.touchMajor);
3025 info->addMotionRange(mOrientedRanges.touchMinor);
3026 }
3027
3028 if (mOrientedRanges.haveToolSize) {
3029 info->addMotionRange(mOrientedRanges.toolMajor);
3030 info->addMotionRange(mOrientedRanges.toolMinor);
3031 }
3032
3033 if (mOrientedRanges.haveOrientation) {
3034 info->addMotionRange(mOrientedRanges.orientation);
3035 }
3036
3037 if (mOrientedRanges.haveDistance) {
3038 info->addMotionRange(mOrientedRanges.distance);
3039 }
3040
3041 if (mOrientedRanges.haveTilt) {
3042 info->addMotionRange(mOrientedRanges.tilt);
3043 }
3044
3045 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3046 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3047 0.0f);
3048 }
3049 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3050 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3051 0.0f);
3052 }
3053 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3054 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3055 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3056 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3057 x.fuzz, x.resolution);
3058 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3059 y.fuzz, y.resolution);
3060 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3061 x.fuzz, x.resolution);
3062 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3063 y.fuzz, y.resolution);
3064 }
3065 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3066 }
3067}
3068
3069void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003070 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071 dumpParameters(dump);
3072 dumpVirtualKeys(dump);
3073 dumpRawPointerAxes(dump);
3074 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003075 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 dumpSurface(dump);
3077
3078 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3079 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3080 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3081 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3082 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3083 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3084 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3085 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3086 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3087 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3088 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3089 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3090 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3091 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3092 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3093 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3094 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3095
Michael Wright7b159c92015-05-14 14:48:03 +01003096 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003098 mLastRawState.rawPointerData.pointerCount);
3099 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3100 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3102 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3103 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3104 "toolType=%d, isHovering=%s\n", i,
3105 pointer.id, pointer.x, pointer.y, pointer.pressure,
3106 pointer.touchMajor, pointer.touchMinor,
3107 pointer.toolMajor, pointer.toolMinor,
3108 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3109 pointer.toolType, toString(pointer.isHovering));
3110 }
3111
Michael Wright7b159c92015-05-14 14:48:03 +01003112 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003114 mLastCookedState.cookedPointerData.pointerCount);
3115 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3116 const PointerProperties& pointerProperties =
3117 mLastCookedState.cookedPointerData.pointerProperties[i];
3118 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3120 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3121 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3122 "toolType=%d, isHovering=%s\n", i,
3123 pointerProperties.id,
3124 pointerCoords.getX(),
3125 pointerCoords.getY(),
3126 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3127 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3128 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3129 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3130 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3131 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3132 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3133 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3134 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003135 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 }
3137
Michael Wright842500e2015-03-13 17:32:02 -07003138 dump.append(INDENT3 "Stylus Fusion:\n");
3139 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3140 toString(mExternalStylusConnected));
3141 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3142 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003143 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003144 dump.append(INDENT3 "External Stylus State:\n");
3145 dumpStylusState(dump, mExternalStylusState);
3146
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 if (mDeviceMode == DEVICE_MODE_POINTER) {
3148 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3149 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3150 mPointerXMovementScale);
3151 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3152 mPointerYMovementScale);
3153 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3154 mPointerXZoomScale);
3155 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3156 mPointerYZoomScale);
3157 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3158 mPointerGestureMaxSwipeWidth);
3159 }
3160}
3161
Santos Cordonfa5cf462017-04-05 10:37:00 -07003162const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3163 switch (deviceMode) {
3164 case DEVICE_MODE_DISABLED:
3165 return "disabled";
3166 case DEVICE_MODE_DIRECT:
3167 return "direct";
3168 case DEVICE_MODE_UNSCALED:
3169 return "unscaled";
3170 case DEVICE_MODE_NAVIGATION:
3171 return "navigation";
3172 case DEVICE_MODE_POINTER:
3173 return "pointer";
3174 }
3175 return "unknown";
3176}
3177
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178void TouchInputMapper::configure(nsecs_t when,
3179 const InputReaderConfiguration* config, uint32_t changes) {
3180 InputMapper::configure(when, config, changes);
3181
3182 mConfig = *config;
3183
3184 if (!changes) { // first time only
3185 // Configure basic parameters.
3186 configureParameters();
3187
3188 // Configure common accumulators.
3189 mCursorScrollAccumulator.configure(getDevice());
3190 mTouchButtonAccumulator.configure(getDevice());
3191
3192 // Configure absolute axis information.
3193 configureRawPointerAxes();
3194
3195 // Prepare input device calibration.
3196 parseCalibration();
3197 resolveCalibration();
3198 }
3199
Michael Wright842500e2015-03-13 17:32:02 -07003200 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003201 // Update location calibration to reflect current settings
3202 updateAffineTransformation();
3203 }
3204
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3206 // Update pointer speed.
3207 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3208 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3209 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3210 }
3211
3212 bool resetNeeded = false;
3213 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3214 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003215 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3216 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 // Configure device sources, surface dimensions, orientation and
3218 // scaling factors.
3219 configureSurface(when, &resetNeeded);
3220 }
3221
3222 if (changes && resetNeeded) {
3223 // Send reset, unless this is the first time the device has been configured,
3224 // in which case the reader will call reset itself after all mappers are ready.
3225 getDevice()->notifyReset(when);
3226 }
3227}
3228
Michael Wright842500e2015-03-13 17:32:02 -07003229void TouchInputMapper::resolveExternalStylusPresence() {
3230 Vector<InputDeviceInfo> devices;
3231 mContext->getExternalStylusDevices(devices);
3232 mExternalStylusConnected = !devices.isEmpty();
3233
3234 if (!mExternalStylusConnected) {
3235 resetExternalStylus();
3236 }
3237}
3238
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239void TouchInputMapper::configureParameters() {
3240 // Use the pointer presentation mode for devices that do not support distinct
3241 // multitouch. The spot-based presentation relies on being able to accurately
3242 // locate two or more fingers on the touch pad.
3243 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003244 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245
3246 String8 gestureModeString;
3247 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3248 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003249 if (gestureModeString == "single-touch") {
3250 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3251 } else if (gestureModeString == "multi-touch") {
3252 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 } else if (gestureModeString != "default") {
3254 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3255 }
3256 }
3257
3258 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3259 // The device is a touch screen.
3260 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3261 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3262 // The device is a pointing device like a track pad.
3263 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3264 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3265 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3266 // The device is a cursor device with a touch pad attached.
3267 // By default don't use the touch pad to move the pointer.
3268 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3269 } else {
3270 // The device is a touch pad of unknown purpose.
3271 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3272 }
3273
3274 mParameters.hasButtonUnderPad=
3275 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3276
3277 String8 deviceTypeString;
3278 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3279 deviceTypeString)) {
3280 if (deviceTypeString == "touchScreen") {
3281 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3282 } else if (deviceTypeString == "touchPad") {
3283 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3284 } else if (deviceTypeString == "touchNavigation") {
3285 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3286 } else if (deviceTypeString == "pointer") {
3287 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3288 } else if (deviceTypeString != "default") {
3289 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3290 }
3291 }
3292
3293 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3294 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3295 mParameters.orientationAware);
3296
3297 mParameters.hasAssociatedDisplay = false;
3298 mParameters.associatedDisplayIsExternal = false;
3299 if (mParameters.orientationAware
3300 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3301 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3302 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003303 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3304 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3305 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3306 mParameters.uniqueDisplayId);
3307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003309
3310 // Initial downs on external touch devices should wake the device.
3311 // Normally we don't do this for internal touch screens to prevent them from waking
3312 // up in your pocket but you can enable it using the input device configuration.
3313 mParameters.wake = getDevice()->isExternal();
3314 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3315 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316}
3317
3318void TouchInputMapper::dumpParameters(String8& dump) {
3319 dump.append(INDENT3 "Parameters:\n");
3320
3321 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003322 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3323 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003325 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3326 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 break;
3328 default:
3329 assert(false);
3330 }
3331
3332 switch (mParameters.deviceType) {
3333 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3334 dump.append(INDENT4 "DeviceType: touchScreen\n");
3335 break;
3336 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3337 dump.append(INDENT4 "DeviceType: touchPad\n");
3338 break;
3339 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3340 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3341 break;
3342 case Parameters::DEVICE_TYPE_POINTER:
3343 dump.append(INDENT4 "DeviceType: pointer\n");
3344 break;
3345 default:
3346 ALOG_ASSERT(false);
3347 }
3348
Santos Cordonfa5cf462017-04-05 10:37:00 -07003349 dump.appendFormat(
3350 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003352 toString(mParameters.associatedDisplayIsExternal),
3353 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3355 toString(mParameters.orientationAware));
3356}
3357
3358void TouchInputMapper::configureRawPointerAxes() {
3359 mRawPointerAxes.clear();
3360}
3361
3362void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3363 dump.append(INDENT3 "Raw Touch Axes:\n");
3364 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3365 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3366 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3367 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3368 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3369 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3370 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3371 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3372 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3373 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3374 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3375 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3376 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3377}
3378
Michael Wright842500e2015-03-13 17:32:02 -07003379bool TouchInputMapper::hasExternalStylus() const {
3380 return mExternalStylusConnected;
3381}
3382
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3384 int32_t oldDeviceMode = mDeviceMode;
3385
Michael Wright842500e2015-03-13 17:32:02 -07003386 resolveExternalStylusPresence();
3387
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 // Determine device mode.
3389 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3390 && mConfig.pointerGesturesEnabled) {
3391 mSource = AINPUT_SOURCE_MOUSE;
3392 mDeviceMode = DEVICE_MODE_POINTER;
3393 if (hasStylus()) {
3394 mSource |= AINPUT_SOURCE_STYLUS;
3395 }
3396 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3397 && mParameters.hasAssociatedDisplay) {
3398 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3399 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003400 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 mSource |= AINPUT_SOURCE_STYLUS;
3402 }
Michael Wright2f78b682015-06-12 15:25:08 +01003403 if (hasExternalStylus()) {
3404 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3407 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3408 mDeviceMode = DEVICE_MODE_NAVIGATION;
3409 } else {
3410 mSource = AINPUT_SOURCE_TOUCHPAD;
3411 mDeviceMode = DEVICE_MODE_UNSCALED;
3412 }
3413
3414 // Ensure we have valid X and Y axes.
3415 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3416 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3417 "The device will be inoperable.", getDeviceName().string());
3418 mDeviceMode = DEVICE_MODE_DISABLED;
3419 return;
3420 }
3421
3422 // Raw width and height in the natural orientation.
3423 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3424 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3425
3426 // Get associated display dimensions.
3427 DisplayViewport newViewport;
3428 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003429 const String8* uniqueDisplayId = NULL;
3430 ViewportType viewportTypeToUse;
3431
3432 if (mParameters.associatedDisplayIsExternal) {
3433 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3434 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3435 // If the IDC file specified a unique display Id, then it expects to be linked to a
3436 // virtual display with the same unique ID.
3437 uniqueDisplayId = &mParameters.uniqueDisplayId;
3438 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3439 } else {
3440 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3441 }
3442
3443 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3445 "display. The device will be inoperable until the display size "
3446 "becomes available.",
3447 getDeviceName().string());
3448 mDeviceMode = DEVICE_MODE_DISABLED;
3449 return;
3450 }
3451 } else {
3452 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3453 }
3454 bool viewportChanged = mViewport != newViewport;
3455 if (viewportChanged) {
3456 mViewport = newViewport;
3457
3458 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3459 // Convert rotated viewport to natural surface coordinates.
3460 int32_t naturalLogicalWidth, naturalLogicalHeight;
3461 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3462 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3463 int32_t naturalDeviceWidth, naturalDeviceHeight;
3464 switch (mViewport.orientation) {
3465 case DISPLAY_ORIENTATION_90:
3466 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3467 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3468 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3469 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3470 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3471 naturalPhysicalTop = mViewport.physicalLeft;
3472 naturalDeviceWidth = mViewport.deviceHeight;
3473 naturalDeviceHeight = mViewport.deviceWidth;
3474 break;
3475 case DISPLAY_ORIENTATION_180:
3476 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3477 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3478 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3479 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3480 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3481 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3482 naturalDeviceWidth = mViewport.deviceWidth;
3483 naturalDeviceHeight = mViewport.deviceHeight;
3484 break;
3485 case DISPLAY_ORIENTATION_270:
3486 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3487 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3488 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3489 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3490 naturalPhysicalLeft = mViewport.physicalTop;
3491 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3492 naturalDeviceWidth = mViewport.deviceHeight;
3493 naturalDeviceHeight = mViewport.deviceWidth;
3494 break;
3495 case DISPLAY_ORIENTATION_0:
3496 default:
3497 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3498 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3499 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3500 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3501 naturalPhysicalLeft = mViewport.physicalLeft;
3502 naturalPhysicalTop = mViewport.physicalTop;
3503 naturalDeviceWidth = mViewport.deviceWidth;
3504 naturalDeviceHeight = mViewport.deviceHeight;
3505 break;
3506 }
3507
3508 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3509 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3510 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3511 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3512
3513 mSurfaceOrientation = mParameters.orientationAware ?
3514 mViewport.orientation : DISPLAY_ORIENTATION_0;
3515 } else {
3516 mSurfaceWidth = rawWidth;
3517 mSurfaceHeight = rawHeight;
3518 mSurfaceLeft = 0;
3519 mSurfaceTop = 0;
3520 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3521 }
3522 }
3523
3524 // If moving between pointer modes, need to reset some state.
3525 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3526 if (deviceModeChanged) {
3527 mOrientedRanges.clear();
3528 }
3529
3530 // Create pointer controller if needed.
3531 if (mDeviceMode == DEVICE_MODE_POINTER ||
3532 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3533 if (mPointerController == NULL) {
3534 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3535 }
3536 } else {
3537 mPointerController.clear();
3538 }
3539
3540 if (viewportChanged || deviceModeChanged) {
3541 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3542 "display id %d",
3543 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3544 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3545
3546 // Configure X and Y factors.
3547 mXScale = float(mSurfaceWidth) / rawWidth;
3548 mYScale = float(mSurfaceHeight) / rawHeight;
3549 mXTranslate = -mSurfaceLeft;
3550 mYTranslate = -mSurfaceTop;
3551 mXPrecision = 1.0f / mXScale;
3552 mYPrecision = 1.0f / mYScale;
3553
3554 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3555 mOrientedRanges.x.source = mSource;
3556 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3557 mOrientedRanges.y.source = mSource;
3558
3559 configureVirtualKeys();
3560
3561 // Scale factor for terms that are not oriented in a particular axis.
3562 // If the pixels are square then xScale == yScale otherwise we fake it
3563 // by choosing an average.
3564 mGeometricScale = avg(mXScale, mYScale);
3565
3566 // Size of diagonal axis.
3567 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3568
3569 // Size factors.
3570 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3571 if (mRawPointerAxes.touchMajor.valid
3572 && mRawPointerAxes.touchMajor.maxValue != 0) {
3573 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3574 } else if (mRawPointerAxes.toolMajor.valid
3575 && mRawPointerAxes.toolMajor.maxValue != 0) {
3576 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3577 } else {
3578 mSizeScale = 0.0f;
3579 }
3580
3581 mOrientedRanges.haveTouchSize = true;
3582 mOrientedRanges.haveToolSize = true;
3583 mOrientedRanges.haveSize = true;
3584
3585 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3586 mOrientedRanges.touchMajor.source = mSource;
3587 mOrientedRanges.touchMajor.min = 0;
3588 mOrientedRanges.touchMajor.max = diagonalSize;
3589 mOrientedRanges.touchMajor.flat = 0;
3590 mOrientedRanges.touchMajor.fuzz = 0;
3591 mOrientedRanges.touchMajor.resolution = 0;
3592
3593 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3594 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3595
3596 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3597 mOrientedRanges.toolMajor.source = mSource;
3598 mOrientedRanges.toolMajor.min = 0;
3599 mOrientedRanges.toolMajor.max = diagonalSize;
3600 mOrientedRanges.toolMajor.flat = 0;
3601 mOrientedRanges.toolMajor.fuzz = 0;
3602 mOrientedRanges.toolMajor.resolution = 0;
3603
3604 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3605 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3606
3607 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3608 mOrientedRanges.size.source = mSource;
3609 mOrientedRanges.size.min = 0;
3610 mOrientedRanges.size.max = 1.0;
3611 mOrientedRanges.size.flat = 0;
3612 mOrientedRanges.size.fuzz = 0;
3613 mOrientedRanges.size.resolution = 0;
3614 } else {
3615 mSizeScale = 0.0f;
3616 }
3617
3618 // Pressure factors.
3619 mPressureScale = 0;
3620 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3621 || mCalibration.pressureCalibration
3622 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3623 if (mCalibration.havePressureScale) {
3624 mPressureScale = mCalibration.pressureScale;
3625 } else if (mRawPointerAxes.pressure.valid
3626 && mRawPointerAxes.pressure.maxValue != 0) {
3627 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3628 }
3629 }
3630
3631 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3632 mOrientedRanges.pressure.source = mSource;
3633 mOrientedRanges.pressure.min = 0;
3634 mOrientedRanges.pressure.max = 1.0;
3635 mOrientedRanges.pressure.flat = 0;
3636 mOrientedRanges.pressure.fuzz = 0;
3637 mOrientedRanges.pressure.resolution = 0;
3638
3639 // Tilt
3640 mTiltXCenter = 0;
3641 mTiltXScale = 0;
3642 mTiltYCenter = 0;
3643 mTiltYScale = 0;
3644 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3645 if (mHaveTilt) {
3646 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3647 mRawPointerAxes.tiltX.maxValue);
3648 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3649 mRawPointerAxes.tiltY.maxValue);
3650 mTiltXScale = M_PI / 180;
3651 mTiltYScale = M_PI / 180;
3652
3653 mOrientedRanges.haveTilt = true;
3654
3655 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3656 mOrientedRanges.tilt.source = mSource;
3657 mOrientedRanges.tilt.min = 0;
3658 mOrientedRanges.tilt.max = M_PI_2;
3659 mOrientedRanges.tilt.flat = 0;
3660 mOrientedRanges.tilt.fuzz = 0;
3661 mOrientedRanges.tilt.resolution = 0;
3662 }
3663
3664 // Orientation
3665 mOrientationScale = 0;
3666 if (mHaveTilt) {
3667 mOrientedRanges.haveOrientation = true;
3668
3669 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3670 mOrientedRanges.orientation.source = mSource;
3671 mOrientedRanges.orientation.min = -M_PI;
3672 mOrientedRanges.orientation.max = M_PI;
3673 mOrientedRanges.orientation.flat = 0;
3674 mOrientedRanges.orientation.fuzz = 0;
3675 mOrientedRanges.orientation.resolution = 0;
3676 } else if (mCalibration.orientationCalibration !=
3677 Calibration::ORIENTATION_CALIBRATION_NONE) {
3678 if (mCalibration.orientationCalibration
3679 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3680 if (mRawPointerAxes.orientation.valid) {
3681 if (mRawPointerAxes.orientation.maxValue > 0) {
3682 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3683 } else if (mRawPointerAxes.orientation.minValue < 0) {
3684 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3685 } else {
3686 mOrientationScale = 0;
3687 }
3688 }
3689 }
3690
3691 mOrientedRanges.haveOrientation = true;
3692
3693 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3694 mOrientedRanges.orientation.source = mSource;
3695 mOrientedRanges.orientation.min = -M_PI_2;
3696 mOrientedRanges.orientation.max = M_PI_2;
3697 mOrientedRanges.orientation.flat = 0;
3698 mOrientedRanges.orientation.fuzz = 0;
3699 mOrientedRanges.orientation.resolution = 0;
3700 }
3701
3702 // Distance
3703 mDistanceScale = 0;
3704 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3705 if (mCalibration.distanceCalibration
3706 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3707 if (mCalibration.haveDistanceScale) {
3708 mDistanceScale = mCalibration.distanceScale;
3709 } else {
3710 mDistanceScale = 1.0f;
3711 }
3712 }
3713
3714 mOrientedRanges.haveDistance = true;
3715
3716 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3717 mOrientedRanges.distance.source = mSource;
3718 mOrientedRanges.distance.min =
3719 mRawPointerAxes.distance.minValue * mDistanceScale;
3720 mOrientedRanges.distance.max =
3721 mRawPointerAxes.distance.maxValue * mDistanceScale;
3722 mOrientedRanges.distance.flat = 0;
3723 mOrientedRanges.distance.fuzz =
3724 mRawPointerAxes.distance.fuzz * mDistanceScale;
3725 mOrientedRanges.distance.resolution = 0;
3726 }
3727
3728 // Compute oriented precision, scales and ranges.
3729 // Note that the maximum value reported is an inclusive maximum value so it is one
3730 // unit less than the total width or height of surface.
3731 switch (mSurfaceOrientation) {
3732 case DISPLAY_ORIENTATION_90:
3733 case DISPLAY_ORIENTATION_270:
3734 mOrientedXPrecision = mYPrecision;
3735 mOrientedYPrecision = mXPrecision;
3736
3737 mOrientedRanges.x.min = mYTranslate;
3738 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3739 mOrientedRanges.x.flat = 0;
3740 mOrientedRanges.x.fuzz = 0;
3741 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3742
3743 mOrientedRanges.y.min = mXTranslate;
3744 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3745 mOrientedRanges.y.flat = 0;
3746 mOrientedRanges.y.fuzz = 0;
3747 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3748 break;
3749
3750 default:
3751 mOrientedXPrecision = mXPrecision;
3752 mOrientedYPrecision = mYPrecision;
3753
3754 mOrientedRanges.x.min = mXTranslate;
3755 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3756 mOrientedRanges.x.flat = 0;
3757 mOrientedRanges.x.fuzz = 0;
3758 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3759
3760 mOrientedRanges.y.min = mYTranslate;
3761 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3762 mOrientedRanges.y.flat = 0;
3763 mOrientedRanges.y.fuzz = 0;
3764 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3765 break;
3766 }
3767
Jason Gerecke71b16e82014-03-10 09:47:59 -07003768 // Location
3769 updateAffineTransformation();
3770
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 if (mDeviceMode == DEVICE_MODE_POINTER) {
3772 // Compute pointer gesture detection parameters.
3773 float rawDiagonal = hypotf(rawWidth, rawHeight);
3774 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3775
3776 // Scale movements such that one whole swipe of the touch pad covers a
3777 // given area relative to the diagonal size of the display when no acceleration
3778 // is applied.
3779 // Assume that the touch pad has a square aspect ratio such that movements in
3780 // X and Y of the same number of raw units cover the same physical distance.
3781 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3782 * displayDiagonal / rawDiagonal;
3783 mPointerYMovementScale = mPointerXMovementScale;
3784
3785 // Scale zooms to cover a smaller range of the display than movements do.
3786 // This value determines the area around the pointer that is affected by freeform
3787 // pointer gestures.
3788 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3789 * displayDiagonal / rawDiagonal;
3790 mPointerYZoomScale = mPointerXZoomScale;
3791
3792 // Max width between pointers to detect a swipe gesture is more than some fraction
3793 // of the diagonal axis of the touch pad. Touches that are wider than this are
3794 // translated into freeform gestures.
3795 mPointerGestureMaxSwipeWidth =
3796 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3797
3798 // Abort current pointer usages because the state has changed.
3799 abortPointerUsage(when, 0 /*policyFlags*/);
3800 }
3801
3802 // Inform the dispatcher about the changes.
3803 *outResetNeeded = true;
3804 bumpGeneration();
3805 }
3806}
3807
3808void TouchInputMapper::dumpSurface(String8& dump) {
3809 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3810 "logicalFrame=[%d, %d, %d, %d], "
3811 "physicalFrame=[%d, %d, %d, %d], "
3812 "deviceSize=[%d, %d]\n",
3813 mViewport.displayId, mViewport.orientation,
3814 mViewport.logicalLeft, mViewport.logicalTop,
3815 mViewport.logicalRight, mViewport.logicalBottom,
3816 mViewport.physicalLeft, mViewport.physicalTop,
3817 mViewport.physicalRight, mViewport.physicalBottom,
3818 mViewport.deviceWidth, mViewport.deviceHeight);
3819
3820 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3821 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3822 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3823 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3824 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3825}
3826
3827void TouchInputMapper::configureVirtualKeys() {
3828 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3829 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3830
3831 mVirtualKeys.clear();
3832
3833 if (virtualKeyDefinitions.size() == 0) {
3834 return;
3835 }
3836
3837 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3838
3839 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3840 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3841 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3842 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3843
3844 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3845 const VirtualKeyDefinition& virtualKeyDefinition =
3846 virtualKeyDefinitions[i];
3847
3848 mVirtualKeys.add();
3849 VirtualKey& virtualKey = mVirtualKeys.editTop();
3850
3851 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3852 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003853 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003855 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3856 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3858 virtualKey.scanCode);
3859 mVirtualKeys.pop(); // drop the key
3860 continue;
3861 }
3862
3863 virtualKey.keyCode = keyCode;
3864 virtualKey.flags = flags;
3865
3866 // convert the key definition's display coordinates into touch coordinates for a hit box
3867 int32_t halfWidth = virtualKeyDefinition.width / 2;
3868 int32_t halfHeight = virtualKeyDefinition.height / 2;
3869
3870 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3871 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3872 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3873 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3874 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3875 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3876 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3877 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3878 }
3879}
3880
3881void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3882 if (!mVirtualKeys.isEmpty()) {
3883 dump.append(INDENT3 "Virtual Keys:\n");
3884
3885 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3886 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003887 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3889 i, virtualKey.scanCode, virtualKey.keyCode,
3890 virtualKey.hitLeft, virtualKey.hitRight,
3891 virtualKey.hitTop, virtualKey.hitBottom);
3892 }
3893 }
3894}
3895
3896void TouchInputMapper::parseCalibration() {
3897 const PropertyMap& in = getDevice()->getConfiguration();
3898 Calibration& out = mCalibration;
3899
3900 // Size
3901 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3902 String8 sizeCalibrationString;
3903 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3904 if (sizeCalibrationString == "none") {
3905 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3906 } else if (sizeCalibrationString == "geometric") {
3907 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3908 } else if (sizeCalibrationString == "diameter") {
3909 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3910 } else if (sizeCalibrationString == "box") {
3911 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3912 } else if (sizeCalibrationString == "area") {
3913 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3914 } else if (sizeCalibrationString != "default") {
3915 ALOGW("Invalid value for touch.size.calibration: '%s'",
3916 sizeCalibrationString.string());
3917 }
3918 }
3919
3920 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3921 out.sizeScale);
3922 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3923 out.sizeBias);
3924 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3925 out.sizeIsSummed);
3926
3927 // Pressure
3928 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3929 String8 pressureCalibrationString;
3930 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3931 if (pressureCalibrationString == "none") {
3932 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3933 } else if (pressureCalibrationString == "physical") {
3934 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3935 } else if (pressureCalibrationString == "amplitude") {
3936 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3937 } else if (pressureCalibrationString != "default") {
3938 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3939 pressureCalibrationString.string());
3940 }
3941 }
3942
3943 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3944 out.pressureScale);
3945
3946 // Orientation
3947 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3948 String8 orientationCalibrationString;
3949 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3950 if (orientationCalibrationString == "none") {
3951 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3952 } else if (orientationCalibrationString == "interpolated") {
3953 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3954 } else if (orientationCalibrationString == "vector") {
3955 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3956 } else if (orientationCalibrationString != "default") {
3957 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3958 orientationCalibrationString.string());
3959 }
3960 }
3961
3962 // Distance
3963 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3964 String8 distanceCalibrationString;
3965 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3966 if (distanceCalibrationString == "none") {
3967 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3968 } else if (distanceCalibrationString == "scaled") {
3969 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3970 } else if (distanceCalibrationString != "default") {
3971 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3972 distanceCalibrationString.string());
3973 }
3974 }
3975
3976 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3977 out.distanceScale);
3978
3979 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3980 String8 coverageCalibrationString;
3981 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3982 if (coverageCalibrationString == "none") {
3983 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3984 } else if (coverageCalibrationString == "box") {
3985 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3986 } else if (coverageCalibrationString != "default") {
3987 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3988 coverageCalibrationString.string());
3989 }
3990 }
3991}
3992
3993void TouchInputMapper::resolveCalibration() {
3994 // Size
3995 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3996 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3997 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3998 }
3999 } else {
4000 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4001 }
4002
4003 // Pressure
4004 if (mRawPointerAxes.pressure.valid) {
4005 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4006 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4007 }
4008 } else {
4009 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4010 }
4011
4012 // Orientation
4013 if (mRawPointerAxes.orientation.valid) {
4014 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4015 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4016 }
4017 } else {
4018 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4019 }
4020
4021 // Distance
4022 if (mRawPointerAxes.distance.valid) {
4023 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4024 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4025 }
4026 } else {
4027 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4028 }
4029
4030 // Coverage
4031 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4032 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4033 }
4034}
4035
4036void TouchInputMapper::dumpCalibration(String8& dump) {
4037 dump.append(INDENT3 "Calibration:\n");
4038
4039 // Size
4040 switch (mCalibration.sizeCalibration) {
4041 case Calibration::SIZE_CALIBRATION_NONE:
4042 dump.append(INDENT4 "touch.size.calibration: none\n");
4043 break;
4044 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4045 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4046 break;
4047 case Calibration::SIZE_CALIBRATION_DIAMETER:
4048 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4049 break;
4050 case Calibration::SIZE_CALIBRATION_BOX:
4051 dump.append(INDENT4 "touch.size.calibration: box\n");
4052 break;
4053 case Calibration::SIZE_CALIBRATION_AREA:
4054 dump.append(INDENT4 "touch.size.calibration: area\n");
4055 break;
4056 default:
4057 ALOG_ASSERT(false);
4058 }
4059
4060 if (mCalibration.haveSizeScale) {
4061 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4062 mCalibration.sizeScale);
4063 }
4064
4065 if (mCalibration.haveSizeBias) {
4066 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4067 mCalibration.sizeBias);
4068 }
4069
4070 if (mCalibration.haveSizeIsSummed) {
4071 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4072 toString(mCalibration.sizeIsSummed));
4073 }
4074
4075 // Pressure
4076 switch (mCalibration.pressureCalibration) {
4077 case Calibration::PRESSURE_CALIBRATION_NONE:
4078 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4079 break;
4080 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4081 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4082 break;
4083 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4084 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4085 break;
4086 default:
4087 ALOG_ASSERT(false);
4088 }
4089
4090 if (mCalibration.havePressureScale) {
4091 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4092 mCalibration.pressureScale);
4093 }
4094
4095 // Orientation
4096 switch (mCalibration.orientationCalibration) {
4097 case Calibration::ORIENTATION_CALIBRATION_NONE:
4098 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4099 break;
4100 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4101 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4102 break;
4103 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4104 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4105 break;
4106 default:
4107 ALOG_ASSERT(false);
4108 }
4109
4110 // Distance
4111 switch (mCalibration.distanceCalibration) {
4112 case Calibration::DISTANCE_CALIBRATION_NONE:
4113 dump.append(INDENT4 "touch.distance.calibration: none\n");
4114 break;
4115 case Calibration::DISTANCE_CALIBRATION_SCALED:
4116 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4117 break;
4118 default:
4119 ALOG_ASSERT(false);
4120 }
4121
4122 if (mCalibration.haveDistanceScale) {
4123 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4124 mCalibration.distanceScale);
4125 }
4126
4127 switch (mCalibration.coverageCalibration) {
4128 case Calibration::COVERAGE_CALIBRATION_NONE:
4129 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4130 break;
4131 case Calibration::COVERAGE_CALIBRATION_BOX:
4132 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4133 break;
4134 default:
4135 ALOG_ASSERT(false);
4136 }
4137}
4138
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004139void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4140 dump.append(INDENT3 "Affine Transformation:\n");
4141
4142 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4143 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4144 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4145 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4146 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4147 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4148}
4149
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004150void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004151 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4152 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004153}
4154
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155void TouchInputMapper::reset(nsecs_t when) {
4156 mCursorButtonAccumulator.reset(getDevice());
4157 mCursorScrollAccumulator.reset(getDevice());
4158 mTouchButtonAccumulator.reset(getDevice());
4159
4160 mPointerVelocityControl.reset();
4161 mWheelXVelocityControl.reset();
4162 mWheelYVelocityControl.reset();
4163
Michael Wright842500e2015-03-13 17:32:02 -07004164 mRawStatesPending.clear();
4165 mCurrentRawState.clear();
4166 mCurrentCookedState.clear();
4167 mLastRawState.clear();
4168 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 mPointerUsage = POINTER_USAGE_NONE;
4170 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004171 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004172 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 mDownTime = 0;
4174
4175 mCurrentVirtualKey.down = false;
4176
4177 mPointerGesture.reset();
4178 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004179 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
4181 if (mPointerController != NULL) {
4182 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4183 mPointerController->clearSpots();
4184 }
4185
4186 InputMapper::reset(when);
4187}
4188
Michael Wright842500e2015-03-13 17:32:02 -07004189void TouchInputMapper::resetExternalStylus() {
4190 mExternalStylusState.clear();
4191 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004192 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004193 mExternalStylusDataPending = false;
4194}
4195
Michael Wright43fd19f2015-04-21 19:02:58 +01004196void TouchInputMapper::clearStylusDataPendingFlags() {
4197 mExternalStylusDataPending = false;
4198 mExternalStylusFusionTimeout = LLONG_MAX;
4199}
4200
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201void TouchInputMapper::process(const RawEvent* rawEvent) {
4202 mCursorButtonAccumulator.process(rawEvent);
4203 mCursorScrollAccumulator.process(rawEvent);
4204 mTouchButtonAccumulator.process(rawEvent);
4205
4206 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4207 sync(rawEvent->when);
4208 }
4209}
4210
4211void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004212 const RawState* last = mRawStatesPending.isEmpty() ?
4213 &mCurrentRawState : &mRawStatesPending.top();
4214
4215 // Push a new state.
4216 mRawStatesPending.push();
4217 RawState* next = &mRawStatesPending.editTop();
4218 next->clear();
4219 next->when = when;
4220
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004222 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 | mCursorButtonAccumulator.getButtonState();
4224
Michael Wright842500e2015-03-13 17:32:02 -07004225 // Sync scroll
4226 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4227 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 mCursorScrollAccumulator.finishSync();
4229
Michael Wright842500e2015-03-13 17:32:02 -07004230 // Sync touch
4231 syncTouch(when, next);
4232
4233 // Assign pointer ids.
4234 if (!mHavePointerIds) {
4235 assignPointerIds(last, next);
4236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237
4238#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004239 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4240 "hovering ids 0x%08x -> 0x%08x",
4241 last->rawPointerData.pointerCount,
4242 next->rawPointerData.pointerCount,
4243 last->rawPointerData.touchingIdBits.value,
4244 next->rawPointerData.touchingIdBits.value,
4245 last->rawPointerData.hoveringIdBits.value,
4246 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247#endif
4248
Michael Wright842500e2015-03-13 17:32:02 -07004249 processRawTouches(false /*timeout*/);
4250}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
Michael Wright842500e2015-03-13 17:32:02 -07004252void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4254 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004255 mCurrentRawState.clear();
4256 mRawStatesPending.clear();
4257 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
Michael Wright842500e2015-03-13 17:32:02 -07004260 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4261 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4262 // touching the current state will only observe the events that have been dispatched to the
4263 // rest of the pipeline.
4264 const size_t N = mRawStatesPending.size();
4265 size_t count;
4266 for(count = 0; count < N; count++) {
4267 const RawState& next = mRawStatesPending[count];
4268
4269 // A failure to assign the stylus id means that we're waiting on stylus data
4270 // and so should defer the rest of the pipeline.
4271 if (assignExternalStylusId(next, timeout)) {
4272 break;
4273 }
4274
4275 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004276 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004277 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004278 if (mCurrentRawState.when < mLastRawState.when) {
4279 mCurrentRawState.when = mLastRawState.when;
4280 }
Michael Wright842500e2015-03-13 17:32:02 -07004281 cookAndDispatch(mCurrentRawState.when);
4282 }
4283 if (count != 0) {
4284 mRawStatesPending.removeItemsAt(0, count);
4285 }
4286
Michael Wright842500e2015-03-13 17:32:02 -07004287 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004288 if (timeout) {
4289 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4290 clearStylusDataPendingFlags();
4291 mCurrentRawState.copyFrom(mLastRawState);
4292#if DEBUG_STYLUS_FUSION
4293 ALOGD("Timeout expired, synthesizing event with new stylus data");
4294#endif
4295 cookAndDispatch(when);
4296 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4297 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4298 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4299 }
Michael Wright842500e2015-03-13 17:32:02 -07004300 }
4301}
4302
4303void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4304 // Always start with a clean state.
4305 mCurrentCookedState.clear();
4306
4307 // Apply stylus buttons to current raw state.
4308 applyExternalStylusButtonState(when);
4309
4310 // Handle policy on initial down or hover events.
4311 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4312 && mCurrentRawState.rawPointerData.pointerCount != 0;
4313
4314 uint32_t policyFlags = 0;
4315 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4316 if (initialDown || buttonsPressed) {
4317 // If this is a touch screen, hide the pointer on an initial down.
4318 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4319 getContext()->fadePointer();
4320 }
4321
4322 if (mParameters.wake) {
4323 policyFlags |= POLICY_FLAG_WAKE;
4324 }
4325 }
4326
4327 // Consume raw off-screen touches before cooking pointer data.
4328 // If touches are consumed, subsequent code will not receive any pointer data.
4329 if (consumeRawTouches(when, policyFlags)) {
4330 mCurrentRawState.rawPointerData.clear();
4331 }
4332
4333 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4334 // with cooked pointer data that has the same ids and indices as the raw data.
4335 // The following code can use either the raw or cooked data, as needed.
4336 cookPointerData();
4337
4338 // Apply stylus pressure to current cooked state.
4339 applyExternalStylusTouchState(when);
4340
4341 // Synthesize key down from raw buttons if needed.
4342 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004343 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004344
4345 // Dispatch the touches either directly or by translation through a pointer on screen.
4346 if (mDeviceMode == DEVICE_MODE_POINTER) {
4347 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4348 !idBits.isEmpty(); ) {
4349 uint32_t id = idBits.clearFirstMarkedBit();
4350 const RawPointerData::Pointer& pointer =
4351 mCurrentRawState.rawPointerData.pointerForId(id);
4352 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4353 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4354 mCurrentCookedState.stylusIdBits.markBit(id);
4355 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4356 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4357 mCurrentCookedState.fingerIdBits.markBit(id);
4358 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4359 mCurrentCookedState.mouseIdBits.markBit(id);
4360 }
4361 }
4362 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4363 !idBits.isEmpty(); ) {
4364 uint32_t id = idBits.clearFirstMarkedBit();
4365 const RawPointerData::Pointer& pointer =
4366 mCurrentRawState.rawPointerData.pointerForId(id);
4367 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4368 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4369 mCurrentCookedState.stylusIdBits.markBit(id);
4370 }
4371 }
4372
4373 // Stylus takes precedence over all tools, then mouse, then finger.
4374 PointerUsage pointerUsage = mPointerUsage;
4375 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4376 mCurrentCookedState.mouseIdBits.clear();
4377 mCurrentCookedState.fingerIdBits.clear();
4378 pointerUsage = POINTER_USAGE_STYLUS;
4379 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4380 mCurrentCookedState.fingerIdBits.clear();
4381 pointerUsage = POINTER_USAGE_MOUSE;
4382 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4383 isPointerDown(mCurrentRawState.buttonState)) {
4384 pointerUsage = POINTER_USAGE_GESTURES;
4385 }
4386
4387 dispatchPointerUsage(when, policyFlags, pointerUsage);
4388 } else {
4389 if (mDeviceMode == DEVICE_MODE_DIRECT
4390 && mConfig.showTouches && mPointerController != NULL) {
4391 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4392 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4393
4394 mPointerController->setButtonState(mCurrentRawState.buttonState);
4395 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4396 mCurrentCookedState.cookedPointerData.idToIndex,
4397 mCurrentCookedState.cookedPointerData.touchingIdBits);
4398 }
4399
Michael Wright8e812822015-06-22 16:18:21 +01004400 if (!mCurrentMotionAborted) {
4401 dispatchButtonRelease(when, policyFlags);
4402 dispatchHoverExit(when, policyFlags);
4403 dispatchTouches(when, policyFlags);
4404 dispatchHoverEnterAndMove(when, policyFlags);
4405 dispatchButtonPress(when, policyFlags);
4406 }
4407
4408 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4409 mCurrentMotionAborted = false;
4410 }
Michael Wright842500e2015-03-13 17:32:02 -07004411 }
4412
4413 // Synthesize key up from raw buttons if needed.
4414 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004415 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416
4417 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004418 mCurrentRawState.rawVScroll = 0;
4419 mCurrentRawState.rawHScroll = 0;
4420
4421 // Copy current touch to last touch in preparation for the next cycle.
4422 mLastRawState.copyFrom(mCurrentRawState);
4423 mLastCookedState.copyFrom(mCurrentCookedState);
4424}
4425
4426void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004427 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004428 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4429 }
4430}
4431
4432void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004433 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4434 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004435
Michael Wright53dca3a2015-04-23 17:39:53 +01004436 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4437 float pressure = mExternalStylusState.pressure;
4438 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4439 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4440 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4441 }
4442 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4443 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4444
4445 PointerProperties& properties =
4446 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004447 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4448 properties.toolType = mExternalStylusState.toolType;
4449 }
4450 }
4451}
4452
4453bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4454 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4455 return false;
4456 }
4457
4458 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4459 && state.rawPointerData.pointerCount != 0;
4460 if (initialDown) {
4461 if (mExternalStylusState.pressure != 0.0f) {
4462#if DEBUG_STYLUS_FUSION
4463 ALOGD("Have both stylus and touch data, beginning fusion");
4464#endif
4465 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4466 } else if (timeout) {
4467#if DEBUG_STYLUS_FUSION
4468 ALOGD("Timeout expired, assuming touch is not a stylus.");
4469#endif
4470 resetExternalStylus();
4471 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004472 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4473 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004474 }
4475#if DEBUG_STYLUS_FUSION
4476 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004477 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004478#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004479 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004480 return true;
4481 }
4482 }
4483
4484 // Check if the stylus pointer has gone up.
4485 if (mExternalStylusId != -1 &&
4486 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4487#if DEBUG_STYLUS_FUSION
4488 ALOGD("Stylus pointer is going up");
4489#endif
4490 mExternalStylusId = -1;
4491 }
4492
4493 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494}
4495
4496void TouchInputMapper::timeoutExpired(nsecs_t when) {
4497 if (mDeviceMode == DEVICE_MODE_POINTER) {
4498 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4499 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4500 }
Michael Wright842500e2015-03-13 17:32:02 -07004501 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004502 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004503 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004504 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4505 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004506 }
4507 }
4508}
4509
4510void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004511 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004512 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004513 // We're either in the middle of a fused stream of data or we're waiting on data before
4514 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4515 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004516 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004517 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
4519}
4520
4521bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4522 // Check for release of a virtual key.
4523 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004524 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 // Pointer went up while virtual key was down.
4526 mCurrentVirtualKey.down = false;
4527 if (!mCurrentVirtualKey.ignored) {
4528#if DEBUG_VIRTUAL_KEYS
4529 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4530 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4531#endif
4532 dispatchVirtualKey(when, policyFlags,
4533 AKEY_EVENT_ACTION_UP,
4534 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4535 }
4536 return true;
4537 }
4538
Michael Wright842500e2015-03-13 17:32:02 -07004539 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4540 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4541 const RawPointerData::Pointer& pointer =
4542 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4544 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4545 // Pointer is still within the space of the virtual key.
4546 return true;
4547 }
4548 }
4549
4550 // Pointer left virtual key area or another pointer also went down.
4551 // Send key cancellation but do not consume the touch yet.
4552 // This is useful when the user swipes through from the virtual key area
4553 // into the main display surface.
4554 mCurrentVirtualKey.down = false;
4555 if (!mCurrentVirtualKey.ignored) {
4556#if DEBUG_VIRTUAL_KEYS
4557 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4558 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4559#endif
4560 dispatchVirtualKey(when, policyFlags,
4561 AKEY_EVENT_ACTION_UP,
4562 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4563 | AKEY_EVENT_FLAG_CANCELED);
4564 }
4565 }
4566
Michael Wright842500e2015-03-13 17:32:02 -07004567 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4568 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004570 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4571 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4573 // If exactly one pointer went down, check for virtual key hit.
4574 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004575 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4577 if (virtualKey) {
4578 mCurrentVirtualKey.down = true;
4579 mCurrentVirtualKey.downTime = when;
4580 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4581 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4582 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4583 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4584
4585 if (!mCurrentVirtualKey.ignored) {
4586#if DEBUG_VIRTUAL_KEYS
4587 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4588 mCurrentVirtualKey.keyCode,
4589 mCurrentVirtualKey.scanCode);
4590#endif
4591 dispatchVirtualKey(when, policyFlags,
4592 AKEY_EVENT_ACTION_DOWN,
4593 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4594 }
4595 }
4596 }
4597 return true;
4598 }
4599 }
4600
4601 // Disable all virtual key touches that happen within a short time interval of the
4602 // most recent touch within the screen area. The idea is to filter out stray
4603 // virtual key presses when interacting with the touch screen.
4604 //
4605 // Problems we're trying to solve:
4606 //
4607 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4608 // virtual key area that is implemented by a separate touch panel and accidentally
4609 // triggers a virtual key.
4610 //
4611 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4612 // area and accidentally triggers a virtual key. This often happens when virtual keys
4613 // are layed out below the screen near to where the on screen keyboard's space bar
4614 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004615 if (mConfig.virtualKeyQuietTime > 0 &&
4616 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4618 }
4619 return false;
4620}
4621
4622void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4623 int32_t keyEventAction, int32_t keyEventFlags) {
4624 int32_t keyCode = mCurrentVirtualKey.keyCode;
4625 int32_t scanCode = mCurrentVirtualKey.scanCode;
4626 nsecs_t downTime = mCurrentVirtualKey.downTime;
4627 int32_t metaState = mContext->getGlobalMetaState();
4628 policyFlags |= POLICY_FLAG_VIRTUAL;
4629
4630 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4631 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4632 getListener()->notifyKey(&args);
4633}
4634
Michael Wright8e812822015-06-22 16:18:21 +01004635void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4636 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4637 if (!currentIdBits.isEmpty()) {
4638 int32_t metaState = getContext()->getGlobalMetaState();
4639 int32_t buttonState = mCurrentCookedState.buttonState;
4640 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4641 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4642 mCurrentCookedState.cookedPointerData.pointerProperties,
4643 mCurrentCookedState.cookedPointerData.pointerCoords,
4644 mCurrentCookedState.cookedPointerData.idToIndex,
4645 currentIdBits, -1,
4646 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4647 mCurrentMotionAborted = true;
4648 }
4649}
4650
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004652 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4653 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004655 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
4657 if (currentIdBits == lastIdBits) {
4658 if (!currentIdBits.isEmpty()) {
4659 // No pointer id changes so this is a move event.
4660 // The listener takes care of batching moves so we don't have to deal with that here.
4661 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004662 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004664 mCurrentCookedState.cookedPointerData.pointerProperties,
4665 mCurrentCookedState.cookedPointerData.pointerCoords,
4666 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 currentIdBits, -1,
4668 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4669 }
4670 } else {
4671 // There may be pointers going up and pointers going down and pointers moving
4672 // all at the same time.
4673 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4674 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4675 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4676 BitSet32 dispatchedIdBits(lastIdBits.value);
4677
4678 // Update last coordinates of pointers that have moved so that we observe the new
4679 // pointer positions at the same time as other pointers that have just gone up.
4680 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004681 mCurrentCookedState.cookedPointerData.pointerProperties,
4682 mCurrentCookedState.cookedPointerData.pointerCoords,
4683 mCurrentCookedState.cookedPointerData.idToIndex,
4684 mLastCookedState.cookedPointerData.pointerProperties,
4685 mLastCookedState.cookedPointerData.pointerCoords,
4686 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004688 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 moveNeeded = true;
4690 }
4691
4692 // Dispatch pointer up events.
4693 while (!upIdBits.isEmpty()) {
4694 uint32_t upId = upIdBits.clearFirstMarkedBit();
4695
4696 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004697 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004698 mLastCookedState.cookedPointerData.pointerProperties,
4699 mLastCookedState.cookedPointerData.pointerCoords,
4700 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004701 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 dispatchedIdBits.clearBit(upId);
4703 }
4704
4705 // Dispatch move events if any of the remaining pointers moved from their old locations.
4706 // Although applications receive new locations as part of individual pointer up
4707 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004708 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4710 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004711 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004712 mCurrentCookedState.cookedPointerData.pointerProperties,
4713 mCurrentCookedState.cookedPointerData.pointerCoords,
4714 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004715 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 }
4717
4718 // Dispatch pointer down events using the new pointer locations.
4719 while (!downIdBits.isEmpty()) {
4720 uint32_t downId = downIdBits.clearFirstMarkedBit();
4721 dispatchedIdBits.markBit(downId);
4722
4723 if (dispatchedIdBits.count() == 1) {
4724 // First pointer is going down. Set down time.
4725 mDownTime = when;
4726 }
4727
4728 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004729 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004730 mCurrentCookedState.cookedPointerData.pointerProperties,
4731 mCurrentCookedState.cookedPointerData.pointerCoords,
4732 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004733 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 }
4735 }
4736}
4737
4738void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4739 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004740 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4741 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 int32_t metaState = getContext()->getGlobalMetaState();
4743 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004744 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004745 mLastCookedState.cookedPointerData.pointerProperties,
4746 mLastCookedState.cookedPointerData.pointerCoords,
4747 mLastCookedState.cookedPointerData.idToIndex,
4748 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4750 mSentHoverEnter = false;
4751 }
4752}
4753
4754void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004755 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4756 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 int32_t metaState = getContext()->getGlobalMetaState();
4758 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004759 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004760 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004761 mCurrentCookedState.cookedPointerData.pointerProperties,
4762 mCurrentCookedState.cookedPointerData.pointerCoords,
4763 mCurrentCookedState.cookedPointerData.idToIndex,
4764 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4766 mSentHoverEnter = true;
4767 }
4768
4769 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004770 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004771 mCurrentRawState.buttonState, 0,
4772 mCurrentCookedState.cookedPointerData.pointerProperties,
4773 mCurrentCookedState.cookedPointerData.pointerCoords,
4774 mCurrentCookedState.cookedPointerData.idToIndex,
4775 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4777 }
4778}
4779
Michael Wright7b159c92015-05-14 14:48:03 +01004780void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4781 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4782 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4783 const int32_t metaState = getContext()->getGlobalMetaState();
4784 int32_t buttonState = mLastCookedState.buttonState;
4785 while (!releasedButtons.isEmpty()) {
4786 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4787 buttonState &= ~actionButton;
4788 dispatchMotion(when, policyFlags, mSource,
4789 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4790 0, metaState, buttonState, 0,
4791 mCurrentCookedState.cookedPointerData.pointerProperties,
4792 mCurrentCookedState.cookedPointerData.pointerCoords,
4793 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4794 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4795 }
4796}
4797
4798void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4799 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4800 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4801 const int32_t metaState = getContext()->getGlobalMetaState();
4802 int32_t buttonState = mLastCookedState.buttonState;
4803 while (!pressedButtons.isEmpty()) {
4804 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4805 buttonState |= actionButton;
4806 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4807 0, metaState, buttonState, 0,
4808 mCurrentCookedState.cookedPointerData.pointerProperties,
4809 mCurrentCookedState.cookedPointerData.pointerCoords,
4810 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4811 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4812 }
4813}
4814
4815const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4816 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4817 return cookedPointerData.touchingIdBits;
4818 }
4819 return cookedPointerData.hoveringIdBits;
4820}
4821
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004823 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824
Michael Wright842500e2015-03-13 17:32:02 -07004825 mCurrentCookedState.cookedPointerData.clear();
4826 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4827 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4828 mCurrentRawState.rawPointerData.hoveringIdBits;
4829 mCurrentCookedState.cookedPointerData.touchingIdBits =
4830 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831
Michael Wright7b159c92015-05-14 14:48:03 +01004832 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4833 mCurrentCookedState.buttonState = 0;
4834 } else {
4835 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4836 }
4837
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 // Walk through the the active pointers and map device coordinates onto
4839 // surface coordinates and adjust for display orientation.
4840 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004841 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842
4843 // Size
4844 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4845 switch (mCalibration.sizeCalibration) {
4846 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4847 case Calibration::SIZE_CALIBRATION_DIAMETER:
4848 case Calibration::SIZE_CALIBRATION_BOX:
4849 case Calibration::SIZE_CALIBRATION_AREA:
4850 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4851 touchMajor = in.touchMajor;
4852 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4853 toolMajor = in.toolMajor;
4854 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4855 size = mRawPointerAxes.touchMinor.valid
4856 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4857 } else if (mRawPointerAxes.touchMajor.valid) {
4858 toolMajor = touchMajor = in.touchMajor;
4859 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4860 ? in.touchMinor : in.touchMajor;
4861 size = mRawPointerAxes.touchMinor.valid
4862 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4863 } else if (mRawPointerAxes.toolMajor.valid) {
4864 touchMajor = toolMajor = in.toolMajor;
4865 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4866 ? in.toolMinor : in.toolMajor;
4867 size = mRawPointerAxes.toolMinor.valid
4868 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4869 } else {
4870 ALOG_ASSERT(false, "No touch or tool axes. "
4871 "Size calibration should have been resolved to NONE.");
4872 touchMajor = 0;
4873 touchMinor = 0;
4874 toolMajor = 0;
4875 toolMinor = 0;
4876 size = 0;
4877 }
4878
4879 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004880 uint32_t touchingCount =
4881 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 if (touchingCount > 1) {
4883 touchMajor /= touchingCount;
4884 touchMinor /= touchingCount;
4885 toolMajor /= touchingCount;
4886 toolMinor /= touchingCount;
4887 size /= touchingCount;
4888 }
4889 }
4890
4891 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4892 touchMajor *= mGeometricScale;
4893 touchMinor *= mGeometricScale;
4894 toolMajor *= mGeometricScale;
4895 toolMinor *= mGeometricScale;
4896 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4897 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4898 touchMinor = touchMajor;
4899 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4900 toolMinor = toolMajor;
4901 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4902 touchMinor = touchMajor;
4903 toolMinor = toolMajor;
4904 }
4905
4906 mCalibration.applySizeScaleAndBias(&touchMajor);
4907 mCalibration.applySizeScaleAndBias(&touchMinor);
4908 mCalibration.applySizeScaleAndBias(&toolMajor);
4909 mCalibration.applySizeScaleAndBias(&toolMinor);
4910 size *= mSizeScale;
4911 break;
4912 default:
4913 touchMajor = 0;
4914 touchMinor = 0;
4915 toolMajor = 0;
4916 toolMinor = 0;
4917 size = 0;
4918 break;
4919 }
4920
4921 // Pressure
4922 float pressure;
4923 switch (mCalibration.pressureCalibration) {
4924 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4925 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4926 pressure = in.pressure * mPressureScale;
4927 break;
4928 default:
4929 pressure = in.isHovering ? 0 : 1;
4930 break;
4931 }
4932
4933 // Tilt and Orientation
4934 float tilt;
4935 float orientation;
4936 if (mHaveTilt) {
4937 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4938 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4939 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4940 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4941 } else {
4942 tilt = 0;
4943
4944 switch (mCalibration.orientationCalibration) {
4945 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4946 orientation = in.orientation * mOrientationScale;
4947 break;
4948 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4949 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4950 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4951 if (c1 != 0 || c2 != 0) {
4952 orientation = atan2f(c1, c2) * 0.5f;
4953 float confidence = hypotf(c1, c2);
4954 float scale = 1.0f + confidence / 16.0f;
4955 touchMajor *= scale;
4956 touchMinor /= scale;
4957 toolMajor *= scale;
4958 toolMinor /= scale;
4959 } else {
4960 orientation = 0;
4961 }
4962 break;
4963 }
4964 default:
4965 orientation = 0;
4966 }
4967 }
4968
4969 // Distance
4970 float distance;
4971 switch (mCalibration.distanceCalibration) {
4972 case Calibration::DISTANCE_CALIBRATION_SCALED:
4973 distance = in.distance * mDistanceScale;
4974 break;
4975 default:
4976 distance = 0;
4977 }
4978
4979 // Coverage
4980 int32_t rawLeft, rawTop, rawRight, rawBottom;
4981 switch (mCalibration.coverageCalibration) {
4982 case Calibration::COVERAGE_CALIBRATION_BOX:
4983 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4984 rawRight = in.toolMinor & 0x0000ffff;
4985 rawBottom = in.toolMajor & 0x0000ffff;
4986 rawTop = (in.toolMajor & 0xffff0000) >> 16;
4987 break;
4988 default:
4989 rawLeft = rawTop = rawRight = rawBottom = 0;
4990 break;
4991 }
4992
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004993 // Adjust X,Y coords for device calibration
4994 // TODO: Adjust coverage coords?
4995 float xTransformed = in.x, yTransformed = in.y;
4996 mAffineTransform.applyTo(xTransformed, yTransformed);
4997
4998 // Adjust X, Y, and coverage coords for surface orientation.
4999 float x, y;
5000 float left, top, right, bottom;
5001
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 switch (mSurfaceOrientation) {
5003 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005004 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5005 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5007 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5008 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5009 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5010 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005011 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005012 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5013 }
5014 break;
5015 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005016 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5017 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5019 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5020 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5021 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5022 orientation -= M_PI;
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_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005028 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5029 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5031 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5032 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5033 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5034 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005035 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5037 }
5038 break;
5039 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005040 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5041 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5043 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5044 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5045 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5046 break;
5047 }
5048
5049 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005050 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 out.clear();
5052 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5053 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5054 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5055 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5056 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5057 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5058 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5059 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5060 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5061 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5062 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5063 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5064 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5065 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5066 } else {
5067 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5068 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5069 }
5070
5071 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005072 PointerProperties& properties =
5073 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 uint32_t id = in.id;
5075 properties.clear();
5076 properties.id = id;
5077 properties.toolType = in.toolType;
5078
5079 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005080 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 }
5082}
5083
5084void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5085 PointerUsage pointerUsage) {
5086 if (pointerUsage != mPointerUsage) {
5087 abortPointerUsage(when, policyFlags);
5088 mPointerUsage = pointerUsage;
5089 }
5090
5091 switch (mPointerUsage) {
5092 case POINTER_USAGE_GESTURES:
5093 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5094 break;
5095 case POINTER_USAGE_STYLUS:
5096 dispatchPointerStylus(when, policyFlags);
5097 break;
5098 case POINTER_USAGE_MOUSE:
5099 dispatchPointerMouse(when, policyFlags);
5100 break;
5101 default:
5102 break;
5103 }
5104}
5105
5106void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5107 switch (mPointerUsage) {
5108 case POINTER_USAGE_GESTURES:
5109 abortPointerGestures(when, policyFlags);
5110 break;
5111 case POINTER_USAGE_STYLUS:
5112 abortPointerStylus(when, policyFlags);
5113 break;
5114 case POINTER_USAGE_MOUSE:
5115 abortPointerMouse(when, policyFlags);
5116 break;
5117 default:
5118 break;
5119 }
5120
5121 mPointerUsage = POINTER_USAGE_NONE;
5122}
5123
5124void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5125 bool isTimeout) {
5126 // Update current gesture coordinates.
5127 bool cancelPreviousGesture, finishPreviousGesture;
5128 bool sendEvents = preparePointerGestures(when,
5129 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5130 if (!sendEvents) {
5131 return;
5132 }
5133 if (finishPreviousGesture) {
5134 cancelPreviousGesture = false;
5135 }
5136
5137 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005138 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5139 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 if (finishPreviousGesture || cancelPreviousGesture) {
5141 mPointerController->clearSpots();
5142 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005143
5144 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5145 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5146 mPointerGesture.currentGestureIdToIndex,
5147 mPointerGesture.currentGestureIdBits);
5148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 } else {
5150 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5151 }
5152
5153 // Show or hide the pointer if needed.
5154 switch (mPointerGesture.currentGestureMode) {
5155 case PointerGesture::NEUTRAL:
5156 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005157 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5158 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 // Remind the user of where the pointer is after finishing a gesture with spots.
5160 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5161 }
5162 break;
5163 case PointerGesture::TAP:
5164 case PointerGesture::TAP_DRAG:
5165 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5166 case PointerGesture::HOVER:
5167 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005168 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 // Unfade the pointer when the current gesture manipulates the
5170 // area directly under the pointer.
5171 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5172 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 case PointerGesture::FREEFORM:
5174 // Fade the pointer when the current gesture manipulates a different
5175 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005176 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5178 } else {
5179 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5180 }
5181 break;
5182 }
5183
5184 // Send events!
5185 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005186 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187
5188 // Update last coordinates of pointers that have moved so that we observe the new
5189 // pointer positions at the same time as other pointers that have just gone up.
5190 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5191 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5192 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5193 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5194 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5195 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5196 bool moveNeeded = false;
5197 if (down && !cancelPreviousGesture && !finishPreviousGesture
5198 && !mPointerGesture.lastGestureIdBits.isEmpty()
5199 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5200 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5201 & mPointerGesture.lastGestureIdBits.value);
5202 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5203 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5204 mPointerGesture.lastGestureProperties,
5205 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5206 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005207 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208 moveNeeded = true;
5209 }
5210 }
5211
5212 // Send motion events for all pointers that went up or were canceled.
5213 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5214 if (!dispatchedGestureIdBits.isEmpty()) {
5215 if (cancelPreviousGesture) {
5216 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005217 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005218 AMOTION_EVENT_EDGE_FLAG_NONE,
5219 mPointerGesture.lastGestureProperties,
5220 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005221 dispatchedGestureIdBits, -1, 0,
5222 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223
5224 dispatchedGestureIdBits.clear();
5225 } else {
5226 BitSet32 upGestureIdBits;
5227 if (finishPreviousGesture) {
5228 upGestureIdBits = dispatchedGestureIdBits;
5229 } else {
5230 upGestureIdBits.value = dispatchedGestureIdBits.value
5231 & ~mPointerGesture.currentGestureIdBits.value;
5232 }
5233 while (!upGestureIdBits.isEmpty()) {
5234 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5235
5236 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005237 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5239 mPointerGesture.lastGestureProperties,
5240 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5241 dispatchedGestureIdBits, id,
5242 0, 0, mPointerGesture.downTime);
5243
5244 dispatchedGestureIdBits.clearBit(id);
5245 }
5246 }
5247 }
5248
5249 // Send motion events for all pointers that moved.
5250 if (moveNeeded) {
5251 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005252 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5253 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254 mPointerGesture.currentGestureProperties,
5255 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5256 dispatchedGestureIdBits, -1,
5257 0, 0, mPointerGesture.downTime);
5258 }
5259
5260 // Send motion events for all pointers that went down.
5261 if (down) {
5262 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5263 & ~dispatchedGestureIdBits.value);
5264 while (!downGestureIdBits.isEmpty()) {
5265 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5266 dispatchedGestureIdBits.markBit(id);
5267
5268 if (dispatchedGestureIdBits.count() == 1) {
5269 mPointerGesture.downTime = when;
5270 }
5271
5272 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005273 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 mPointerGesture.currentGestureProperties,
5275 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5276 dispatchedGestureIdBits, id,
5277 0, 0, mPointerGesture.downTime);
5278 }
5279 }
5280
5281 // Send motion events for hover.
5282 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5283 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005284 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5286 mPointerGesture.currentGestureProperties,
5287 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5288 mPointerGesture.currentGestureIdBits, -1,
5289 0, 0, mPointerGesture.downTime);
5290 } else if (dispatchedGestureIdBits.isEmpty()
5291 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5292 // Synthesize a hover move event after all pointers go up to indicate that
5293 // the pointer is hovering again even if the user is not currently touching
5294 // the touch pad. This ensures that a view will receive a fresh hover enter
5295 // event after a tap.
5296 float x, y;
5297 mPointerController->getPosition(&x, &y);
5298
5299 PointerProperties pointerProperties;
5300 pointerProperties.clear();
5301 pointerProperties.id = 0;
5302 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5303
5304 PointerCoords pointerCoords;
5305 pointerCoords.clear();
5306 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5307 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5308
5309 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005310 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5312 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5313 0, 0, mPointerGesture.downTime);
5314 getListener()->notifyMotion(&args);
5315 }
5316
5317 // Update state.
5318 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5319 if (!down) {
5320 mPointerGesture.lastGestureIdBits.clear();
5321 } else {
5322 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5323 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5324 uint32_t id = idBits.clearFirstMarkedBit();
5325 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5326 mPointerGesture.lastGestureProperties[index].copyFrom(
5327 mPointerGesture.currentGestureProperties[index]);
5328 mPointerGesture.lastGestureCoords[index].copyFrom(
5329 mPointerGesture.currentGestureCoords[index]);
5330 mPointerGesture.lastGestureIdToIndex[id] = index;
5331 }
5332 }
5333}
5334
5335void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5336 // Cancel previously dispatches pointers.
5337 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5338 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005339 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005341 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 AMOTION_EVENT_EDGE_FLAG_NONE,
5343 mPointerGesture.lastGestureProperties,
5344 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5345 mPointerGesture.lastGestureIdBits, -1,
5346 0, 0, mPointerGesture.downTime);
5347 }
5348
5349 // Reset the current pointer gesture.
5350 mPointerGesture.reset();
5351 mPointerVelocityControl.reset();
5352
5353 // Remove any current spots.
5354 if (mPointerController != NULL) {
5355 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5356 mPointerController->clearSpots();
5357 }
5358}
5359
5360bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5361 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5362 *outCancelPreviousGesture = false;
5363 *outFinishPreviousGesture = false;
5364
5365 // Handle TAP timeout.
5366 if (isTimeout) {
5367#if DEBUG_GESTURES
5368 ALOGD("Gestures: Processing timeout");
5369#endif
5370
5371 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5372 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5373 // The tap/drag timeout has not yet expired.
5374 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5375 + mConfig.pointerGestureTapDragInterval);
5376 } else {
5377 // The tap is finished.
5378#if DEBUG_GESTURES
5379 ALOGD("Gestures: TAP finished");
5380#endif
5381 *outFinishPreviousGesture = true;
5382
5383 mPointerGesture.activeGestureId = -1;
5384 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5385 mPointerGesture.currentGestureIdBits.clear();
5386
5387 mPointerVelocityControl.reset();
5388 return true;
5389 }
5390 }
5391
5392 // We did not handle this timeout.
5393 return false;
5394 }
5395
Michael Wright842500e2015-03-13 17:32:02 -07005396 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5397 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398
5399 // Update the velocity tracker.
5400 {
5401 VelocityTracker::Position positions[MAX_POINTERS];
5402 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005403 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005405 const RawPointerData::Pointer& pointer =
5406 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 positions[count].x = pointer.x * mPointerXMovementScale;
5408 positions[count].y = pointer.y * mPointerYMovementScale;
5409 }
5410 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005411 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 }
5413
5414 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5415 // to NEUTRAL, then we should not generate tap event.
5416 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5417 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5418 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5419 mPointerGesture.resetTap();
5420 }
5421
5422 // Pick a new active touch id if needed.
5423 // Choose an arbitrary pointer that just went down, if there is one.
5424 // Otherwise choose an arbitrary remaining pointer.
5425 // This guarantees we always have an active touch id when there is at least one pointer.
5426 // We keep the same active touch id for as long as possible.
5427 bool activeTouchChanged = false;
5428 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5429 int32_t activeTouchId = lastActiveTouchId;
5430 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005431 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 activeTouchChanged = true;
5433 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005434 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 mPointerGesture.firstTouchTime = when;
5436 }
Michael Wright842500e2015-03-13 17:32:02 -07005437 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005439 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005441 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 } else {
5443 activeTouchId = mPointerGesture.activeTouchId = -1;
5444 }
5445 }
5446
5447 // Determine whether we are in quiet time.
5448 bool isQuietTime = false;
5449 if (activeTouchId < 0) {
5450 mPointerGesture.resetQuietTime();
5451 } else {
5452 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5453 if (!isQuietTime) {
5454 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5455 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5456 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5457 && currentFingerCount < 2) {
5458 // Enter quiet time when exiting swipe or freeform state.
5459 // This is to prevent accidentally entering the hover state and flinging the
5460 // pointer when finishing a swipe and there is still one pointer left onscreen.
5461 isQuietTime = true;
5462 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5463 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005464 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 // Enter quiet time when releasing the button and there are still two or more
5466 // fingers down. This may indicate that one finger was used to press the button
5467 // but it has not gone up yet.
5468 isQuietTime = true;
5469 }
5470 if (isQuietTime) {
5471 mPointerGesture.quietTime = when;
5472 }
5473 }
5474 }
5475
5476 // Switch states based on button and pointer state.
5477 if (isQuietTime) {
5478 // Case 1: Quiet time. (QUIET)
5479#if DEBUG_GESTURES
5480 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5481 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5482#endif
5483 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5484 *outFinishPreviousGesture = true;
5485 }
5486
5487 mPointerGesture.activeGestureId = -1;
5488 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5489 mPointerGesture.currentGestureIdBits.clear();
5490
5491 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005492 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5494 // The pointer follows the active touch point.
5495 // Emit DOWN, MOVE, UP events at the pointer location.
5496 //
5497 // Only the active touch matters; other fingers are ignored. This policy helps
5498 // to handle the case where the user places a second finger on the touch pad
5499 // to apply the necessary force to depress an integrated button below the surface.
5500 // We don't want the second finger to be delivered to applications.
5501 //
5502 // For this to work well, we need to make sure to track the pointer that is really
5503 // active. If the user first puts one finger down to click then adds another
5504 // finger to drag then the active pointer should switch to the finger that is
5505 // being dragged.
5506#if DEBUG_GESTURES
5507 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5508 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5509#endif
5510 // Reset state when just starting.
5511 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5512 *outFinishPreviousGesture = true;
5513 mPointerGesture.activeGestureId = 0;
5514 }
5515
5516 // Switch pointers if needed.
5517 // Find the fastest pointer and follow it.
5518 if (activeTouchId >= 0 && currentFingerCount > 1) {
5519 int32_t bestId = -1;
5520 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005521 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 uint32_t id = idBits.clearFirstMarkedBit();
5523 float vx, vy;
5524 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5525 float speed = hypotf(vx, vy);
5526 if (speed > bestSpeed) {
5527 bestId = id;
5528 bestSpeed = speed;
5529 }
5530 }
5531 }
5532 if (bestId >= 0 && bestId != activeTouchId) {
5533 mPointerGesture.activeTouchId = activeTouchId = bestId;
5534 activeTouchChanged = true;
5535#if DEBUG_GESTURES
5536 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5537 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5538#endif
5539 }
5540 }
5541
Jun Mukaifa1706a2015-12-03 01:14:46 -08005542 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005543 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005545 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005547 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005548 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5549 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550
5551 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5552 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5553
5554 // Move the pointer using a relative motion.
5555 // When using spots, the click will occur at the position of the anchor
5556 // spot and all other spots will move there.
5557 mPointerController->move(deltaX, deltaY);
5558 } else {
5559 mPointerVelocityControl.reset();
5560 }
5561
5562 float x, y;
5563 mPointerController->getPosition(&x, &y);
5564
5565 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5566 mPointerGesture.currentGestureIdBits.clear();
5567 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5568 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5569 mPointerGesture.currentGestureProperties[0].clear();
5570 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5571 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5572 mPointerGesture.currentGestureCoords[0].clear();
5573 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5574 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5575 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5576 } else if (currentFingerCount == 0) {
5577 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5578 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5579 *outFinishPreviousGesture = true;
5580 }
5581
5582 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5583 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5584 bool tapped = false;
5585 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5586 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5587 && lastFingerCount == 1) {
5588 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5589 float x, y;
5590 mPointerController->getPosition(&x, &y);
5591 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5592 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5593#if DEBUG_GESTURES
5594 ALOGD("Gestures: TAP");
5595#endif
5596
5597 mPointerGesture.tapUpTime = when;
5598 getContext()->requestTimeoutAtTime(when
5599 + mConfig.pointerGestureTapDragInterval);
5600
5601 mPointerGesture.activeGestureId = 0;
5602 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5603 mPointerGesture.currentGestureIdBits.clear();
5604 mPointerGesture.currentGestureIdBits.markBit(
5605 mPointerGesture.activeGestureId);
5606 mPointerGesture.currentGestureIdToIndex[
5607 mPointerGesture.activeGestureId] = 0;
5608 mPointerGesture.currentGestureProperties[0].clear();
5609 mPointerGesture.currentGestureProperties[0].id =
5610 mPointerGesture.activeGestureId;
5611 mPointerGesture.currentGestureProperties[0].toolType =
5612 AMOTION_EVENT_TOOL_TYPE_FINGER;
5613 mPointerGesture.currentGestureCoords[0].clear();
5614 mPointerGesture.currentGestureCoords[0].setAxisValue(
5615 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5616 mPointerGesture.currentGestureCoords[0].setAxisValue(
5617 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5618 mPointerGesture.currentGestureCoords[0].setAxisValue(
5619 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5620
5621 tapped = true;
5622 } else {
5623#if DEBUG_GESTURES
5624 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5625 x - mPointerGesture.tapX,
5626 y - mPointerGesture.tapY);
5627#endif
5628 }
5629 } else {
5630#if DEBUG_GESTURES
5631 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5632 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5633 (when - mPointerGesture.tapDownTime) * 0.000001f);
5634 } else {
5635 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5636 }
5637#endif
5638 }
5639 }
5640
5641 mPointerVelocityControl.reset();
5642
5643 if (!tapped) {
5644#if DEBUG_GESTURES
5645 ALOGD("Gestures: NEUTRAL");
5646#endif
5647 mPointerGesture.activeGestureId = -1;
5648 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5649 mPointerGesture.currentGestureIdBits.clear();
5650 }
5651 } else if (currentFingerCount == 1) {
5652 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5653 // The pointer follows the active touch point.
5654 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5655 // When in TAP_DRAG, emit MOVE events at the pointer location.
5656 ALOG_ASSERT(activeTouchId >= 0);
5657
5658 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5659 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5660 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5661 float x, y;
5662 mPointerController->getPosition(&x, &y);
5663 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5664 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5665 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5666 } else {
5667#if DEBUG_GESTURES
5668 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5669 x - mPointerGesture.tapX,
5670 y - mPointerGesture.tapY);
5671#endif
5672 }
5673 } else {
5674#if DEBUG_GESTURES
5675 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5676 (when - mPointerGesture.tapUpTime) * 0.000001f);
5677#endif
5678 }
5679 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5680 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5681 }
5682
Jun Mukaifa1706a2015-12-03 01:14:46 -08005683 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005684 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005686 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005688 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005689 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5690 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691
5692 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5693 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5694
5695 // Move the pointer using a relative motion.
5696 // When using spots, the hover or drag will occur at the position of the anchor spot.
5697 mPointerController->move(deltaX, deltaY);
5698 } else {
5699 mPointerVelocityControl.reset();
5700 }
5701
5702 bool down;
5703 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5704#if DEBUG_GESTURES
5705 ALOGD("Gestures: TAP_DRAG");
5706#endif
5707 down = true;
5708 } else {
5709#if DEBUG_GESTURES
5710 ALOGD("Gestures: HOVER");
5711#endif
5712 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5713 *outFinishPreviousGesture = true;
5714 }
5715 mPointerGesture.activeGestureId = 0;
5716 down = false;
5717 }
5718
5719 float x, y;
5720 mPointerController->getPosition(&x, &y);
5721
5722 mPointerGesture.currentGestureIdBits.clear();
5723 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5724 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5725 mPointerGesture.currentGestureProperties[0].clear();
5726 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5727 mPointerGesture.currentGestureProperties[0].toolType =
5728 AMOTION_EVENT_TOOL_TYPE_FINGER;
5729 mPointerGesture.currentGestureCoords[0].clear();
5730 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5731 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5732 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5733 down ? 1.0f : 0.0f);
5734
5735 if (lastFingerCount == 0 && currentFingerCount != 0) {
5736 mPointerGesture.resetTap();
5737 mPointerGesture.tapDownTime = when;
5738 mPointerGesture.tapX = x;
5739 mPointerGesture.tapY = y;
5740 }
5741 } else {
5742 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5743 // We need to provide feedback for each finger that goes down so we cannot wait
5744 // for the fingers to move before deciding what to do.
5745 //
5746 // The ambiguous case is deciding what to do when there are two fingers down but they
5747 // have not moved enough to determine whether they are part of a drag or part of a
5748 // freeform gesture, or just a press or long-press at the pointer location.
5749 //
5750 // When there are two fingers we start with the PRESS hypothesis and we generate a
5751 // down at the pointer location.
5752 //
5753 // When the two fingers move enough or when additional fingers are added, we make
5754 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5755 ALOG_ASSERT(activeTouchId >= 0);
5756
5757 bool settled = when >= mPointerGesture.firstTouchTime
5758 + mConfig.pointerGestureMultitouchSettleInterval;
5759 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5760 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5761 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5762 *outFinishPreviousGesture = true;
5763 } else if (!settled && currentFingerCount > lastFingerCount) {
5764 // Additional pointers have gone down but not yet settled.
5765 // Reset the gesture.
5766#if DEBUG_GESTURES
5767 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5768 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5769 + mConfig.pointerGestureMultitouchSettleInterval - when)
5770 * 0.000001f);
5771#endif
5772 *outCancelPreviousGesture = true;
5773 } else {
5774 // Continue previous gesture.
5775 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5776 }
5777
5778 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5779 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5780 mPointerGesture.activeGestureId = 0;
5781 mPointerGesture.referenceIdBits.clear();
5782 mPointerVelocityControl.reset();
5783
5784 // Use the centroid and pointer location as the reference points for the gesture.
5785#if DEBUG_GESTURES
5786 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5787 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5788 + mConfig.pointerGestureMultitouchSettleInterval - when)
5789 * 0.000001f);
5790#endif
Michael Wright842500e2015-03-13 17:32:02 -07005791 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 &mPointerGesture.referenceTouchX,
5793 &mPointerGesture.referenceTouchY);
5794 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5795 &mPointerGesture.referenceGestureY);
5796 }
5797
5798 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005799 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5801 uint32_t id = idBits.clearFirstMarkedBit();
5802 mPointerGesture.referenceDeltas[id].dx = 0;
5803 mPointerGesture.referenceDeltas[id].dy = 0;
5804 }
Michael Wright842500e2015-03-13 17:32:02 -07005805 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806
5807 // Add delta for all fingers and calculate a common movement delta.
5808 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005809 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5810 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5812 bool first = (idBits == commonIdBits);
5813 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005814 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5815 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5817 delta.dx += cpd.x - lpd.x;
5818 delta.dy += cpd.y - lpd.y;
5819
5820 if (first) {
5821 commonDeltaX = delta.dx;
5822 commonDeltaY = delta.dy;
5823 } else {
5824 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5825 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5826 }
5827 }
5828
5829 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5830 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5831 float dist[MAX_POINTER_ID + 1];
5832 int32_t distOverThreshold = 0;
5833 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5834 uint32_t id = idBits.clearFirstMarkedBit();
5835 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5836 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5837 delta.dy * mPointerYZoomScale);
5838 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5839 distOverThreshold += 1;
5840 }
5841 }
5842
5843 // Only transition when at least two pointers have moved further than
5844 // the minimum distance threshold.
5845 if (distOverThreshold >= 2) {
5846 if (currentFingerCount > 2) {
5847 // There are more than two pointers, switch to FREEFORM.
5848#if DEBUG_GESTURES
5849 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5850 currentFingerCount);
5851#endif
5852 *outCancelPreviousGesture = true;
5853 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5854 } else {
5855 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005856 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857 uint32_t id1 = idBits.clearFirstMarkedBit();
5858 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005859 const RawPointerData::Pointer& p1 =
5860 mCurrentRawState.rawPointerData.pointerForId(id1);
5861 const RawPointerData::Pointer& p2 =
5862 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5864 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5865 // There are two pointers but they are too far apart for a SWIPE,
5866 // switch to FREEFORM.
5867#if DEBUG_GESTURES
5868 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5869 mutualDistance, mPointerGestureMaxSwipeWidth);
5870#endif
5871 *outCancelPreviousGesture = true;
5872 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5873 } else {
5874 // There are two pointers. Wait for both pointers to start moving
5875 // before deciding whether this is a SWIPE or FREEFORM gesture.
5876 float dist1 = dist[id1];
5877 float dist2 = dist[id2];
5878 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5879 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5880 // Calculate the dot product of the displacement vectors.
5881 // When the vectors are oriented in approximately the same direction,
5882 // the angle betweeen them is near zero and the cosine of the angle
5883 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5884 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5885 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5886 float dx1 = delta1.dx * mPointerXZoomScale;
5887 float dy1 = delta1.dy * mPointerYZoomScale;
5888 float dx2 = delta2.dx * mPointerXZoomScale;
5889 float dy2 = delta2.dy * mPointerYZoomScale;
5890 float dot = dx1 * dx2 + dy1 * dy2;
5891 float cosine = dot / (dist1 * dist2); // denominator always > 0
5892 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5893 // Pointers are moving in the same direction. Switch to SWIPE.
5894#if DEBUG_GESTURES
5895 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5896 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5897 "cosine %0.3f >= %0.3f",
5898 dist1, mConfig.pointerGestureMultitouchMinDistance,
5899 dist2, mConfig.pointerGestureMultitouchMinDistance,
5900 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5901#endif
5902 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5903 } else {
5904 // Pointers are moving in different directions. Switch to FREEFORM.
5905#if DEBUG_GESTURES
5906 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5907 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5908 "cosine %0.3f < %0.3f",
5909 dist1, mConfig.pointerGestureMultitouchMinDistance,
5910 dist2, mConfig.pointerGestureMultitouchMinDistance,
5911 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5912#endif
5913 *outCancelPreviousGesture = true;
5914 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5915 }
5916 }
5917 }
5918 }
5919 }
5920 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5921 // Switch from SWIPE to FREEFORM if additional pointers go down.
5922 // Cancel previous gesture.
5923 if (currentFingerCount > 2) {
5924#if DEBUG_GESTURES
5925 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5926 currentFingerCount);
5927#endif
5928 *outCancelPreviousGesture = true;
5929 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5930 }
5931 }
5932
5933 // Move the reference points based on the overall group motion of the fingers
5934 // except in PRESS mode while waiting for a transition to occur.
5935 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5936 && (commonDeltaX || commonDeltaY)) {
5937 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5938 uint32_t id = idBits.clearFirstMarkedBit();
5939 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5940 delta.dx = 0;
5941 delta.dy = 0;
5942 }
5943
5944 mPointerGesture.referenceTouchX += commonDeltaX;
5945 mPointerGesture.referenceTouchY += commonDeltaY;
5946
5947 commonDeltaX *= mPointerXMovementScale;
5948 commonDeltaY *= mPointerYMovementScale;
5949
5950 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5951 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5952
5953 mPointerGesture.referenceGestureX += commonDeltaX;
5954 mPointerGesture.referenceGestureY += commonDeltaY;
5955 }
5956
5957 // Report gestures.
5958 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5959 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5960 // PRESS or SWIPE mode.
5961#if DEBUG_GESTURES
5962 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5963 "activeGestureId=%d, currentTouchPointerCount=%d",
5964 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5965#endif
5966 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5967
5968 mPointerGesture.currentGestureIdBits.clear();
5969 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5970 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5971 mPointerGesture.currentGestureProperties[0].clear();
5972 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5973 mPointerGesture.currentGestureProperties[0].toolType =
5974 AMOTION_EVENT_TOOL_TYPE_FINGER;
5975 mPointerGesture.currentGestureCoords[0].clear();
5976 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5977 mPointerGesture.referenceGestureX);
5978 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5979 mPointerGesture.referenceGestureY);
5980 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5981 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5982 // FREEFORM mode.
5983#if DEBUG_GESTURES
5984 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5985 "activeGestureId=%d, currentTouchPointerCount=%d",
5986 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5987#endif
5988 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5989
5990 mPointerGesture.currentGestureIdBits.clear();
5991
5992 BitSet32 mappedTouchIdBits;
5993 BitSet32 usedGestureIdBits;
5994 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5995 // Initially, assign the active gesture id to the active touch point
5996 // if there is one. No other touch id bits are mapped yet.
5997 if (!*outCancelPreviousGesture) {
5998 mappedTouchIdBits.markBit(activeTouchId);
5999 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6000 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6001 mPointerGesture.activeGestureId;
6002 } else {
6003 mPointerGesture.activeGestureId = -1;
6004 }
6005 } else {
6006 // Otherwise, assume we mapped all touches from the previous frame.
6007 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006008 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6009 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6011
6012 // Check whether we need to choose a new active gesture id because the
6013 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006014 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6015 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 !upTouchIdBits.isEmpty(); ) {
6017 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6018 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6019 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6020 mPointerGesture.activeGestureId = -1;
6021 break;
6022 }
6023 }
6024 }
6025
6026#if DEBUG_GESTURES
6027 ALOGD("Gestures: FREEFORM follow up "
6028 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6029 "activeGestureId=%d",
6030 mappedTouchIdBits.value, usedGestureIdBits.value,
6031 mPointerGesture.activeGestureId);
6032#endif
6033
Michael Wright842500e2015-03-13 17:32:02 -07006034 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035 for (uint32_t i = 0; i < currentFingerCount; i++) {
6036 uint32_t touchId = idBits.clearFirstMarkedBit();
6037 uint32_t gestureId;
6038 if (!mappedTouchIdBits.hasBit(touchId)) {
6039 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6040 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6041#if DEBUG_GESTURES
6042 ALOGD("Gestures: FREEFORM "
6043 "new mapping for touch id %d -> gesture id %d",
6044 touchId, gestureId);
6045#endif
6046 } else {
6047 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6048#if DEBUG_GESTURES
6049 ALOGD("Gestures: FREEFORM "
6050 "existing mapping for touch id %d -> gesture id %d",
6051 touchId, gestureId);
6052#endif
6053 }
6054 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6055 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6056
6057 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006058 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6060 * mPointerXZoomScale;
6061 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6062 * mPointerYZoomScale;
6063 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6064
6065 mPointerGesture.currentGestureProperties[i].clear();
6066 mPointerGesture.currentGestureProperties[i].id = gestureId;
6067 mPointerGesture.currentGestureProperties[i].toolType =
6068 AMOTION_EVENT_TOOL_TYPE_FINGER;
6069 mPointerGesture.currentGestureCoords[i].clear();
6070 mPointerGesture.currentGestureCoords[i].setAxisValue(
6071 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6072 mPointerGesture.currentGestureCoords[i].setAxisValue(
6073 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6074 mPointerGesture.currentGestureCoords[i].setAxisValue(
6075 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6076 }
6077
6078 if (mPointerGesture.activeGestureId < 0) {
6079 mPointerGesture.activeGestureId =
6080 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6081#if DEBUG_GESTURES
6082 ALOGD("Gestures: FREEFORM new "
6083 "activeGestureId=%d", mPointerGesture.activeGestureId);
6084#endif
6085 }
6086 }
6087 }
6088
Michael Wright842500e2015-03-13 17:32:02 -07006089 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090
6091#if DEBUG_GESTURES
6092 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6093 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6094 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6095 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6096 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6097 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6098 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6099 uint32_t id = idBits.clearFirstMarkedBit();
6100 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6101 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6102 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6103 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6104 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6105 id, index, properties.toolType,
6106 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6107 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6108 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6109 }
6110 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6111 uint32_t id = idBits.clearFirstMarkedBit();
6112 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6113 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6114 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6115 ALOGD(" lastGesture[%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#endif
6123 return true;
6124}
6125
6126void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6127 mPointerSimple.currentCoords.clear();
6128 mPointerSimple.currentProperties.clear();
6129
6130 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006131 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6132 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6133 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6134 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6135 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136 mPointerController->setPosition(x, y);
6137
Michael Wright842500e2015-03-13 17:32:02 -07006138 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006139 down = !hovering;
6140
6141 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006142 mPointerSimple.currentCoords.copyFrom(
6143 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006144 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6145 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6146 mPointerSimple.currentProperties.id = 0;
6147 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006148 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006149 } else {
6150 down = false;
6151 hovering = false;
6152 }
6153
6154 dispatchPointerSimple(when, policyFlags, down, hovering);
6155}
6156
6157void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6158 abortPointerSimple(when, policyFlags);
6159}
6160
6161void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6162 mPointerSimple.currentCoords.clear();
6163 mPointerSimple.currentProperties.clear();
6164
6165 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006166 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6167 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6168 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006169 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006170 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6171 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006172 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006173 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006174 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006175 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006176 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006177 * mPointerYMovementScale;
6178
6179 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6180 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6181
6182 mPointerController->move(deltaX, deltaY);
6183 } else {
6184 mPointerVelocityControl.reset();
6185 }
6186
Michael Wright842500e2015-03-13 17:32:02 -07006187 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188 hovering = !down;
6189
6190 float x, y;
6191 mPointerController->getPosition(&x, &y);
6192 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006193 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6195 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6196 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6197 hovering ? 0.0f : 1.0f);
6198 mPointerSimple.currentProperties.id = 0;
6199 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006200 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006201 } else {
6202 mPointerVelocityControl.reset();
6203
6204 down = false;
6205 hovering = false;
6206 }
6207
6208 dispatchPointerSimple(when, policyFlags, down, hovering);
6209}
6210
6211void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6212 abortPointerSimple(when, policyFlags);
6213
6214 mPointerVelocityControl.reset();
6215}
6216
6217void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6218 bool down, bool hovering) {
6219 int32_t metaState = getContext()->getGlobalMetaState();
6220
6221 if (mPointerController != NULL) {
6222 if (down || hovering) {
6223 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6224 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006225 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6227 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6228 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6229 }
6230 }
6231
6232 if (mPointerSimple.down && !down) {
6233 mPointerSimple.down = false;
6234
6235 // Send up.
6236 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006237 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 mViewport.displayId,
6239 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6240 mOrientedXPrecision, mOrientedYPrecision,
6241 mPointerSimple.downTime);
6242 getListener()->notifyMotion(&args);
6243 }
6244
6245 if (mPointerSimple.hovering && !hovering) {
6246 mPointerSimple.hovering = false;
6247
6248 // Send hover exit.
6249 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006250 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 mViewport.displayId,
6252 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6253 mOrientedXPrecision, mOrientedYPrecision,
6254 mPointerSimple.downTime);
6255 getListener()->notifyMotion(&args);
6256 }
6257
6258 if (down) {
6259 if (!mPointerSimple.down) {
6260 mPointerSimple.down = true;
6261 mPointerSimple.downTime = when;
6262
6263 // Send down.
6264 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006265 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006266 mViewport.displayId,
6267 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6268 mOrientedXPrecision, mOrientedYPrecision,
6269 mPointerSimple.downTime);
6270 getListener()->notifyMotion(&args);
6271 }
6272
6273 // Send move.
6274 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006275 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276 mViewport.displayId,
6277 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6278 mOrientedXPrecision, mOrientedYPrecision,
6279 mPointerSimple.downTime);
6280 getListener()->notifyMotion(&args);
6281 }
6282
6283 if (hovering) {
6284 if (!mPointerSimple.hovering) {
6285 mPointerSimple.hovering = true;
6286
6287 // Send hover enter.
6288 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006289 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006290 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006291 mViewport.displayId,
6292 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6293 mOrientedXPrecision, mOrientedYPrecision,
6294 mPointerSimple.downTime);
6295 getListener()->notifyMotion(&args);
6296 }
6297
6298 // Send hover move.
6299 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006300 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006301 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006302 mViewport.displayId,
6303 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6304 mOrientedXPrecision, mOrientedYPrecision,
6305 mPointerSimple.downTime);
6306 getListener()->notifyMotion(&args);
6307 }
6308
Michael Wright842500e2015-03-13 17:32:02 -07006309 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6310 float vscroll = mCurrentRawState.rawVScroll;
6311 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312 mWheelYVelocityControl.move(when, NULL, &vscroll);
6313 mWheelXVelocityControl.move(when, &hscroll, NULL);
6314
6315 // Send scroll.
6316 PointerCoords pointerCoords;
6317 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6318 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6319 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6320
6321 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006322 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006323 mViewport.displayId,
6324 1, &mPointerSimple.currentProperties, &pointerCoords,
6325 mOrientedXPrecision, mOrientedYPrecision,
6326 mPointerSimple.downTime);
6327 getListener()->notifyMotion(&args);
6328 }
6329
6330 // Save state.
6331 if (down || hovering) {
6332 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6333 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6334 } else {
6335 mPointerSimple.reset();
6336 }
6337}
6338
6339void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6340 mPointerSimple.currentCoords.clear();
6341 mPointerSimple.currentProperties.clear();
6342
6343 dispatchPointerSimple(when, policyFlags, false, false);
6344}
6345
6346void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006347 int32_t action, int32_t actionButton, int32_t flags,
6348 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006350 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6351 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352 PointerCoords pointerCoords[MAX_POINTERS];
6353 PointerProperties pointerProperties[MAX_POINTERS];
6354 uint32_t pointerCount = 0;
6355 while (!idBits.isEmpty()) {
6356 uint32_t id = idBits.clearFirstMarkedBit();
6357 uint32_t index = idToIndex[id];
6358 pointerProperties[pointerCount].copyFrom(properties[index]);
6359 pointerCoords[pointerCount].copyFrom(coords[index]);
6360
6361 if (changedId >= 0 && id == uint32_t(changedId)) {
6362 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6363 }
6364
6365 pointerCount += 1;
6366 }
6367
6368 ALOG_ASSERT(pointerCount != 0);
6369
6370 if (changedId >= 0 && pointerCount == 1) {
6371 // Replace initial down and final up action.
6372 // We can compare the action without masking off the changed pointer index
6373 // because we know the index is 0.
6374 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6375 action = AMOTION_EVENT_ACTION_DOWN;
6376 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6377 action = AMOTION_EVENT_ACTION_UP;
6378 } else {
6379 // Can't happen.
6380 ALOG_ASSERT(false);
6381 }
6382 }
6383
6384 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006385 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6387 xPrecision, yPrecision, downTime);
6388 getListener()->notifyMotion(&args);
6389}
6390
6391bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6392 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6393 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6394 BitSet32 idBits) const {
6395 bool changed = false;
6396 while (!idBits.isEmpty()) {
6397 uint32_t id = idBits.clearFirstMarkedBit();
6398 uint32_t inIndex = inIdToIndex[id];
6399 uint32_t outIndex = outIdToIndex[id];
6400
6401 const PointerProperties& curInProperties = inProperties[inIndex];
6402 const PointerCoords& curInCoords = inCoords[inIndex];
6403 PointerProperties& curOutProperties = outProperties[outIndex];
6404 PointerCoords& curOutCoords = outCoords[outIndex];
6405
6406 if (curInProperties != curOutProperties) {
6407 curOutProperties.copyFrom(curInProperties);
6408 changed = true;
6409 }
6410
6411 if (curInCoords != curOutCoords) {
6412 curOutCoords.copyFrom(curInCoords);
6413 changed = true;
6414 }
6415 }
6416 return changed;
6417}
6418
6419void TouchInputMapper::fadePointer() {
6420 if (mPointerController != NULL) {
6421 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6422 }
6423}
6424
Jeff Brownc9aa6282015-02-11 19:03:28 -08006425void TouchInputMapper::cancelTouch(nsecs_t when) {
6426 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006427 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006428}
6429
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6431 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6432 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6433}
6434
6435const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6436 int32_t x, int32_t y) {
6437 size_t numVirtualKeys = mVirtualKeys.size();
6438 for (size_t i = 0; i < numVirtualKeys; i++) {
6439 const VirtualKey& virtualKey = mVirtualKeys[i];
6440
6441#if DEBUG_VIRTUAL_KEYS
6442 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6443 "left=%d, top=%d, right=%d, bottom=%d",
6444 x, y,
6445 virtualKey.keyCode, virtualKey.scanCode,
6446 virtualKey.hitLeft, virtualKey.hitTop,
6447 virtualKey.hitRight, virtualKey.hitBottom);
6448#endif
6449
6450 if (virtualKey.isHit(x, y)) {
6451 return & virtualKey;
6452 }
6453 }
6454
6455 return NULL;
6456}
6457
Michael Wright842500e2015-03-13 17:32:02 -07006458void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6459 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6460 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006461
Michael Wright842500e2015-03-13 17:32:02 -07006462 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006463
6464 if (currentPointerCount == 0) {
6465 // No pointers to assign.
6466 return;
6467 }
6468
6469 if (lastPointerCount == 0) {
6470 // All pointers are new.
6471 for (uint32_t i = 0; i < currentPointerCount; i++) {
6472 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006473 current->rawPointerData.pointers[i].id = id;
6474 current->rawPointerData.idToIndex[id] = i;
6475 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006476 }
6477 return;
6478 }
6479
6480 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006481 && current->rawPointerData.pointers[0].toolType
6482 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006483 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006484 uint32_t id = last->rawPointerData.pointers[0].id;
6485 current->rawPointerData.pointers[0].id = id;
6486 current->rawPointerData.idToIndex[id] = 0;
6487 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006488 return;
6489 }
6490
6491 // General case.
6492 // We build a heap of squared euclidean distances between current and last pointers
6493 // associated with the current and last pointer indices. Then, we find the best
6494 // match (by distance) for each current pointer.
6495 // The pointers must have the same tool type but it is possible for them to
6496 // transition from hovering to touching or vice-versa while retaining the same id.
6497 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6498
6499 uint32_t heapSize = 0;
6500 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6501 currentPointerIndex++) {
6502 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6503 lastPointerIndex++) {
6504 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006505 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006507 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006508 if (currentPointer.toolType == lastPointer.toolType) {
6509 int64_t deltaX = currentPointer.x - lastPointer.x;
6510 int64_t deltaY = currentPointer.y - lastPointer.y;
6511
6512 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6513
6514 // Insert new element into the heap (sift up).
6515 heap[heapSize].currentPointerIndex = currentPointerIndex;
6516 heap[heapSize].lastPointerIndex = lastPointerIndex;
6517 heap[heapSize].distance = distance;
6518 heapSize += 1;
6519 }
6520 }
6521 }
6522
6523 // Heapify
6524 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6525 startIndex -= 1;
6526 for (uint32_t parentIndex = startIndex; ;) {
6527 uint32_t childIndex = parentIndex * 2 + 1;
6528 if (childIndex >= heapSize) {
6529 break;
6530 }
6531
6532 if (childIndex + 1 < heapSize
6533 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6534 childIndex += 1;
6535 }
6536
6537 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6538 break;
6539 }
6540
6541 swap(heap[parentIndex], heap[childIndex]);
6542 parentIndex = childIndex;
6543 }
6544 }
6545
6546#if DEBUG_POINTER_ASSIGNMENT
6547 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6548 for (size_t i = 0; i < heapSize; i++) {
6549 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6550 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6551 heap[i].distance);
6552 }
6553#endif
6554
6555 // Pull matches out by increasing order of distance.
6556 // To avoid reassigning pointers that have already been matched, the loop keeps track
6557 // of which last and current pointers have been matched using the matchedXXXBits variables.
6558 // It also tracks the used pointer id bits.
6559 BitSet32 matchedLastBits(0);
6560 BitSet32 matchedCurrentBits(0);
6561 BitSet32 usedIdBits(0);
6562 bool first = true;
6563 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6564 while (heapSize > 0) {
6565 if (first) {
6566 // The first time through the loop, we just consume the root element of
6567 // the heap (the one with smallest distance).
6568 first = false;
6569 } else {
6570 // Previous iterations consumed the root element of the heap.
6571 // Pop root element off of the heap (sift down).
6572 heap[0] = heap[heapSize];
6573 for (uint32_t parentIndex = 0; ;) {
6574 uint32_t childIndex = parentIndex * 2 + 1;
6575 if (childIndex >= heapSize) {
6576 break;
6577 }
6578
6579 if (childIndex + 1 < heapSize
6580 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6581 childIndex += 1;
6582 }
6583
6584 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6585 break;
6586 }
6587
6588 swap(heap[parentIndex], heap[childIndex]);
6589 parentIndex = childIndex;
6590 }
6591
6592#if DEBUG_POINTER_ASSIGNMENT
6593 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6594 for (size_t i = 0; i < heapSize; i++) {
6595 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6596 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6597 heap[i].distance);
6598 }
6599#endif
6600 }
6601
6602 heapSize -= 1;
6603
6604 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6605 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6606
6607 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6608 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6609
6610 matchedCurrentBits.markBit(currentPointerIndex);
6611 matchedLastBits.markBit(lastPointerIndex);
6612
Michael Wright842500e2015-03-13 17:32:02 -07006613 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6614 current->rawPointerData.pointers[currentPointerIndex].id = id;
6615 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6616 current->rawPointerData.markIdBit(id,
6617 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006618 usedIdBits.markBit(id);
6619
6620#if DEBUG_POINTER_ASSIGNMENT
6621 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6622 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6623#endif
6624 break;
6625 }
6626 }
6627
6628 // Assign fresh ids to pointers that were not matched in the process.
6629 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6630 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6631 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6632
Michael Wright842500e2015-03-13 17:32:02 -07006633 current->rawPointerData.pointers[currentPointerIndex].id = id;
6634 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6635 current->rawPointerData.markIdBit(id,
6636 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006637
6638#if DEBUG_POINTER_ASSIGNMENT
6639 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6640 currentPointerIndex, id);
6641#endif
6642 }
6643}
6644
6645int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6646 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6647 return AKEY_STATE_VIRTUAL;
6648 }
6649
6650 size_t numVirtualKeys = mVirtualKeys.size();
6651 for (size_t i = 0; i < numVirtualKeys; i++) {
6652 const VirtualKey& virtualKey = mVirtualKeys[i];
6653 if (virtualKey.keyCode == keyCode) {
6654 return AKEY_STATE_UP;
6655 }
6656 }
6657
6658 return AKEY_STATE_UNKNOWN;
6659}
6660
6661int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6662 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6663 return AKEY_STATE_VIRTUAL;
6664 }
6665
6666 size_t numVirtualKeys = mVirtualKeys.size();
6667 for (size_t i = 0; i < numVirtualKeys; i++) {
6668 const VirtualKey& virtualKey = mVirtualKeys[i];
6669 if (virtualKey.scanCode == scanCode) {
6670 return AKEY_STATE_UP;
6671 }
6672 }
6673
6674 return AKEY_STATE_UNKNOWN;
6675}
6676
6677bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6678 const int32_t* keyCodes, uint8_t* outFlags) {
6679 size_t numVirtualKeys = mVirtualKeys.size();
6680 for (size_t i = 0; i < numVirtualKeys; i++) {
6681 const VirtualKey& virtualKey = mVirtualKeys[i];
6682
6683 for (size_t i = 0; i < numCodes; i++) {
6684 if (virtualKey.keyCode == keyCodes[i]) {
6685 outFlags[i] = 1;
6686 }
6687 }
6688 }
6689
6690 return true;
6691}
6692
6693
6694// --- SingleTouchInputMapper ---
6695
6696SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6697 TouchInputMapper(device) {
6698}
6699
6700SingleTouchInputMapper::~SingleTouchInputMapper() {
6701}
6702
6703void SingleTouchInputMapper::reset(nsecs_t when) {
6704 mSingleTouchMotionAccumulator.reset(getDevice());
6705
6706 TouchInputMapper::reset(when);
6707}
6708
6709void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6710 TouchInputMapper::process(rawEvent);
6711
6712 mSingleTouchMotionAccumulator.process(rawEvent);
6713}
6714
Michael Wright842500e2015-03-13 17:32:02 -07006715void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006716 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006717 outState->rawPointerData.pointerCount = 1;
6718 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006719
6720 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6721 && (mTouchButtonAccumulator.isHovering()
6722 || (mRawPointerAxes.pressure.valid
6723 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006724 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006725
Michael Wright842500e2015-03-13 17:32:02 -07006726 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006727 outPointer.id = 0;
6728 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6729 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6730 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6731 outPointer.touchMajor = 0;
6732 outPointer.touchMinor = 0;
6733 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6734 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6735 outPointer.orientation = 0;
6736 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6737 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6738 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6739 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6740 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6741 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6742 }
6743 outPointer.isHovering = isHovering;
6744 }
6745}
6746
6747void SingleTouchInputMapper::configureRawPointerAxes() {
6748 TouchInputMapper::configureRawPointerAxes();
6749
6750 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6751 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6752 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6753 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6754 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6755 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6756 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6757}
6758
6759bool SingleTouchInputMapper::hasStylus() const {
6760 return mTouchButtonAccumulator.hasStylus();
6761}
6762
6763
6764// --- MultiTouchInputMapper ---
6765
6766MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6767 TouchInputMapper(device) {
6768}
6769
6770MultiTouchInputMapper::~MultiTouchInputMapper() {
6771}
6772
6773void MultiTouchInputMapper::reset(nsecs_t when) {
6774 mMultiTouchMotionAccumulator.reset(getDevice());
6775
6776 mPointerIdBits.clear();
6777
6778 TouchInputMapper::reset(when);
6779}
6780
6781void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6782 TouchInputMapper::process(rawEvent);
6783
6784 mMultiTouchMotionAccumulator.process(rawEvent);
6785}
6786
Michael Wright842500e2015-03-13 17:32:02 -07006787void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006788 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6789 size_t outCount = 0;
6790 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006791 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006792
6793 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6794 const MultiTouchMotionAccumulator::Slot* inSlot =
6795 mMultiTouchMotionAccumulator.getSlot(inIndex);
6796 if (!inSlot->isInUse()) {
6797 continue;
6798 }
6799
6800 if (outCount >= MAX_POINTERS) {
6801#if DEBUG_POINTERS
6802 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6803 "ignoring the rest.",
6804 getDeviceName().string(), MAX_POINTERS);
6805#endif
6806 break; // too many fingers!
6807 }
6808
Michael Wright842500e2015-03-13 17:32:02 -07006809 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006810 outPointer.x = inSlot->getX();
6811 outPointer.y = inSlot->getY();
6812 outPointer.pressure = inSlot->getPressure();
6813 outPointer.touchMajor = inSlot->getTouchMajor();
6814 outPointer.touchMinor = inSlot->getTouchMinor();
6815 outPointer.toolMajor = inSlot->getToolMajor();
6816 outPointer.toolMinor = inSlot->getToolMinor();
6817 outPointer.orientation = inSlot->getOrientation();
6818 outPointer.distance = inSlot->getDistance();
6819 outPointer.tiltX = 0;
6820 outPointer.tiltY = 0;
6821
6822 outPointer.toolType = inSlot->getToolType();
6823 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6824 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6825 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6826 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6827 }
6828 }
6829
6830 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6831 && (mTouchButtonAccumulator.isHovering()
6832 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6833 outPointer.isHovering = isHovering;
6834
6835 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006836 if (mHavePointerIds) {
6837 int32_t trackingId = inSlot->getTrackingId();
6838 int32_t id = -1;
6839 if (trackingId >= 0) {
6840 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6841 uint32_t n = idBits.clearFirstMarkedBit();
6842 if (mPointerTrackingIdMap[n] == trackingId) {
6843 id = n;
6844 }
6845 }
6846
6847 if (id < 0 && !mPointerIdBits.isFull()) {
6848 id = mPointerIdBits.markFirstUnmarkedBit();
6849 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006850 }
Michael Wright842500e2015-03-13 17:32:02 -07006851 }
gaoshang1a632de2016-08-24 10:23:50 +08006852 if (id < 0) {
6853 mHavePointerIds = false;
6854 outState->rawPointerData.clearIdBits();
6855 newPointerIdBits.clear();
6856 } else {
6857 outPointer.id = id;
6858 outState->rawPointerData.idToIndex[id] = outCount;
6859 outState->rawPointerData.markIdBit(id, isHovering);
6860 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006861 }
Michael Wright842500e2015-03-13 17:32:02 -07006862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006863 outCount += 1;
6864 }
6865
Michael Wright842500e2015-03-13 17:32:02 -07006866 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006867 mPointerIdBits = newPointerIdBits;
6868
6869 mMultiTouchMotionAccumulator.finishSync();
6870}
6871
6872void MultiTouchInputMapper::configureRawPointerAxes() {
6873 TouchInputMapper::configureRawPointerAxes();
6874
6875 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6876 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6877 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6878 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6879 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6880 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6881 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6882 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6883 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6884 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6885 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6886
6887 if (mRawPointerAxes.trackingId.valid
6888 && mRawPointerAxes.slot.valid
6889 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6890 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6891 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006892 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6893 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006894 getDeviceName().string(), slotCount, MAX_SLOTS);
6895 slotCount = MAX_SLOTS;
6896 }
6897 mMultiTouchMotionAccumulator.configure(getDevice(),
6898 slotCount, true /*usingSlotsProtocol*/);
6899 } else {
6900 mMultiTouchMotionAccumulator.configure(getDevice(),
6901 MAX_POINTERS, false /*usingSlotsProtocol*/);
6902 }
6903}
6904
6905bool MultiTouchInputMapper::hasStylus() const {
6906 return mMultiTouchMotionAccumulator.hasStylus()
6907 || mTouchButtonAccumulator.hasStylus();
6908}
6909
Michael Wright842500e2015-03-13 17:32:02 -07006910// --- ExternalStylusInputMapper
6911
6912ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6913 InputMapper(device) {
6914
6915}
6916
6917uint32_t ExternalStylusInputMapper::getSources() {
6918 return AINPUT_SOURCE_STYLUS;
6919}
6920
6921void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6922 InputMapper::populateDeviceInfo(info);
6923 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6924 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6925}
6926
6927void ExternalStylusInputMapper::dump(String8& dump) {
6928 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6929 dump.append(INDENT3 "Raw Stylus Axes:\n");
6930 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6931 dump.append(INDENT3 "Stylus State:\n");
6932 dumpStylusState(dump, mStylusState);
6933}
6934
6935void ExternalStylusInputMapper::configure(nsecs_t when,
6936 const InputReaderConfiguration* config, uint32_t changes) {
6937 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6938 mTouchButtonAccumulator.configure(getDevice());
6939}
6940
6941void ExternalStylusInputMapper::reset(nsecs_t when) {
6942 InputDevice* device = getDevice();
6943 mSingleTouchMotionAccumulator.reset(device);
6944 mTouchButtonAccumulator.reset(device);
6945 InputMapper::reset(when);
6946}
6947
6948void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6949 mSingleTouchMotionAccumulator.process(rawEvent);
6950 mTouchButtonAccumulator.process(rawEvent);
6951
6952 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6953 sync(rawEvent->when);
6954 }
6955}
6956
6957void ExternalStylusInputMapper::sync(nsecs_t when) {
6958 mStylusState.clear();
6959
6960 mStylusState.when = when;
6961
Michael Wright45ccacf2015-04-21 19:01:58 +01006962 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6963 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6964 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6965 }
6966
Michael Wright842500e2015-03-13 17:32:02 -07006967 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6968 if (mRawPressureAxis.valid) {
6969 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6970 } else if (mTouchButtonAccumulator.isToolActive()) {
6971 mStylusState.pressure = 1.0f;
6972 } else {
6973 mStylusState.pressure = 0.0f;
6974 }
6975
6976 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07006977
6978 mContext->dispatchExternalStylusState(mStylusState);
6979}
6980
Michael Wrightd02c5b62014-02-10 15:10:22 -08006981
6982// --- JoystickInputMapper ---
6983
6984JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6985 InputMapper(device) {
6986}
6987
6988JoystickInputMapper::~JoystickInputMapper() {
6989}
6990
6991uint32_t JoystickInputMapper::getSources() {
6992 return AINPUT_SOURCE_JOYSTICK;
6993}
6994
6995void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6996 InputMapper::populateDeviceInfo(info);
6997
6998 for (size_t i = 0; i < mAxes.size(); i++) {
6999 const Axis& axis = mAxes.valueAt(i);
7000 addMotionRange(axis.axisInfo.axis, axis, info);
7001
7002 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7003 addMotionRange(axis.axisInfo.highAxis, axis, info);
7004
7005 }
7006 }
7007}
7008
7009void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7010 InputDeviceInfo* info) {
7011 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7012 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7013 /* In order to ease the transition for developers from using the old axes
7014 * to the newer, more semantically correct axes, we'll continue to register
7015 * the old axes as duplicates of their corresponding new ones. */
7016 int32_t compatAxis = getCompatAxis(axisId);
7017 if (compatAxis >= 0) {
7018 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7019 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7020 }
7021}
7022
7023/* A mapping from axes the joystick actually has to the axes that should be
7024 * artificially created for compatibility purposes.
7025 * Returns -1 if no compatibility axis is needed. */
7026int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7027 switch(axis) {
7028 case AMOTION_EVENT_AXIS_LTRIGGER:
7029 return AMOTION_EVENT_AXIS_BRAKE;
7030 case AMOTION_EVENT_AXIS_RTRIGGER:
7031 return AMOTION_EVENT_AXIS_GAS;
7032 }
7033 return -1;
7034}
7035
7036void JoystickInputMapper::dump(String8& dump) {
7037 dump.append(INDENT2 "Joystick Input Mapper:\n");
7038
7039 dump.append(INDENT3 "Axes:\n");
7040 size_t numAxes = mAxes.size();
7041 for (size_t i = 0; i < numAxes; i++) {
7042 const Axis& axis = mAxes.valueAt(i);
7043 const char* label = getAxisLabel(axis.axisInfo.axis);
7044 if (label) {
7045 dump.appendFormat(INDENT4 "%s", label);
7046 } else {
7047 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7048 }
7049 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7050 label = getAxisLabel(axis.axisInfo.highAxis);
7051 if (label) {
7052 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7053 } else {
7054 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7055 axis.axisInfo.splitValue);
7056 }
7057 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7058 dump.append(" (invert)");
7059 }
7060
7061 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7062 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7063 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7064 "highScale=%0.5f, highOffset=%0.5f\n",
7065 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7066 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7067 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7068 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7069 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7070 }
7071}
7072
7073void JoystickInputMapper::configure(nsecs_t when,
7074 const InputReaderConfiguration* config, uint32_t changes) {
7075 InputMapper::configure(when, config, changes);
7076
7077 if (!changes) { // first time only
7078 // Collect all axes.
7079 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7080 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7081 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7082 continue; // axis must be claimed by a different device
7083 }
7084
7085 RawAbsoluteAxisInfo rawAxisInfo;
7086 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7087 if (rawAxisInfo.valid) {
7088 // Map axis.
7089 AxisInfo axisInfo;
7090 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7091 if (!explicitlyMapped) {
7092 // Axis is not explicitly mapped, will choose a generic axis later.
7093 axisInfo.mode = AxisInfo::MODE_NORMAL;
7094 axisInfo.axis = -1;
7095 }
7096
7097 // Apply flat override.
7098 int32_t rawFlat = axisInfo.flatOverride < 0
7099 ? rawAxisInfo.flat : axisInfo.flatOverride;
7100
7101 // Calculate scaling factors and limits.
7102 Axis axis;
7103 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7104 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7105 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7106 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7107 scale, 0.0f, highScale, 0.0f,
7108 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7109 rawAxisInfo.resolution * scale);
7110 } else if (isCenteredAxis(axisInfo.axis)) {
7111 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7112 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7113 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7114 scale, offset, scale, offset,
7115 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7116 rawAxisInfo.resolution * scale);
7117 } else {
7118 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7119 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7120 scale, 0.0f, scale, 0.0f,
7121 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7122 rawAxisInfo.resolution * scale);
7123 }
7124
7125 // To eliminate noise while the joystick is at rest, filter out small variations
7126 // in axis values up front.
7127 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7128
7129 mAxes.add(abs, axis);
7130 }
7131 }
7132
7133 // If there are too many axes, start dropping them.
7134 // Prefer to keep explicitly mapped axes.
7135 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007136 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007137 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7138 pruneAxes(true);
7139 pruneAxes(false);
7140 }
7141
7142 // Assign generic axis ids to remaining axes.
7143 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7144 size_t numAxes = mAxes.size();
7145 for (size_t i = 0; i < numAxes; i++) {
7146 Axis& axis = mAxes.editValueAt(i);
7147 if (axis.axisInfo.axis < 0) {
7148 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7149 && haveAxis(nextGenericAxisId)) {
7150 nextGenericAxisId += 1;
7151 }
7152
7153 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7154 axis.axisInfo.axis = nextGenericAxisId;
7155 nextGenericAxisId += 1;
7156 } else {
7157 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7158 "have already been assigned to other axes.",
7159 getDeviceName().string(), mAxes.keyAt(i));
7160 mAxes.removeItemsAt(i--);
7161 numAxes -= 1;
7162 }
7163 }
7164 }
7165 }
7166}
7167
7168bool JoystickInputMapper::haveAxis(int32_t axisId) {
7169 size_t numAxes = mAxes.size();
7170 for (size_t i = 0; i < numAxes; i++) {
7171 const Axis& axis = mAxes.valueAt(i);
7172 if (axis.axisInfo.axis == axisId
7173 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7174 && axis.axisInfo.highAxis == axisId)) {
7175 return true;
7176 }
7177 }
7178 return false;
7179}
7180
7181void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7182 size_t i = mAxes.size();
7183 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7184 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7185 continue;
7186 }
7187 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7188 getDeviceName().string(), mAxes.keyAt(i));
7189 mAxes.removeItemsAt(i);
7190 }
7191}
7192
7193bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7194 switch (axis) {
7195 case AMOTION_EVENT_AXIS_X:
7196 case AMOTION_EVENT_AXIS_Y:
7197 case AMOTION_EVENT_AXIS_Z:
7198 case AMOTION_EVENT_AXIS_RX:
7199 case AMOTION_EVENT_AXIS_RY:
7200 case AMOTION_EVENT_AXIS_RZ:
7201 case AMOTION_EVENT_AXIS_HAT_X:
7202 case AMOTION_EVENT_AXIS_HAT_Y:
7203 case AMOTION_EVENT_AXIS_ORIENTATION:
7204 case AMOTION_EVENT_AXIS_RUDDER:
7205 case AMOTION_EVENT_AXIS_WHEEL:
7206 return true;
7207 default:
7208 return false;
7209 }
7210}
7211
7212void JoystickInputMapper::reset(nsecs_t when) {
7213 // Recenter all axes.
7214 size_t numAxes = mAxes.size();
7215 for (size_t i = 0; i < numAxes; i++) {
7216 Axis& axis = mAxes.editValueAt(i);
7217 axis.resetValue();
7218 }
7219
7220 InputMapper::reset(when);
7221}
7222
7223void JoystickInputMapper::process(const RawEvent* rawEvent) {
7224 switch (rawEvent->type) {
7225 case EV_ABS: {
7226 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7227 if (index >= 0) {
7228 Axis& axis = mAxes.editValueAt(index);
7229 float newValue, highNewValue;
7230 switch (axis.axisInfo.mode) {
7231 case AxisInfo::MODE_INVERT:
7232 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7233 * axis.scale + axis.offset;
7234 highNewValue = 0.0f;
7235 break;
7236 case AxisInfo::MODE_SPLIT:
7237 if (rawEvent->value < axis.axisInfo.splitValue) {
7238 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7239 * axis.scale + axis.offset;
7240 highNewValue = 0.0f;
7241 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7242 newValue = 0.0f;
7243 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7244 * axis.highScale + axis.highOffset;
7245 } else {
7246 newValue = 0.0f;
7247 highNewValue = 0.0f;
7248 }
7249 break;
7250 default:
7251 newValue = rawEvent->value * axis.scale + axis.offset;
7252 highNewValue = 0.0f;
7253 break;
7254 }
7255 axis.newValue = newValue;
7256 axis.highNewValue = highNewValue;
7257 }
7258 break;
7259 }
7260
7261 case EV_SYN:
7262 switch (rawEvent->code) {
7263 case SYN_REPORT:
7264 sync(rawEvent->when, false /*force*/);
7265 break;
7266 }
7267 break;
7268 }
7269}
7270
7271void JoystickInputMapper::sync(nsecs_t when, bool force) {
7272 if (!filterAxes(force)) {
7273 return;
7274 }
7275
7276 int32_t metaState = mContext->getGlobalMetaState();
7277 int32_t buttonState = 0;
7278
7279 PointerProperties pointerProperties;
7280 pointerProperties.clear();
7281 pointerProperties.id = 0;
7282 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7283
7284 PointerCoords pointerCoords;
7285 pointerCoords.clear();
7286
7287 size_t numAxes = mAxes.size();
7288 for (size_t i = 0; i < numAxes; i++) {
7289 const Axis& axis = mAxes.valueAt(i);
7290 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7291 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7292 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7293 axis.highCurrentValue);
7294 }
7295 }
7296
7297 // Moving a joystick axis should not wake the device because joysticks can
7298 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7299 // button will likely wake the device.
7300 // TODO: Use the input device configuration to control this behavior more finely.
7301 uint32_t policyFlags = 0;
7302
7303 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007304 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007305 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7306 getListener()->notifyMotion(&args);
7307}
7308
7309void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7310 int32_t axis, float value) {
7311 pointerCoords->setAxisValue(axis, value);
7312 /* In order to ease the transition for developers from using the old axes
7313 * to the newer, more semantically correct axes, we'll continue to produce
7314 * values for the old axes as mirrors of the value of their corresponding
7315 * new axes. */
7316 int32_t compatAxis = getCompatAxis(axis);
7317 if (compatAxis >= 0) {
7318 pointerCoords->setAxisValue(compatAxis, value);
7319 }
7320}
7321
7322bool JoystickInputMapper::filterAxes(bool force) {
7323 bool atLeastOneSignificantChange = force;
7324 size_t numAxes = mAxes.size();
7325 for (size_t i = 0; i < numAxes; i++) {
7326 Axis& axis = mAxes.editValueAt(i);
7327 if (force || hasValueChangedSignificantly(axis.filter,
7328 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7329 axis.currentValue = axis.newValue;
7330 atLeastOneSignificantChange = true;
7331 }
7332 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7333 if (force || hasValueChangedSignificantly(axis.filter,
7334 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7335 axis.highCurrentValue = axis.highNewValue;
7336 atLeastOneSignificantChange = true;
7337 }
7338 }
7339 }
7340 return atLeastOneSignificantChange;
7341}
7342
7343bool JoystickInputMapper::hasValueChangedSignificantly(
7344 float filter, float newValue, float currentValue, float min, float max) {
7345 if (newValue != currentValue) {
7346 // Filter out small changes in value unless the value is converging on the axis
7347 // bounds or center point. This is intended to reduce the amount of information
7348 // sent to applications by particularly noisy joysticks (such as PS3).
7349 if (fabs(newValue - currentValue) > filter
7350 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7351 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7352 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7353 return true;
7354 }
7355 }
7356 return false;
7357}
7358
7359bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7360 float filter, float newValue, float currentValue, float thresholdValue) {
7361 float newDistance = fabs(newValue - thresholdValue);
7362 if (newDistance < filter) {
7363 float oldDistance = fabs(currentValue - thresholdValue);
7364 if (newDistance < oldDistance) {
7365 return true;
7366 }
7367 }
7368 return false;
7369}
7370
7371} // namespace android