blob: cc81a298a2e478708a96081ecca8bbec57e32629 [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
Michael Wright58ba9882017-07-26 16:19:11 +01002332bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2333 switch (keyCode) {
2334 case AKEYCODE_MEDIA_PLAY:
2335 case AKEYCODE_MEDIA_PAUSE:
2336 case AKEYCODE_MEDIA_PLAY_PAUSE:
2337 case AKEYCODE_MUTE:
2338 case AKEYCODE_HEADSETHOOK:
2339 case AKEYCODE_MEDIA_STOP:
2340 case AKEYCODE_MEDIA_NEXT:
2341 case AKEYCODE_MEDIA_PREVIOUS:
2342 case AKEYCODE_MEDIA_REWIND:
2343 case AKEYCODE_MEDIA_RECORD:
2344 case AKEYCODE_MEDIA_FAST_FORWARD:
2345 case AKEYCODE_MEDIA_SKIP_FORWARD:
2346 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2347 case AKEYCODE_MEDIA_STEP_FORWARD:
2348 case AKEYCODE_MEDIA_STEP_BACKWARD:
2349 case AKEYCODE_MEDIA_AUDIO_TRACK:
2350 case AKEYCODE_VOLUME_UP:
2351 case AKEYCODE_VOLUME_DOWN:
2352 case AKEYCODE_VOLUME_MUTE:
2353 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2354 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2355 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2356 return true;
2357 }
2358 return false;
2359}
2360
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002361void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2362 int32_t usageCode) {
2363 int32_t keyCode;
2364 int32_t keyMetaState;
2365 uint32_t policyFlags;
2366
2367 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2368 &keyCode, &keyMetaState, &policyFlags)) {
2369 keyCode = AKEYCODE_UNKNOWN;
2370 keyMetaState = mMetaState;
2371 policyFlags = 0;
2372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373
2374 if (down) {
2375 // Rotate key codes according to orientation if needed.
2376 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2377 keyCode = rotateKeyCode(keyCode, mOrientation);
2378 }
2379
2380 // Add key down.
2381 ssize_t keyDownIndex = findKeyDown(scanCode);
2382 if (keyDownIndex >= 0) {
2383 // key repeat, be sure to use same keycode as before in case of rotation
2384 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2385 } else {
2386 // key down
2387 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2388 && mContext->shouldDropVirtualKey(when,
2389 getDevice(), keyCode, scanCode)) {
2390 return;
2391 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002392 if (policyFlags & POLICY_FLAG_GESTURE) {
2393 mDevice->cancelTouch(when);
2394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395
2396 mKeyDowns.push();
2397 KeyDown& keyDown = mKeyDowns.editTop();
2398 keyDown.keyCode = keyCode;
2399 keyDown.scanCode = scanCode;
2400 }
2401
2402 mDownTime = when;
2403 } else {
2404 // Remove key down.
2405 ssize_t keyDownIndex = findKeyDown(scanCode);
2406 if (keyDownIndex >= 0) {
2407 // key up, be sure to use same keycode as before in case of rotation
2408 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2409 mKeyDowns.removeAt(size_t(keyDownIndex));
2410 } else {
2411 // key was not actually down
2412 ALOGI("Dropping key up from device %s because the key was not down. "
2413 "keyCode=%d, scanCode=%d",
2414 getDeviceName().string(), keyCode, scanCode);
2415 return;
2416 }
2417 }
2418
Andrii Kulian763a3a42016-03-08 10:46:16 -08002419 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002420 // If global meta state changed send it along with the key.
2421 // If it has not changed then we'll use what keymap gave us,
2422 // since key replacement logic might temporarily reset a few
2423 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002424 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426
2427 nsecs_t downTime = mDownTime;
2428
2429 // Key down on external an keyboard should wake the device.
2430 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2431 // For internal keyboards, the key layout file should specify the policy flags for
2432 // each wake key individually.
2433 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002434 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002435 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
2437
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002438 if (mParameters.handlesKeyRepeat) {
2439 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2440 }
2441
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2443 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002444 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 getListener()->notifyKey(&args);
2446}
2447
2448ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2449 size_t n = mKeyDowns.size();
2450 for (size_t i = 0; i < n; i++) {
2451 if (mKeyDowns[i].scanCode == scanCode) {
2452 return i;
2453 }
2454 }
2455 return -1;
2456}
2457
2458int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2459 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2460}
2461
2462int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2463 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2464}
2465
2466bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2467 const int32_t* keyCodes, uint8_t* outFlags) {
2468 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2469}
2470
2471int32_t KeyboardInputMapper::getMetaState() {
2472 return mMetaState;
2473}
2474
Andrii Kulian763a3a42016-03-08 10:46:16 -08002475void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2476 updateMetaStateIfNeeded(keyCode, false);
2477}
2478
2479bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2480 int32_t oldMetaState = mMetaState;
2481 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2482 bool metaStateChanged = oldMetaState != newMetaState;
2483 if (metaStateChanged) {
2484 mMetaState = newMetaState;
2485 updateLedState(false);
2486
2487 getContext()->updateGlobalMetaState();
2488 }
2489
2490 return metaStateChanged;
2491}
2492
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493void KeyboardInputMapper::resetLedState() {
2494 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2495 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2496 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2497
2498 updateLedState(true);
2499}
2500
2501void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2502 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2503 ledState.on = false;
2504}
2505
2506void KeyboardInputMapper::updateLedState(bool reset) {
2507 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2508 AMETA_CAPS_LOCK_ON, reset);
2509 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2510 AMETA_NUM_LOCK_ON, reset);
2511 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2512 AMETA_SCROLL_LOCK_ON, reset);
2513}
2514
2515void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2516 int32_t led, int32_t modifier, bool reset) {
2517 if (ledState.avail) {
2518 bool desiredState = (mMetaState & modifier) != 0;
2519 if (reset || ledState.on != desiredState) {
2520 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2521 ledState.on = desiredState;
2522 }
2523 }
2524}
2525
2526
2527// --- CursorInputMapper ---
2528
2529CursorInputMapper::CursorInputMapper(InputDevice* device) :
2530 InputMapper(device) {
2531}
2532
2533CursorInputMapper::~CursorInputMapper() {
2534}
2535
2536uint32_t CursorInputMapper::getSources() {
2537 return mSource;
2538}
2539
2540void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2541 InputMapper::populateDeviceInfo(info);
2542
2543 if (mParameters.mode == Parameters::MODE_POINTER) {
2544 float minX, minY, maxX, maxY;
2545 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2546 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2547 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2548 }
2549 } else {
2550 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2551 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2552 }
2553 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2554
2555 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2556 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2557 }
2558 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2559 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2560 }
2561}
2562
2563void CursorInputMapper::dump(String8& dump) {
2564 dump.append(INDENT2 "Cursor Input Mapper:\n");
2565 dumpParameters(dump);
2566 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2567 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2568 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2569 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2570 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2571 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2572 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2573 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2574 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2575 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2576 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2577 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2578 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002579 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580}
2581
2582void CursorInputMapper::configure(nsecs_t when,
2583 const InputReaderConfiguration* config, uint32_t changes) {
2584 InputMapper::configure(when, config, changes);
2585
2586 if (!changes) { // first time only
2587 mCursorScrollAccumulator.configure(getDevice());
2588
2589 // Configure basic parameters.
2590 configureParameters();
2591
2592 // Configure device mode.
2593 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002594 case Parameters::MODE_POINTER_RELATIVE:
2595 // Should not happen during first time configuration.
2596 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2597 mParameters.mode = Parameters::MODE_POINTER;
2598 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 case Parameters::MODE_POINTER:
2600 mSource = AINPUT_SOURCE_MOUSE;
2601 mXPrecision = 1.0f;
2602 mYPrecision = 1.0f;
2603 mXScale = 1.0f;
2604 mYScale = 1.0f;
2605 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2606 break;
2607 case Parameters::MODE_NAVIGATION:
2608 mSource = AINPUT_SOURCE_TRACKBALL;
2609 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2610 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2611 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2612 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2613 break;
2614 }
2615
2616 mVWheelScale = 1.0f;
2617 mHWheelScale = 1.0f;
2618 }
2619
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002620 if ((!changes && config->pointerCapture)
2621 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2622 if (config->pointerCapture) {
2623 if (mParameters.mode == Parameters::MODE_POINTER) {
2624 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2625 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2626 // Keep PointerController around in order to preserve the pointer position.
2627 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2628 } else {
2629 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2630 }
2631 } else {
2632 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2633 mParameters.mode = Parameters::MODE_POINTER;
2634 mSource = AINPUT_SOURCE_MOUSE;
2635 } else {
2636 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2637 }
2638 }
2639 bumpGeneration();
2640 if (changes) {
2641 getDevice()->notifyReset(when);
2642 }
2643 }
2644
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2646 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2647 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2648 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2649 }
2650
2651 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2652 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2653 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002654 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 mOrientation = v.orientation;
2656 } else {
2657 mOrientation = DISPLAY_ORIENTATION_0;
2658 }
2659 } else {
2660 mOrientation = DISPLAY_ORIENTATION_0;
2661 }
2662 bumpGeneration();
2663 }
2664}
2665
2666void CursorInputMapper::configureParameters() {
2667 mParameters.mode = Parameters::MODE_POINTER;
2668 String8 cursorModeString;
2669 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2670 if (cursorModeString == "navigation") {
2671 mParameters.mode = Parameters::MODE_NAVIGATION;
2672 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2673 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2674 }
2675 }
2676
2677 mParameters.orientationAware = false;
2678 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2679 mParameters.orientationAware);
2680
2681 mParameters.hasAssociatedDisplay = false;
2682 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2683 mParameters.hasAssociatedDisplay = true;
2684 }
2685}
2686
2687void CursorInputMapper::dumpParameters(String8& dump) {
2688 dump.append(INDENT3 "Parameters:\n");
2689 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2690 toString(mParameters.hasAssociatedDisplay));
2691
2692 switch (mParameters.mode) {
2693 case Parameters::MODE_POINTER:
2694 dump.append(INDENT4 "Mode: pointer\n");
2695 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002696 case Parameters::MODE_POINTER_RELATIVE:
2697 dump.append(INDENT4 "Mode: relative pointer\n");
2698 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 case Parameters::MODE_NAVIGATION:
2700 dump.append(INDENT4 "Mode: navigation\n");
2701 break;
2702 default:
2703 ALOG_ASSERT(false);
2704 }
2705
2706 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2707 toString(mParameters.orientationAware));
2708}
2709
2710void CursorInputMapper::reset(nsecs_t when) {
2711 mButtonState = 0;
2712 mDownTime = 0;
2713
2714 mPointerVelocityControl.reset();
2715 mWheelXVelocityControl.reset();
2716 mWheelYVelocityControl.reset();
2717
2718 mCursorButtonAccumulator.reset(getDevice());
2719 mCursorMotionAccumulator.reset(getDevice());
2720 mCursorScrollAccumulator.reset(getDevice());
2721
2722 InputMapper::reset(when);
2723}
2724
2725void CursorInputMapper::process(const RawEvent* rawEvent) {
2726 mCursorButtonAccumulator.process(rawEvent);
2727 mCursorMotionAccumulator.process(rawEvent);
2728 mCursorScrollAccumulator.process(rawEvent);
2729
2730 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2731 sync(rawEvent->when);
2732 }
2733}
2734
2735void CursorInputMapper::sync(nsecs_t when) {
2736 int32_t lastButtonState = mButtonState;
2737 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2738 mButtonState = currentButtonState;
2739
2740 bool wasDown = isPointerDown(lastButtonState);
2741 bool down = isPointerDown(currentButtonState);
2742 bool downChanged;
2743 if (!wasDown && down) {
2744 mDownTime = when;
2745 downChanged = true;
2746 } else if (wasDown && !down) {
2747 downChanged = true;
2748 } else {
2749 downChanged = false;
2750 }
2751 nsecs_t downTime = mDownTime;
2752 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002753 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2754 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
2756 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2757 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2758 bool moved = deltaX != 0 || deltaY != 0;
2759
2760 // Rotate delta according to orientation if needed.
2761 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2762 && (deltaX != 0.0f || deltaY != 0.0f)) {
2763 rotateDelta(mOrientation, &deltaX, &deltaY);
2764 }
2765
2766 // Move the pointer.
2767 PointerProperties pointerProperties;
2768 pointerProperties.clear();
2769 pointerProperties.id = 0;
2770 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2771
2772 PointerCoords pointerCoords;
2773 pointerCoords.clear();
2774
2775 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2776 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2777 bool scrolled = vscroll != 0 || hscroll != 0;
2778
2779 mWheelYVelocityControl.move(when, NULL, &vscroll);
2780 mWheelXVelocityControl.move(when, &hscroll, NULL);
2781
2782 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2783
2784 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002785 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 if (moved || scrolled || buttonsChanged) {
2787 mPointerController->setPresentation(
2788 PointerControllerInterface::PRESENTATION_POINTER);
2789
2790 if (moved) {
2791 mPointerController->move(deltaX, deltaY);
2792 }
2793
2794 if (buttonsChanged) {
2795 mPointerController->setButtonState(currentButtonState);
2796 }
2797
2798 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2799 }
2800
2801 float x, y;
2802 mPointerController->getPosition(&x, &y);
2803 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2804 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2806 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 displayId = ADISPLAY_ID_DEFAULT;
2808 } else {
2809 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2810 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2811 displayId = ADISPLAY_ID_NONE;
2812 }
2813
2814 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2815
2816 // Moving an external trackball or mouse should wake the device.
2817 // We don't do this for internal cursor devices to prevent them from waking up
2818 // the device in your pocket.
2819 // TODO: Use the input device configuration to control this behavior more finely.
2820 uint32_t policyFlags = 0;
2821 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002822 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
2824
2825 // Synthesize key down from buttons if needed.
2826 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2827 policyFlags, lastButtonState, currentButtonState);
2828
2829 // Send motion event.
2830 if (downChanged || moved || scrolled || buttonsChanged) {
2831 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002832 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 int32_t motionEventAction;
2834 if (downChanged) {
2835 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002836 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2838 } else {
2839 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2840 }
2841
Michael Wright7b159c92015-05-14 14:48:03 +01002842 if (buttonsReleased) {
2843 BitSet32 released(buttonsReleased);
2844 while (!released.isEmpty()) {
2845 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2846 buttonState &= ~actionButton;
2847 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2848 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2849 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2850 displayId, 1, &pointerProperties, &pointerCoords,
2851 mXPrecision, mYPrecision, downTime);
2852 getListener()->notifyMotion(&releaseArgs);
2853 }
2854 }
2855
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002857 motionEventAction, 0, 0, metaState, currentButtonState,
2858 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 displayId, 1, &pointerProperties, &pointerCoords,
2860 mXPrecision, mYPrecision, downTime);
2861 getListener()->notifyMotion(&args);
2862
Michael Wright7b159c92015-05-14 14:48:03 +01002863 if (buttonsPressed) {
2864 BitSet32 pressed(buttonsPressed);
2865 while (!pressed.isEmpty()) {
2866 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2867 buttonState |= actionButton;
2868 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2869 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2870 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2871 displayId, 1, &pointerProperties, &pointerCoords,
2872 mXPrecision, mYPrecision, downTime);
2873 getListener()->notifyMotion(&pressArgs);
2874 }
2875 }
2876
2877 ALOG_ASSERT(buttonState == currentButtonState);
2878
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 // Send hover move after UP to tell the application that the mouse is hovering now.
2880 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002881 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002883 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2885 displayId, 1, &pointerProperties, &pointerCoords,
2886 mXPrecision, mYPrecision, downTime);
2887 getListener()->notifyMotion(&hoverArgs);
2888 }
2889
2890 // Send scroll events.
2891 if (scrolled) {
2892 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2893 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2894
2895 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002896 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 AMOTION_EVENT_EDGE_FLAG_NONE,
2898 displayId, 1, &pointerProperties, &pointerCoords,
2899 mXPrecision, mYPrecision, downTime);
2900 getListener()->notifyMotion(&scrollArgs);
2901 }
2902 }
2903
2904 // Synthesize key up from buttons if needed.
2905 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2906 policyFlags, lastButtonState, currentButtonState);
2907
2908 mCursorMotionAccumulator.finishSync();
2909 mCursorScrollAccumulator.finishSync();
2910}
2911
2912int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2913 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2914 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2915 } else {
2916 return AKEY_STATE_UNKNOWN;
2917 }
2918}
2919
2920void CursorInputMapper::fadePointer() {
2921 if (mPointerController != NULL) {
2922 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2923 }
2924}
2925
Prashant Malani1941ff52015-08-11 18:29:28 -07002926// --- RotaryEncoderInputMapper ---
2927
2928RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2929 InputMapper(device) {
2930 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2931}
2932
2933RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2934}
2935
2936uint32_t RotaryEncoderInputMapper::getSources() {
2937 return mSource;
2938}
2939
2940void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2941 InputMapper::populateDeviceInfo(info);
2942
2943 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002944 float res = 0.0f;
2945 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2946 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2947 }
2948 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2949 mScalingFactor)) {
2950 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2951 "default to 1.0!\n");
2952 mScalingFactor = 1.0f;
2953 }
2954 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2955 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002956 }
2957}
2958
2959void RotaryEncoderInputMapper::dump(String8& dump) {
2960 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2961 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2962 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2963}
2964
2965void RotaryEncoderInputMapper::configure(nsecs_t when,
2966 const InputReaderConfiguration* config, uint32_t changes) {
2967 InputMapper::configure(when, config, changes);
2968 if (!changes) {
2969 mRotaryEncoderScrollAccumulator.configure(getDevice());
2970 }
2971}
2972
2973void RotaryEncoderInputMapper::reset(nsecs_t when) {
2974 mRotaryEncoderScrollAccumulator.reset(getDevice());
2975
2976 InputMapper::reset(when);
2977}
2978
2979void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2980 mRotaryEncoderScrollAccumulator.process(rawEvent);
2981
2982 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2983 sync(rawEvent->when);
2984 }
2985}
2986
2987void RotaryEncoderInputMapper::sync(nsecs_t when) {
2988 PointerCoords pointerCoords;
2989 pointerCoords.clear();
2990
2991 PointerProperties pointerProperties;
2992 pointerProperties.clear();
2993 pointerProperties.id = 0;
2994 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2995
2996 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2997 bool scrolled = scroll != 0;
2998
2999 // This is not a pointer, so it's not associated with a display.
3000 int32_t displayId = ADISPLAY_ID_NONE;
3001
3002 // Moving the rotary encoder should wake the device (if specified).
3003 uint32_t policyFlags = 0;
3004 if (scrolled && getDevice()->isExternal()) {
3005 policyFlags |= POLICY_FLAG_WAKE;
3006 }
3007
3008 // Send motion event.
3009 if (scrolled) {
3010 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003011 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003012
3013 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3014 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3015 AMOTION_EVENT_EDGE_FLAG_NONE,
3016 displayId, 1, &pointerProperties, &pointerCoords,
3017 0, 0, 0);
3018 getListener()->notifyMotion(&scrollArgs);
3019 }
3020
3021 mRotaryEncoderScrollAccumulator.finishSync();
3022}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023
3024// --- TouchInputMapper ---
3025
3026TouchInputMapper::TouchInputMapper(InputDevice* device) :
3027 InputMapper(device),
3028 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3029 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3030 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3031}
3032
3033TouchInputMapper::~TouchInputMapper() {
3034}
3035
3036uint32_t TouchInputMapper::getSources() {
3037 return mSource;
3038}
3039
3040void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3041 InputMapper::populateDeviceInfo(info);
3042
3043 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3044 info->addMotionRange(mOrientedRanges.x);
3045 info->addMotionRange(mOrientedRanges.y);
3046 info->addMotionRange(mOrientedRanges.pressure);
3047
3048 if (mOrientedRanges.haveSize) {
3049 info->addMotionRange(mOrientedRanges.size);
3050 }
3051
3052 if (mOrientedRanges.haveTouchSize) {
3053 info->addMotionRange(mOrientedRanges.touchMajor);
3054 info->addMotionRange(mOrientedRanges.touchMinor);
3055 }
3056
3057 if (mOrientedRanges.haveToolSize) {
3058 info->addMotionRange(mOrientedRanges.toolMajor);
3059 info->addMotionRange(mOrientedRanges.toolMinor);
3060 }
3061
3062 if (mOrientedRanges.haveOrientation) {
3063 info->addMotionRange(mOrientedRanges.orientation);
3064 }
3065
3066 if (mOrientedRanges.haveDistance) {
3067 info->addMotionRange(mOrientedRanges.distance);
3068 }
3069
3070 if (mOrientedRanges.haveTilt) {
3071 info->addMotionRange(mOrientedRanges.tilt);
3072 }
3073
3074 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3075 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3076 0.0f);
3077 }
3078 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3079 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3080 0.0f);
3081 }
3082 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3083 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3084 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3085 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3086 x.fuzz, x.resolution);
3087 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3088 y.fuzz, y.resolution);
3089 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3090 x.fuzz, x.resolution);
3091 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3092 y.fuzz, y.resolution);
3093 }
3094 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3095 }
3096}
3097
3098void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003099 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 dumpParameters(dump);
3101 dumpVirtualKeys(dump);
3102 dumpRawPointerAxes(dump);
3103 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003104 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 dumpSurface(dump);
3106
3107 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3108 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3109 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3110 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3111 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3112 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3113 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3114 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3115 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3116 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3117 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3118 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3119 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3120 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3121 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3122 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3123 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3124
Michael Wright7b159c92015-05-14 14:48:03 +01003125 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003127 mLastRawState.rawPointerData.pointerCount);
3128 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3129 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3131 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3132 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3133 "toolType=%d, isHovering=%s\n", i,
3134 pointer.id, pointer.x, pointer.y, pointer.pressure,
3135 pointer.touchMajor, pointer.touchMinor,
3136 pointer.toolMajor, pointer.toolMinor,
3137 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3138 pointer.toolType, toString(pointer.isHovering));
3139 }
3140
Michael Wright7b159c92015-05-14 14:48:03 +01003141 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003143 mLastCookedState.cookedPointerData.pointerCount);
3144 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3145 const PointerProperties& pointerProperties =
3146 mLastCookedState.cookedPointerData.pointerProperties[i];
3147 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3149 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3150 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3151 "toolType=%d, isHovering=%s\n", i,
3152 pointerProperties.id,
3153 pointerCoords.getX(),
3154 pointerCoords.getY(),
3155 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3156 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3157 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3158 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3159 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3160 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3161 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3162 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3163 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003164 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166
Michael Wright842500e2015-03-13 17:32:02 -07003167 dump.append(INDENT3 "Stylus Fusion:\n");
3168 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3169 toString(mExternalStylusConnected));
3170 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3171 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003172 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003173 dump.append(INDENT3 "External Stylus State:\n");
3174 dumpStylusState(dump, mExternalStylusState);
3175
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 if (mDeviceMode == DEVICE_MODE_POINTER) {
3177 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3178 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3179 mPointerXMovementScale);
3180 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3181 mPointerYMovementScale);
3182 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3183 mPointerXZoomScale);
3184 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3185 mPointerYZoomScale);
3186 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3187 mPointerGestureMaxSwipeWidth);
3188 }
3189}
3190
Santos Cordonfa5cf462017-04-05 10:37:00 -07003191const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3192 switch (deviceMode) {
3193 case DEVICE_MODE_DISABLED:
3194 return "disabled";
3195 case DEVICE_MODE_DIRECT:
3196 return "direct";
3197 case DEVICE_MODE_UNSCALED:
3198 return "unscaled";
3199 case DEVICE_MODE_NAVIGATION:
3200 return "navigation";
3201 case DEVICE_MODE_POINTER:
3202 return "pointer";
3203 }
3204 return "unknown";
3205}
3206
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207void TouchInputMapper::configure(nsecs_t when,
3208 const InputReaderConfiguration* config, uint32_t changes) {
3209 InputMapper::configure(when, config, changes);
3210
3211 mConfig = *config;
3212
3213 if (!changes) { // first time only
3214 // Configure basic parameters.
3215 configureParameters();
3216
3217 // Configure common accumulators.
3218 mCursorScrollAccumulator.configure(getDevice());
3219 mTouchButtonAccumulator.configure(getDevice());
3220
3221 // Configure absolute axis information.
3222 configureRawPointerAxes();
3223
3224 // Prepare input device calibration.
3225 parseCalibration();
3226 resolveCalibration();
3227 }
3228
Michael Wright842500e2015-03-13 17:32:02 -07003229 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003230 // Update location calibration to reflect current settings
3231 updateAffineTransformation();
3232 }
3233
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3235 // Update pointer speed.
3236 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3237 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3238 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3239 }
3240
3241 bool resetNeeded = false;
3242 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3243 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003244 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3245 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 // Configure device sources, surface dimensions, orientation and
3247 // scaling factors.
3248 configureSurface(when, &resetNeeded);
3249 }
3250
3251 if (changes && resetNeeded) {
3252 // Send reset, unless this is the first time the device has been configured,
3253 // in which case the reader will call reset itself after all mappers are ready.
3254 getDevice()->notifyReset(when);
3255 }
3256}
3257
Michael Wright842500e2015-03-13 17:32:02 -07003258void TouchInputMapper::resolveExternalStylusPresence() {
3259 Vector<InputDeviceInfo> devices;
3260 mContext->getExternalStylusDevices(devices);
3261 mExternalStylusConnected = !devices.isEmpty();
3262
3263 if (!mExternalStylusConnected) {
3264 resetExternalStylus();
3265 }
3266}
3267
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268void TouchInputMapper::configureParameters() {
3269 // Use the pointer presentation mode for devices that do not support distinct
3270 // multitouch. The spot-based presentation relies on being able to accurately
3271 // locate two or more fingers on the touch pad.
3272 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003273 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274
3275 String8 gestureModeString;
3276 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3277 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003278 if (gestureModeString == "single-touch") {
3279 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3280 } else if (gestureModeString == "multi-touch") {
3281 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 } else if (gestureModeString != "default") {
3283 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3284 }
3285 }
3286
3287 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3288 // The device is a touch screen.
3289 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3290 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3291 // The device is a pointing device like a track pad.
3292 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3293 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3294 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3295 // The device is a cursor device with a touch pad attached.
3296 // By default don't use the touch pad to move the pointer.
3297 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3298 } else {
3299 // The device is a touch pad of unknown purpose.
3300 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3301 }
3302
3303 mParameters.hasButtonUnderPad=
3304 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3305
3306 String8 deviceTypeString;
3307 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3308 deviceTypeString)) {
3309 if (deviceTypeString == "touchScreen") {
3310 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3311 } else if (deviceTypeString == "touchPad") {
3312 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3313 } else if (deviceTypeString == "touchNavigation") {
3314 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3315 } else if (deviceTypeString == "pointer") {
3316 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3317 } else if (deviceTypeString != "default") {
3318 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3319 }
3320 }
3321
3322 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3323 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3324 mParameters.orientationAware);
3325
3326 mParameters.hasAssociatedDisplay = false;
3327 mParameters.associatedDisplayIsExternal = false;
3328 if (mParameters.orientationAware
3329 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3330 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3331 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003332 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3333 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3334 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3335 mParameters.uniqueDisplayId);
3336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003338
3339 // Initial downs on external touch devices should wake the device.
3340 // Normally we don't do this for internal touch screens to prevent them from waking
3341 // up in your pocket but you can enable it using the input device configuration.
3342 mParameters.wake = getDevice()->isExternal();
3343 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3344 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345}
3346
3347void TouchInputMapper::dumpParameters(String8& dump) {
3348 dump.append(INDENT3 "Parameters:\n");
3349
3350 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003351 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3352 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003354 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3355 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 break;
3357 default:
3358 assert(false);
3359 }
3360
3361 switch (mParameters.deviceType) {
3362 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3363 dump.append(INDENT4 "DeviceType: touchScreen\n");
3364 break;
3365 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3366 dump.append(INDENT4 "DeviceType: touchPad\n");
3367 break;
3368 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3369 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3370 break;
3371 case Parameters::DEVICE_TYPE_POINTER:
3372 dump.append(INDENT4 "DeviceType: pointer\n");
3373 break;
3374 default:
3375 ALOG_ASSERT(false);
3376 }
3377
Santos Cordonfa5cf462017-04-05 10:37:00 -07003378 dump.appendFormat(
3379 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003381 toString(mParameters.associatedDisplayIsExternal),
3382 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3384 toString(mParameters.orientationAware));
3385}
3386
3387void TouchInputMapper::configureRawPointerAxes() {
3388 mRawPointerAxes.clear();
3389}
3390
3391void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3392 dump.append(INDENT3 "Raw Touch Axes:\n");
3393 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3394 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3395 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3396 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3397 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3398 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3399 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3400 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3401 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3402 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3403 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3404 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3405 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3406}
3407
Michael Wright842500e2015-03-13 17:32:02 -07003408bool TouchInputMapper::hasExternalStylus() const {
3409 return mExternalStylusConnected;
3410}
3411
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3413 int32_t oldDeviceMode = mDeviceMode;
3414
Michael Wright842500e2015-03-13 17:32:02 -07003415 resolveExternalStylusPresence();
3416
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 // Determine device mode.
3418 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3419 && mConfig.pointerGesturesEnabled) {
3420 mSource = AINPUT_SOURCE_MOUSE;
3421 mDeviceMode = DEVICE_MODE_POINTER;
3422 if (hasStylus()) {
3423 mSource |= AINPUT_SOURCE_STYLUS;
3424 }
3425 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3426 && mParameters.hasAssociatedDisplay) {
3427 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3428 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003429 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 mSource |= AINPUT_SOURCE_STYLUS;
3431 }
Michael Wright2f78b682015-06-12 15:25:08 +01003432 if (hasExternalStylus()) {
3433 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3436 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3437 mDeviceMode = DEVICE_MODE_NAVIGATION;
3438 } else {
3439 mSource = AINPUT_SOURCE_TOUCHPAD;
3440 mDeviceMode = DEVICE_MODE_UNSCALED;
3441 }
3442
3443 // Ensure we have valid X and Y axes.
3444 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3445 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3446 "The device will be inoperable.", getDeviceName().string());
3447 mDeviceMode = DEVICE_MODE_DISABLED;
3448 return;
3449 }
3450
3451 // Raw width and height in the natural orientation.
3452 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3453 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3454
3455 // Get associated display dimensions.
3456 DisplayViewport newViewport;
3457 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003458 const String8* uniqueDisplayId = NULL;
3459 ViewportType viewportTypeToUse;
3460
3461 if (mParameters.associatedDisplayIsExternal) {
3462 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3463 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3464 // If the IDC file specified a unique display Id, then it expects to be linked to a
3465 // virtual display with the same unique ID.
3466 uniqueDisplayId = &mParameters.uniqueDisplayId;
3467 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3468 } else {
3469 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3470 }
3471
3472 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3474 "display. The device will be inoperable until the display size "
3475 "becomes available.",
3476 getDeviceName().string());
3477 mDeviceMode = DEVICE_MODE_DISABLED;
3478 return;
3479 }
3480 } else {
3481 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3482 }
3483 bool viewportChanged = mViewport != newViewport;
3484 if (viewportChanged) {
3485 mViewport = newViewport;
3486
3487 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3488 // Convert rotated viewport to natural surface coordinates.
3489 int32_t naturalLogicalWidth, naturalLogicalHeight;
3490 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3491 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3492 int32_t naturalDeviceWidth, naturalDeviceHeight;
3493 switch (mViewport.orientation) {
3494 case DISPLAY_ORIENTATION_90:
3495 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3496 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3497 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3498 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3499 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3500 naturalPhysicalTop = mViewport.physicalLeft;
3501 naturalDeviceWidth = mViewport.deviceHeight;
3502 naturalDeviceHeight = mViewport.deviceWidth;
3503 break;
3504 case DISPLAY_ORIENTATION_180:
3505 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3506 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3507 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3508 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3509 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3510 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3511 naturalDeviceWidth = mViewport.deviceWidth;
3512 naturalDeviceHeight = mViewport.deviceHeight;
3513 break;
3514 case DISPLAY_ORIENTATION_270:
3515 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3516 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3517 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3518 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3519 naturalPhysicalLeft = mViewport.physicalTop;
3520 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3521 naturalDeviceWidth = mViewport.deviceHeight;
3522 naturalDeviceHeight = mViewport.deviceWidth;
3523 break;
3524 case DISPLAY_ORIENTATION_0:
3525 default:
3526 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3527 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3528 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3529 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3530 naturalPhysicalLeft = mViewport.physicalLeft;
3531 naturalPhysicalTop = mViewport.physicalTop;
3532 naturalDeviceWidth = mViewport.deviceWidth;
3533 naturalDeviceHeight = mViewport.deviceHeight;
3534 break;
3535 }
3536
3537 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3538 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3539 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3540 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3541
3542 mSurfaceOrientation = mParameters.orientationAware ?
3543 mViewport.orientation : DISPLAY_ORIENTATION_0;
3544 } else {
3545 mSurfaceWidth = rawWidth;
3546 mSurfaceHeight = rawHeight;
3547 mSurfaceLeft = 0;
3548 mSurfaceTop = 0;
3549 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3550 }
3551 }
3552
3553 // If moving between pointer modes, need to reset some state.
3554 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3555 if (deviceModeChanged) {
3556 mOrientedRanges.clear();
3557 }
3558
3559 // Create pointer controller if needed.
3560 if (mDeviceMode == DEVICE_MODE_POINTER ||
3561 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3562 if (mPointerController == NULL) {
3563 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3564 }
3565 } else {
3566 mPointerController.clear();
3567 }
3568
3569 if (viewportChanged || deviceModeChanged) {
3570 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3571 "display id %d",
3572 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3573 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3574
3575 // Configure X and Y factors.
3576 mXScale = float(mSurfaceWidth) / rawWidth;
3577 mYScale = float(mSurfaceHeight) / rawHeight;
3578 mXTranslate = -mSurfaceLeft;
3579 mYTranslate = -mSurfaceTop;
3580 mXPrecision = 1.0f / mXScale;
3581 mYPrecision = 1.0f / mYScale;
3582
3583 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3584 mOrientedRanges.x.source = mSource;
3585 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3586 mOrientedRanges.y.source = mSource;
3587
3588 configureVirtualKeys();
3589
3590 // Scale factor for terms that are not oriented in a particular axis.
3591 // If the pixels are square then xScale == yScale otherwise we fake it
3592 // by choosing an average.
3593 mGeometricScale = avg(mXScale, mYScale);
3594
3595 // Size of diagonal axis.
3596 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3597
3598 // Size factors.
3599 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3600 if (mRawPointerAxes.touchMajor.valid
3601 && mRawPointerAxes.touchMajor.maxValue != 0) {
3602 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3603 } else if (mRawPointerAxes.toolMajor.valid
3604 && mRawPointerAxes.toolMajor.maxValue != 0) {
3605 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3606 } else {
3607 mSizeScale = 0.0f;
3608 }
3609
3610 mOrientedRanges.haveTouchSize = true;
3611 mOrientedRanges.haveToolSize = true;
3612 mOrientedRanges.haveSize = true;
3613
3614 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3615 mOrientedRanges.touchMajor.source = mSource;
3616 mOrientedRanges.touchMajor.min = 0;
3617 mOrientedRanges.touchMajor.max = diagonalSize;
3618 mOrientedRanges.touchMajor.flat = 0;
3619 mOrientedRanges.touchMajor.fuzz = 0;
3620 mOrientedRanges.touchMajor.resolution = 0;
3621
3622 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3623 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3624
3625 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3626 mOrientedRanges.toolMajor.source = mSource;
3627 mOrientedRanges.toolMajor.min = 0;
3628 mOrientedRanges.toolMajor.max = diagonalSize;
3629 mOrientedRanges.toolMajor.flat = 0;
3630 mOrientedRanges.toolMajor.fuzz = 0;
3631 mOrientedRanges.toolMajor.resolution = 0;
3632
3633 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3634 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3635
3636 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3637 mOrientedRanges.size.source = mSource;
3638 mOrientedRanges.size.min = 0;
3639 mOrientedRanges.size.max = 1.0;
3640 mOrientedRanges.size.flat = 0;
3641 mOrientedRanges.size.fuzz = 0;
3642 mOrientedRanges.size.resolution = 0;
3643 } else {
3644 mSizeScale = 0.0f;
3645 }
3646
3647 // Pressure factors.
3648 mPressureScale = 0;
3649 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3650 || mCalibration.pressureCalibration
3651 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3652 if (mCalibration.havePressureScale) {
3653 mPressureScale = mCalibration.pressureScale;
3654 } else if (mRawPointerAxes.pressure.valid
3655 && mRawPointerAxes.pressure.maxValue != 0) {
3656 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3657 }
3658 }
3659
3660 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3661 mOrientedRanges.pressure.source = mSource;
3662 mOrientedRanges.pressure.min = 0;
3663 mOrientedRanges.pressure.max = 1.0;
3664 mOrientedRanges.pressure.flat = 0;
3665 mOrientedRanges.pressure.fuzz = 0;
3666 mOrientedRanges.pressure.resolution = 0;
3667
3668 // Tilt
3669 mTiltXCenter = 0;
3670 mTiltXScale = 0;
3671 mTiltYCenter = 0;
3672 mTiltYScale = 0;
3673 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3674 if (mHaveTilt) {
3675 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3676 mRawPointerAxes.tiltX.maxValue);
3677 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3678 mRawPointerAxes.tiltY.maxValue);
3679 mTiltXScale = M_PI / 180;
3680 mTiltYScale = M_PI / 180;
3681
3682 mOrientedRanges.haveTilt = true;
3683
3684 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3685 mOrientedRanges.tilt.source = mSource;
3686 mOrientedRanges.tilt.min = 0;
3687 mOrientedRanges.tilt.max = M_PI_2;
3688 mOrientedRanges.tilt.flat = 0;
3689 mOrientedRanges.tilt.fuzz = 0;
3690 mOrientedRanges.tilt.resolution = 0;
3691 }
3692
3693 // Orientation
3694 mOrientationScale = 0;
3695 if (mHaveTilt) {
3696 mOrientedRanges.haveOrientation = true;
3697
3698 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3699 mOrientedRanges.orientation.source = mSource;
3700 mOrientedRanges.orientation.min = -M_PI;
3701 mOrientedRanges.orientation.max = M_PI;
3702 mOrientedRanges.orientation.flat = 0;
3703 mOrientedRanges.orientation.fuzz = 0;
3704 mOrientedRanges.orientation.resolution = 0;
3705 } else if (mCalibration.orientationCalibration !=
3706 Calibration::ORIENTATION_CALIBRATION_NONE) {
3707 if (mCalibration.orientationCalibration
3708 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3709 if (mRawPointerAxes.orientation.valid) {
3710 if (mRawPointerAxes.orientation.maxValue > 0) {
3711 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3712 } else if (mRawPointerAxes.orientation.minValue < 0) {
3713 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3714 } else {
3715 mOrientationScale = 0;
3716 }
3717 }
3718 }
3719
3720 mOrientedRanges.haveOrientation = true;
3721
3722 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3723 mOrientedRanges.orientation.source = mSource;
3724 mOrientedRanges.orientation.min = -M_PI_2;
3725 mOrientedRanges.orientation.max = M_PI_2;
3726 mOrientedRanges.orientation.flat = 0;
3727 mOrientedRanges.orientation.fuzz = 0;
3728 mOrientedRanges.orientation.resolution = 0;
3729 }
3730
3731 // Distance
3732 mDistanceScale = 0;
3733 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3734 if (mCalibration.distanceCalibration
3735 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3736 if (mCalibration.haveDistanceScale) {
3737 mDistanceScale = mCalibration.distanceScale;
3738 } else {
3739 mDistanceScale = 1.0f;
3740 }
3741 }
3742
3743 mOrientedRanges.haveDistance = true;
3744
3745 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3746 mOrientedRanges.distance.source = mSource;
3747 mOrientedRanges.distance.min =
3748 mRawPointerAxes.distance.minValue * mDistanceScale;
3749 mOrientedRanges.distance.max =
3750 mRawPointerAxes.distance.maxValue * mDistanceScale;
3751 mOrientedRanges.distance.flat = 0;
3752 mOrientedRanges.distance.fuzz =
3753 mRawPointerAxes.distance.fuzz * mDistanceScale;
3754 mOrientedRanges.distance.resolution = 0;
3755 }
3756
3757 // Compute oriented precision, scales and ranges.
3758 // Note that the maximum value reported is an inclusive maximum value so it is one
3759 // unit less than the total width or height of surface.
3760 switch (mSurfaceOrientation) {
3761 case DISPLAY_ORIENTATION_90:
3762 case DISPLAY_ORIENTATION_270:
3763 mOrientedXPrecision = mYPrecision;
3764 mOrientedYPrecision = mXPrecision;
3765
3766 mOrientedRanges.x.min = mYTranslate;
3767 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3768 mOrientedRanges.x.flat = 0;
3769 mOrientedRanges.x.fuzz = 0;
3770 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3771
3772 mOrientedRanges.y.min = mXTranslate;
3773 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3774 mOrientedRanges.y.flat = 0;
3775 mOrientedRanges.y.fuzz = 0;
3776 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3777 break;
3778
3779 default:
3780 mOrientedXPrecision = mXPrecision;
3781 mOrientedYPrecision = mYPrecision;
3782
3783 mOrientedRanges.x.min = mXTranslate;
3784 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3785 mOrientedRanges.x.flat = 0;
3786 mOrientedRanges.x.fuzz = 0;
3787 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3788
3789 mOrientedRanges.y.min = mYTranslate;
3790 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3791 mOrientedRanges.y.flat = 0;
3792 mOrientedRanges.y.fuzz = 0;
3793 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3794 break;
3795 }
3796
Jason Gerecke71b16e82014-03-10 09:47:59 -07003797 // Location
3798 updateAffineTransformation();
3799
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 if (mDeviceMode == DEVICE_MODE_POINTER) {
3801 // Compute pointer gesture detection parameters.
3802 float rawDiagonal = hypotf(rawWidth, rawHeight);
3803 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3804
3805 // Scale movements such that one whole swipe of the touch pad covers a
3806 // given area relative to the diagonal size of the display when no acceleration
3807 // is applied.
3808 // Assume that the touch pad has a square aspect ratio such that movements in
3809 // X and Y of the same number of raw units cover the same physical distance.
3810 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3811 * displayDiagonal / rawDiagonal;
3812 mPointerYMovementScale = mPointerXMovementScale;
3813
3814 // Scale zooms to cover a smaller range of the display than movements do.
3815 // This value determines the area around the pointer that is affected by freeform
3816 // pointer gestures.
3817 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3818 * displayDiagonal / rawDiagonal;
3819 mPointerYZoomScale = mPointerXZoomScale;
3820
3821 // Max width between pointers to detect a swipe gesture is more than some fraction
3822 // of the diagonal axis of the touch pad. Touches that are wider than this are
3823 // translated into freeform gestures.
3824 mPointerGestureMaxSwipeWidth =
3825 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3826
3827 // Abort current pointer usages because the state has changed.
3828 abortPointerUsage(when, 0 /*policyFlags*/);
3829 }
3830
3831 // Inform the dispatcher about the changes.
3832 *outResetNeeded = true;
3833 bumpGeneration();
3834 }
3835}
3836
3837void TouchInputMapper::dumpSurface(String8& dump) {
3838 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3839 "logicalFrame=[%d, %d, %d, %d], "
3840 "physicalFrame=[%d, %d, %d, %d], "
3841 "deviceSize=[%d, %d]\n",
3842 mViewport.displayId, mViewport.orientation,
3843 mViewport.logicalLeft, mViewport.logicalTop,
3844 mViewport.logicalRight, mViewport.logicalBottom,
3845 mViewport.physicalLeft, mViewport.physicalTop,
3846 mViewport.physicalRight, mViewport.physicalBottom,
3847 mViewport.deviceWidth, mViewport.deviceHeight);
3848
3849 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3850 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3851 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3852 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3853 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3854}
3855
3856void TouchInputMapper::configureVirtualKeys() {
3857 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3858 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3859
3860 mVirtualKeys.clear();
3861
3862 if (virtualKeyDefinitions.size() == 0) {
3863 return;
3864 }
3865
3866 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3867
3868 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3869 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3870 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3871 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3872
3873 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3874 const VirtualKeyDefinition& virtualKeyDefinition =
3875 virtualKeyDefinitions[i];
3876
3877 mVirtualKeys.add();
3878 VirtualKey& virtualKey = mVirtualKeys.editTop();
3879
3880 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3881 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003882 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003884 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3885 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3887 virtualKey.scanCode);
3888 mVirtualKeys.pop(); // drop the key
3889 continue;
3890 }
3891
3892 virtualKey.keyCode = keyCode;
3893 virtualKey.flags = flags;
3894
3895 // convert the key definition's display coordinates into touch coordinates for a hit box
3896 int32_t halfWidth = virtualKeyDefinition.width / 2;
3897 int32_t halfHeight = virtualKeyDefinition.height / 2;
3898
3899 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3900 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3901 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3902 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3903 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3904 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3905 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3906 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3907 }
3908}
3909
3910void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3911 if (!mVirtualKeys.isEmpty()) {
3912 dump.append(INDENT3 "Virtual Keys:\n");
3913
3914 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3915 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003916 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3918 i, virtualKey.scanCode, virtualKey.keyCode,
3919 virtualKey.hitLeft, virtualKey.hitRight,
3920 virtualKey.hitTop, virtualKey.hitBottom);
3921 }
3922 }
3923}
3924
3925void TouchInputMapper::parseCalibration() {
3926 const PropertyMap& in = getDevice()->getConfiguration();
3927 Calibration& out = mCalibration;
3928
3929 // Size
3930 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3931 String8 sizeCalibrationString;
3932 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3933 if (sizeCalibrationString == "none") {
3934 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3935 } else if (sizeCalibrationString == "geometric") {
3936 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3937 } else if (sizeCalibrationString == "diameter") {
3938 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3939 } else if (sizeCalibrationString == "box") {
3940 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3941 } else if (sizeCalibrationString == "area") {
3942 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3943 } else if (sizeCalibrationString != "default") {
3944 ALOGW("Invalid value for touch.size.calibration: '%s'",
3945 sizeCalibrationString.string());
3946 }
3947 }
3948
3949 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3950 out.sizeScale);
3951 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3952 out.sizeBias);
3953 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3954 out.sizeIsSummed);
3955
3956 // Pressure
3957 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3958 String8 pressureCalibrationString;
3959 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3960 if (pressureCalibrationString == "none") {
3961 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3962 } else if (pressureCalibrationString == "physical") {
3963 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3964 } else if (pressureCalibrationString == "amplitude") {
3965 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3966 } else if (pressureCalibrationString != "default") {
3967 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3968 pressureCalibrationString.string());
3969 }
3970 }
3971
3972 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3973 out.pressureScale);
3974
3975 // Orientation
3976 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3977 String8 orientationCalibrationString;
3978 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3979 if (orientationCalibrationString == "none") {
3980 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3981 } else if (orientationCalibrationString == "interpolated") {
3982 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3983 } else if (orientationCalibrationString == "vector") {
3984 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3985 } else if (orientationCalibrationString != "default") {
3986 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3987 orientationCalibrationString.string());
3988 }
3989 }
3990
3991 // Distance
3992 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3993 String8 distanceCalibrationString;
3994 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3995 if (distanceCalibrationString == "none") {
3996 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3997 } else if (distanceCalibrationString == "scaled") {
3998 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3999 } else if (distanceCalibrationString != "default") {
4000 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4001 distanceCalibrationString.string());
4002 }
4003 }
4004
4005 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4006 out.distanceScale);
4007
4008 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4009 String8 coverageCalibrationString;
4010 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4011 if (coverageCalibrationString == "none") {
4012 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4013 } else if (coverageCalibrationString == "box") {
4014 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4015 } else if (coverageCalibrationString != "default") {
4016 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4017 coverageCalibrationString.string());
4018 }
4019 }
4020}
4021
4022void TouchInputMapper::resolveCalibration() {
4023 // Size
4024 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4025 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4026 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4027 }
4028 } else {
4029 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4030 }
4031
4032 // Pressure
4033 if (mRawPointerAxes.pressure.valid) {
4034 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4035 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4036 }
4037 } else {
4038 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4039 }
4040
4041 // Orientation
4042 if (mRawPointerAxes.orientation.valid) {
4043 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4044 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4045 }
4046 } else {
4047 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4048 }
4049
4050 // Distance
4051 if (mRawPointerAxes.distance.valid) {
4052 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4053 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4054 }
4055 } else {
4056 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4057 }
4058
4059 // Coverage
4060 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4061 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4062 }
4063}
4064
4065void TouchInputMapper::dumpCalibration(String8& dump) {
4066 dump.append(INDENT3 "Calibration:\n");
4067
4068 // Size
4069 switch (mCalibration.sizeCalibration) {
4070 case Calibration::SIZE_CALIBRATION_NONE:
4071 dump.append(INDENT4 "touch.size.calibration: none\n");
4072 break;
4073 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4074 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4075 break;
4076 case Calibration::SIZE_CALIBRATION_DIAMETER:
4077 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4078 break;
4079 case Calibration::SIZE_CALIBRATION_BOX:
4080 dump.append(INDENT4 "touch.size.calibration: box\n");
4081 break;
4082 case Calibration::SIZE_CALIBRATION_AREA:
4083 dump.append(INDENT4 "touch.size.calibration: area\n");
4084 break;
4085 default:
4086 ALOG_ASSERT(false);
4087 }
4088
4089 if (mCalibration.haveSizeScale) {
4090 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4091 mCalibration.sizeScale);
4092 }
4093
4094 if (mCalibration.haveSizeBias) {
4095 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4096 mCalibration.sizeBias);
4097 }
4098
4099 if (mCalibration.haveSizeIsSummed) {
4100 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4101 toString(mCalibration.sizeIsSummed));
4102 }
4103
4104 // Pressure
4105 switch (mCalibration.pressureCalibration) {
4106 case Calibration::PRESSURE_CALIBRATION_NONE:
4107 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4108 break;
4109 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4110 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4111 break;
4112 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4113 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4114 break;
4115 default:
4116 ALOG_ASSERT(false);
4117 }
4118
4119 if (mCalibration.havePressureScale) {
4120 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4121 mCalibration.pressureScale);
4122 }
4123
4124 // Orientation
4125 switch (mCalibration.orientationCalibration) {
4126 case Calibration::ORIENTATION_CALIBRATION_NONE:
4127 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4128 break;
4129 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4130 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4131 break;
4132 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4133 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4134 break;
4135 default:
4136 ALOG_ASSERT(false);
4137 }
4138
4139 // Distance
4140 switch (mCalibration.distanceCalibration) {
4141 case Calibration::DISTANCE_CALIBRATION_NONE:
4142 dump.append(INDENT4 "touch.distance.calibration: none\n");
4143 break;
4144 case Calibration::DISTANCE_CALIBRATION_SCALED:
4145 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4146 break;
4147 default:
4148 ALOG_ASSERT(false);
4149 }
4150
4151 if (mCalibration.haveDistanceScale) {
4152 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4153 mCalibration.distanceScale);
4154 }
4155
4156 switch (mCalibration.coverageCalibration) {
4157 case Calibration::COVERAGE_CALIBRATION_NONE:
4158 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4159 break;
4160 case Calibration::COVERAGE_CALIBRATION_BOX:
4161 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4162 break;
4163 default:
4164 ALOG_ASSERT(false);
4165 }
4166}
4167
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004168void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4169 dump.append(INDENT3 "Affine Transformation:\n");
4170
4171 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4172 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4173 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4174 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4175 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4176 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4177}
4178
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004179void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004180 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4181 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004182}
4183
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184void TouchInputMapper::reset(nsecs_t when) {
4185 mCursorButtonAccumulator.reset(getDevice());
4186 mCursorScrollAccumulator.reset(getDevice());
4187 mTouchButtonAccumulator.reset(getDevice());
4188
4189 mPointerVelocityControl.reset();
4190 mWheelXVelocityControl.reset();
4191 mWheelYVelocityControl.reset();
4192
Michael Wright842500e2015-03-13 17:32:02 -07004193 mRawStatesPending.clear();
4194 mCurrentRawState.clear();
4195 mCurrentCookedState.clear();
4196 mLastRawState.clear();
4197 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 mPointerUsage = POINTER_USAGE_NONE;
4199 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004200 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004201 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 mDownTime = 0;
4203
4204 mCurrentVirtualKey.down = false;
4205
4206 mPointerGesture.reset();
4207 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004208 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209
4210 if (mPointerController != NULL) {
4211 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4212 mPointerController->clearSpots();
4213 }
4214
4215 InputMapper::reset(when);
4216}
4217
Michael Wright842500e2015-03-13 17:32:02 -07004218void TouchInputMapper::resetExternalStylus() {
4219 mExternalStylusState.clear();
4220 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004221 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004222 mExternalStylusDataPending = false;
4223}
4224
Michael Wright43fd19f2015-04-21 19:02:58 +01004225void TouchInputMapper::clearStylusDataPendingFlags() {
4226 mExternalStylusDataPending = false;
4227 mExternalStylusFusionTimeout = LLONG_MAX;
4228}
4229
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230void TouchInputMapper::process(const RawEvent* rawEvent) {
4231 mCursorButtonAccumulator.process(rawEvent);
4232 mCursorScrollAccumulator.process(rawEvent);
4233 mTouchButtonAccumulator.process(rawEvent);
4234
4235 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4236 sync(rawEvent->when);
4237 }
4238}
4239
4240void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004241 const RawState* last = mRawStatesPending.isEmpty() ?
4242 &mCurrentRawState : &mRawStatesPending.top();
4243
4244 // Push a new state.
4245 mRawStatesPending.push();
4246 RawState* next = &mRawStatesPending.editTop();
4247 next->clear();
4248 next->when = when;
4249
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004251 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 | mCursorButtonAccumulator.getButtonState();
4253
Michael Wright842500e2015-03-13 17:32:02 -07004254 // Sync scroll
4255 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4256 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 mCursorScrollAccumulator.finishSync();
4258
Michael Wright842500e2015-03-13 17:32:02 -07004259 // Sync touch
4260 syncTouch(when, next);
4261
4262 // Assign pointer ids.
4263 if (!mHavePointerIds) {
4264 assignPointerIds(last, next);
4265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
4267#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004268 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4269 "hovering ids 0x%08x -> 0x%08x",
4270 last->rawPointerData.pointerCount,
4271 next->rawPointerData.pointerCount,
4272 last->rawPointerData.touchingIdBits.value,
4273 next->rawPointerData.touchingIdBits.value,
4274 last->rawPointerData.hoveringIdBits.value,
4275 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276#endif
4277
Michael Wright842500e2015-03-13 17:32:02 -07004278 processRawTouches(false /*timeout*/);
4279}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Michael Wright842500e2015-03-13 17:32:02 -07004281void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4283 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004284 mCurrentRawState.clear();
4285 mRawStatesPending.clear();
4286 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 }
4288
Michael Wright842500e2015-03-13 17:32:02 -07004289 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4290 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4291 // touching the current state will only observe the events that have been dispatched to the
4292 // rest of the pipeline.
4293 const size_t N = mRawStatesPending.size();
4294 size_t count;
4295 for(count = 0; count < N; count++) {
4296 const RawState& next = mRawStatesPending[count];
4297
4298 // A failure to assign the stylus id means that we're waiting on stylus data
4299 // and so should defer the rest of the pipeline.
4300 if (assignExternalStylusId(next, timeout)) {
4301 break;
4302 }
4303
4304 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004305 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004306 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004307 if (mCurrentRawState.when < mLastRawState.when) {
4308 mCurrentRawState.when = mLastRawState.when;
4309 }
Michael Wright842500e2015-03-13 17:32:02 -07004310 cookAndDispatch(mCurrentRawState.when);
4311 }
4312 if (count != 0) {
4313 mRawStatesPending.removeItemsAt(0, count);
4314 }
4315
Michael Wright842500e2015-03-13 17:32:02 -07004316 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004317 if (timeout) {
4318 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4319 clearStylusDataPendingFlags();
4320 mCurrentRawState.copyFrom(mLastRawState);
4321#if DEBUG_STYLUS_FUSION
4322 ALOGD("Timeout expired, synthesizing event with new stylus data");
4323#endif
4324 cookAndDispatch(when);
4325 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4326 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4327 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4328 }
Michael Wright842500e2015-03-13 17:32:02 -07004329 }
4330}
4331
4332void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4333 // Always start with a clean state.
4334 mCurrentCookedState.clear();
4335
4336 // Apply stylus buttons to current raw state.
4337 applyExternalStylusButtonState(when);
4338
4339 // Handle policy on initial down or hover events.
4340 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4341 && mCurrentRawState.rawPointerData.pointerCount != 0;
4342
4343 uint32_t policyFlags = 0;
4344 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4345 if (initialDown || buttonsPressed) {
4346 // If this is a touch screen, hide the pointer on an initial down.
4347 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4348 getContext()->fadePointer();
4349 }
4350
4351 if (mParameters.wake) {
4352 policyFlags |= POLICY_FLAG_WAKE;
4353 }
4354 }
4355
4356 // Consume raw off-screen touches before cooking pointer data.
4357 // If touches are consumed, subsequent code will not receive any pointer data.
4358 if (consumeRawTouches(when, policyFlags)) {
4359 mCurrentRawState.rawPointerData.clear();
4360 }
4361
4362 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4363 // with cooked pointer data that has the same ids and indices as the raw data.
4364 // The following code can use either the raw or cooked data, as needed.
4365 cookPointerData();
4366
4367 // Apply stylus pressure to current cooked state.
4368 applyExternalStylusTouchState(when);
4369
4370 // Synthesize key down from raw buttons if needed.
4371 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004372 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004373
4374 // Dispatch the touches either directly or by translation through a pointer on screen.
4375 if (mDeviceMode == DEVICE_MODE_POINTER) {
4376 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4377 !idBits.isEmpty(); ) {
4378 uint32_t id = idBits.clearFirstMarkedBit();
4379 const RawPointerData::Pointer& pointer =
4380 mCurrentRawState.rawPointerData.pointerForId(id);
4381 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4382 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4383 mCurrentCookedState.stylusIdBits.markBit(id);
4384 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4385 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4386 mCurrentCookedState.fingerIdBits.markBit(id);
4387 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4388 mCurrentCookedState.mouseIdBits.markBit(id);
4389 }
4390 }
4391 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4392 !idBits.isEmpty(); ) {
4393 uint32_t id = idBits.clearFirstMarkedBit();
4394 const RawPointerData::Pointer& pointer =
4395 mCurrentRawState.rawPointerData.pointerForId(id);
4396 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4397 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4398 mCurrentCookedState.stylusIdBits.markBit(id);
4399 }
4400 }
4401
4402 // Stylus takes precedence over all tools, then mouse, then finger.
4403 PointerUsage pointerUsage = mPointerUsage;
4404 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4405 mCurrentCookedState.mouseIdBits.clear();
4406 mCurrentCookedState.fingerIdBits.clear();
4407 pointerUsage = POINTER_USAGE_STYLUS;
4408 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4409 mCurrentCookedState.fingerIdBits.clear();
4410 pointerUsage = POINTER_USAGE_MOUSE;
4411 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4412 isPointerDown(mCurrentRawState.buttonState)) {
4413 pointerUsage = POINTER_USAGE_GESTURES;
4414 }
4415
4416 dispatchPointerUsage(when, policyFlags, pointerUsage);
4417 } else {
4418 if (mDeviceMode == DEVICE_MODE_DIRECT
4419 && mConfig.showTouches && mPointerController != NULL) {
4420 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4421 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4422
4423 mPointerController->setButtonState(mCurrentRawState.buttonState);
4424 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4425 mCurrentCookedState.cookedPointerData.idToIndex,
4426 mCurrentCookedState.cookedPointerData.touchingIdBits);
4427 }
4428
Michael Wright8e812822015-06-22 16:18:21 +01004429 if (!mCurrentMotionAborted) {
4430 dispatchButtonRelease(when, policyFlags);
4431 dispatchHoverExit(when, policyFlags);
4432 dispatchTouches(when, policyFlags);
4433 dispatchHoverEnterAndMove(when, policyFlags);
4434 dispatchButtonPress(when, policyFlags);
4435 }
4436
4437 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4438 mCurrentMotionAborted = false;
4439 }
Michael Wright842500e2015-03-13 17:32:02 -07004440 }
4441
4442 // Synthesize key up from raw buttons if needed.
4443 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004444 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445
4446 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004447 mCurrentRawState.rawVScroll = 0;
4448 mCurrentRawState.rawHScroll = 0;
4449
4450 // Copy current touch to last touch in preparation for the next cycle.
4451 mLastRawState.copyFrom(mCurrentRawState);
4452 mLastCookedState.copyFrom(mCurrentCookedState);
4453}
4454
4455void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004456 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004457 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4458 }
4459}
4460
4461void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004462 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4463 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004464
Michael Wright53dca3a2015-04-23 17:39:53 +01004465 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4466 float pressure = mExternalStylusState.pressure;
4467 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4468 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4469 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4470 }
4471 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4472 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4473
4474 PointerProperties& properties =
4475 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004476 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4477 properties.toolType = mExternalStylusState.toolType;
4478 }
4479 }
4480}
4481
4482bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4483 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4484 return false;
4485 }
4486
4487 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4488 && state.rawPointerData.pointerCount != 0;
4489 if (initialDown) {
4490 if (mExternalStylusState.pressure != 0.0f) {
4491#if DEBUG_STYLUS_FUSION
4492 ALOGD("Have both stylus and touch data, beginning fusion");
4493#endif
4494 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4495 } else if (timeout) {
4496#if DEBUG_STYLUS_FUSION
4497 ALOGD("Timeout expired, assuming touch is not a stylus.");
4498#endif
4499 resetExternalStylus();
4500 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004501 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4502 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004503 }
4504#if DEBUG_STYLUS_FUSION
4505 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004506 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004507#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004508 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004509 return true;
4510 }
4511 }
4512
4513 // Check if the stylus pointer has gone up.
4514 if (mExternalStylusId != -1 &&
4515 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4516#if DEBUG_STYLUS_FUSION
4517 ALOGD("Stylus pointer is going up");
4518#endif
4519 mExternalStylusId = -1;
4520 }
4521
4522 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523}
4524
4525void TouchInputMapper::timeoutExpired(nsecs_t when) {
4526 if (mDeviceMode == DEVICE_MODE_POINTER) {
4527 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4528 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4529 }
Michael Wright842500e2015-03-13 17:32:02 -07004530 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004531 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004532 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004533 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4534 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004535 }
4536 }
4537}
4538
4539void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004540 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004541 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004542 // We're either in the middle of a fused stream of data or we're waiting on data before
4543 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4544 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004545 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004546 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 }
4548}
4549
4550bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4551 // Check for release of a virtual key.
4552 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004553 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 // Pointer went up while virtual key was down.
4555 mCurrentVirtualKey.down = false;
4556 if (!mCurrentVirtualKey.ignored) {
4557#if DEBUG_VIRTUAL_KEYS
4558 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4559 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4560#endif
4561 dispatchVirtualKey(when, policyFlags,
4562 AKEY_EVENT_ACTION_UP,
4563 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4564 }
4565 return true;
4566 }
4567
Michael Wright842500e2015-03-13 17:32:02 -07004568 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4569 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4570 const RawPointerData::Pointer& pointer =
4571 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4573 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4574 // Pointer is still within the space of the virtual key.
4575 return true;
4576 }
4577 }
4578
4579 // Pointer left virtual key area or another pointer also went down.
4580 // Send key cancellation but do not consume the touch yet.
4581 // This is useful when the user swipes through from the virtual key area
4582 // into the main display surface.
4583 mCurrentVirtualKey.down = false;
4584 if (!mCurrentVirtualKey.ignored) {
4585#if DEBUG_VIRTUAL_KEYS
4586 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4587 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4588#endif
4589 dispatchVirtualKey(when, policyFlags,
4590 AKEY_EVENT_ACTION_UP,
4591 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4592 | AKEY_EVENT_FLAG_CANCELED);
4593 }
4594 }
4595
Michael Wright842500e2015-03-13 17:32:02 -07004596 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4597 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004599 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4600 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4602 // If exactly one pointer went down, check for virtual key hit.
4603 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004604 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4606 if (virtualKey) {
4607 mCurrentVirtualKey.down = true;
4608 mCurrentVirtualKey.downTime = when;
4609 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4610 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4611 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4612 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4613
4614 if (!mCurrentVirtualKey.ignored) {
4615#if DEBUG_VIRTUAL_KEYS
4616 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4617 mCurrentVirtualKey.keyCode,
4618 mCurrentVirtualKey.scanCode);
4619#endif
4620 dispatchVirtualKey(when, policyFlags,
4621 AKEY_EVENT_ACTION_DOWN,
4622 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4623 }
4624 }
4625 }
4626 return true;
4627 }
4628 }
4629
4630 // Disable all virtual key touches that happen within a short time interval of the
4631 // most recent touch within the screen area. The idea is to filter out stray
4632 // virtual key presses when interacting with the touch screen.
4633 //
4634 // Problems we're trying to solve:
4635 //
4636 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4637 // virtual key area that is implemented by a separate touch panel and accidentally
4638 // triggers a virtual key.
4639 //
4640 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4641 // area and accidentally triggers a virtual key. This often happens when virtual keys
4642 // are layed out below the screen near to where the on screen keyboard's space bar
4643 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004644 if (mConfig.virtualKeyQuietTime > 0 &&
4645 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4647 }
4648 return false;
4649}
4650
4651void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4652 int32_t keyEventAction, int32_t keyEventFlags) {
4653 int32_t keyCode = mCurrentVirtualKey.keyCode;
4654 int32_t scanCode = mCurrentVirtualKey.scanCode;
4655 nsecs_t downTime = mCurrentVirtualKey.downTime;
4656 int32_t metaState = mContext->getGlobalMetaState();
4657 policyFlags |= POLICY_FLAG_VIRTUAL;
4658
4659 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4660 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4661 getListener()->notifyKey(&args);
4662}
4663
Michael Wright8e812822015-06-22 16:18:21 +01004664void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4665 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4666 if (!currentIdBits.isEmpty()) {
4667 int32_t metaState = getContext()->getGlobalMetaState();
4668 int32_t buttonState = mCurrentCookedState.buttonState;
4669 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4670 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4671 mCurrentCookedState.cookedPointerData.pointerProperties,
4672 mCurrentCookedState.cookedPointerData.pointerCoords,
4673 mCurrentCookedState.cookedPointerData.idToIndex,
4674 currentIdBits, -1,
4675 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4676 mCurrentMotionAborted = true;
4677 }
4678}
4679
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004681 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4682 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004684 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685
4686 if (currentIdBits == lastIdBits) {
4687 if (!currentIdBits.isEmpty()) {
4688 // No pointer id changes so this is a move event.
4689 // The listener takes care of batching moves so we don't have to deal with that here.
4690 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004691 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004693 mCurrentCookedState.cookedPointerData.pointerProperties,
4694 mCurrentCookedState.cookedPointerData.pointerCoords,
4695 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 currentIdBits, -1,
4697 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4698 }
4699 } else {
4700 // There may be pointers going up and pointers going down and pointers moving
4701 // all at the same time.
4702 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4703 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4704 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4705 BitSet32 dispatchedIdBits(lastIdBits.value);
4706
4707 // Update last coordinates of pointers that have moved so that we observe the new
4708 // pointer positions at the same time as other pointers that have just gone up.
4709 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004710 mCurrentCookedState.cookedPointerData.pointerProperties,
4711 mCurrentCookedState.cookedPointerData.pointerCoords,
4712 mCurrentCookedState.cookedPointerData.idToIndex,
4713 mLastCookedState.cookedPointerData.pointerProperties,
4714 mLastCookedState.cookedPointerData.pointerCoords,
4715 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004717 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 moveNeeded = true;
4719 }
4720
4721 // Dispatch pointer up events.
4722 while (!upIdBits.isEmpty()) {
4723 uint32_t upId = upIdBits.clearFirstMarkedBit();
4724
4725 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004726 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004727 mLastCookedState.cookedPointerData.pointerProperties,
4728 mLastCookedState.cookedPointerData.pointerCoords,
4729 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004730 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 dispatchedIdBits.clearBit(upId);
4732 }
4733
4734 // Dispatch move events if any of the remaining pointers moved from their old locations.
4735 // Although applications receive new locations as part of individual pointer up
4736 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004737 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4739 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004740 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004741 mCurrentCookedState.cookedPointerData.pointerProperties,
4742 mCurrentCookedState.cookedPointerData.pointerCoords,
4743 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004744 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 }
4746
4747 // Dispatch pointer down events using the new pointer locations.
4748 while (!downIdBits.isEmpty()) {
4749 uint32_t downId = downIdBits.clearFirstMarkedBit();
4750 dispatchedIdBits.markBit(downId);
4751
4752 if (dispatchedIdBits.count() == 1) {
4753 // First pointer is going down. Set down time.
4754 mDownTime = when;
4755 }
4756
4757 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004758 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004759 mCurrentCookedState.cookedPointerData.pointerProperties,
4760 mCurrentCookedState.cookedPointerData.pointerCoords,
4761 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004762 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 }
4764 }
4765}
4766
4767void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4768 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004769 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4770 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 int32_t metaState = getContext()->getGlobalMetaState();
4772 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004773 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004774 mLastCookedState.cookedPointerData.pointerProperties,
4775 mLastCookedState.cookedPointerData.pointerCoords,
4776 mLastCookedState.cookedPointerData.idToIndex,
4777 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4779 mSentHoverEnter = false;
4780 }
4781}
4782
4783void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004784 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4785 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 int32_t metaState = getContext()->getGlobalMetaState();
4787 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004788 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004789 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004790 mCurrentCookedState.cookedPointerData.pointerProperties,
4791 mCurrentCookedState.cookedPointerData.pointerCoords,
4792 mCurrentCookedState.cookedPointerData.idToIndex,
4793 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4795 mSentHoverEnter = true;
4796 }
4797
4798 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004799 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004800 mCurrentRawState.buttonState, 0,
4801 mCurrentCookedState.cookedPointerData.pointerProperties,
4802 mCurrentCookedState.cookedPointerData.pointerCoords,
4803 mCurrentCookedState.cookedPointerData.idToIndex,
4804 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4806 }
4807}
4808
Michael Wright7b159c92015-05-14 14:48:03 +01004809void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4810 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4811 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4812 const int32_t metaState = getContext()->getGlobalMetaState();
4813 int32_t buttonState = mLastCookedState.buttonState;
4814 while (!releasedButtons.isEmpty()) {
4815 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4816 buttonState &= ~actionButton;
4817 dispatchMotion(when, policyFlags, mSource,
4818 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4819 0, metaState, buttonState, 0,
4820 mCurrentCookedState.cookedPointerData.pointerProperties,
4821 mCurrentCookedState.cookedPointerData.pointerCoords,
4822 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4823 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4824 }
4825}
4826
4827void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4828 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4829 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4830 const int32_t metaState = getContext()->getGlobalMetaState();
4831 int32_t buttonState = mLastCookedState.buttonState;
4832 while (!pressedButtons.isEmpty()) {
4833 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4834 buttonState |= actionButton;
4835 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4836 0, metaState, buttonState, 0,
4837 mCurrentCookedState.cookedPointerData.pointerProperties,
4838 mCurrentCookedState.cookedPointerData.pointerCoords,
4839 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4840 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4841 }
4842}
4843
4844const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4845 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4846 return cookedPointerData.touchingIdBits;
4847 }
4848 return cookedPointerData.hoveringIdBits;
4849}
4850
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004852 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853
Michael Wright842500e2015-03-13 17:32:02 -07004854 mCurrentCookedState.cookedPointerData.clear();
4855 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4856 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4857 mCurrentRawState.rawPointerData.hoveringIdBits;
4858 mCurrentCookedState.cookedPointerData.touchingIdBits =
4859 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860
Michael Wright7b159c92015-05-14 14:48:03 +01004861 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4862 mCurrentCookedState.buttonState = 0;
4863 } else {
4864 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4865 }
4866
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 // Walk through the the active pointers and map device coordinates onto
4868 // surface coordinates and adjust for display orientation.
4869 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004870 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871
4872 // Size
4873 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4874 switch (mCalibration.sizeCalibration) {
4875 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4876 case Calibration::SIZE_CALIBRATION_DIAMETER:
4877 case Calibration::SIZE_CALIBRATION_BOX:
4878 case Calibration::SIZE_CALIBRATION_AREA:
4879 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4880 touchMajor = in.touchMajor;
4881 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4882 toolMajor = in.toolMajor;
4883 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4884 size = mRawPointerAxes.touchMinor.valid
4885 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4886 } else if (mRawPointerAxes.touchMajor.valid) {
4887 toolMajor = touchMajor = in.touchMajor;
4888 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4889 ? in.touchMinor : in.touchMajor;
4890 size = mRawPointerAxes.touchMinor.valid
4891 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4892 } else if (mRawPointerAxes.toolMajor.valid) {
4893 touchMajor = toolMajor = in.toolMajor;
4894 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4895 ? in.toolMinor : in.toolMajor;
4896 size = mRawPointerAxes.toolMinor.valid
4897 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4898 } else {
4899 ALOG_ASSERT(false, "No touch or tool axes. "
4900 "Size calibration should have been resolved to NONE.");
4901 touchMajor = 0;
4902 touchMinor = 0;
4903 toolMajor = 0;
4904 toolMinor = 0;
4905 size = 0;
4906 }
4907
4908 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004909 uint32_t touchingCount =
4910 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 if (touchingCount > 1) {
4912 touchMajor /= touchingCount;
4913 touchMinor /= touchingCount;
4914 toolMajor /= touchingCount;
4915 toolMinor /= touchingCount;
4916 size /= touchingCount;
4917 }
4918 }
4919
4920 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4921 touchMajor *= mGeometricScale;
4922 touchMinor *= mGeometricScale;
4923 toolMajor *= mGeometricScale;
4924 toolMinor *= mGeometricScale;
4925 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4926 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4927 touchMinor = touchMajor;
4928 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4929 toolMinor = toolMajor;
4930 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4931 touchMinor = touchMajor;
4932 toolMinor = toolMajor;
4933 }
4934
4935 mCalibration.applySizeScaleAndBias(&touchMajor);
4936 mCalibration.applySizeScaleAndBias(&touchMinor);
4937 mCalibration.applySizeScaleAndBias(&toolMajor);
4938 mCalibration.applySizeScaleAndBias(&toolMinor);
4939 size *= mSizeScale;
4940 break;
4941 default:
4942 touchMajor = 0;
4943 touchMinor = 0;
4944 toolMajor = 0;
4945 toolMinor = 0;
4946 size = 0;
4947 break;
4948 }
4949
4950 // Pressure
4951 float pressure;
4952 switch (mCalibration.pressureCalibration) {
4953 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4954 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4955 pressure = in.pressure * mPressureScale;
4956 break;
4957 default:
4958 pressure = in.isHovering ? 0 : 1;
4959 break;
4960 }
4961
4962 // Tilt and Orientation
4963 float tilt;
4964 float orientation;
4965 if (mHaveTilt) {
4966 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4967 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4968 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4969 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4970 } else {
4971 tilt = 0;
4972
4973 switch (mCalibration.orientationCalibration) {
4974 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4975 orientation = in.orientation * mOrientationScale;
4976 break;
4977 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4978 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4979 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4980 if (c1 != 0 || c2 != 0) {
4981 orientation = atan2f(c1, c2) * 0.5f;
4982 float confidence = hypotf(c1, c2);
4983 float scale = 1.0f + confidence / 16.0f;
4984 touchMajor *= scale;
4985 touchMinor /= scale;
4986 toolMajor *= scale;
4987 toolMinor /= scale;
4988 } else {
4989 orientation = 0;
4990 }
4991 break;
4992 }
4993 default:
4994 orientation = 0;
4995 }
4996 }
4997
4998 // Distance
4999 float distance;
5000 switch (mCalibration.distanceCalibration) {
5001 case Calibration::DISTANCE_CALIBRATION_SCALED:
5002 distance = in.distance * mDistanceScale;
5003 break;
5004 default:
5005 distance = 0;
5006 }
5007
5008 // Coverage
5009 int32_t rawLeft, rawTop, rawRight, rawBottom;
5010 switch (mCalibration.coverageCalibration) {
5011 case Calibration::COVERAGE_CALIBRATION_BOX:
5012 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5013 rawRight = in.toolMinor & 0x0000ffff;
5014 rawBottom = in.toolMajor & 0x0000ffff;
5015 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5016 break;
5017 default:
5018 rawLeft = rawTop = rawRight = rawBottom = 0;
5019 break;
5020 }
5021
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005022 // Adjust X,Y coords for device calibration
5023 // TODO: Adjust coverage coords?
5024 float xTransformed = in.x, yTransformed = in.y;
5025 mAffineTransform.applyTo(xTransformed, yTransformed);
5026
5027 // Adjust X, Y, and coverage coords for surface orientation.
5028 float x, y;
5029 float left, top, right, bottom;
5030
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031 switch (mSurfaceOrientation) {
5032 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005033 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5034 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5036 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5037 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5038 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5039 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005040 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5042 }
5043 break;
5044 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005045 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5046 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5048 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5049 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5050 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5051 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005052 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5054 }
5055 break;
5056 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005057 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5058 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5060 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5061 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5062 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5063 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005064 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5066 }
5067 break;
5068 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005069 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5070 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5072 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5073 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5074 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5075 break;
5076 }
5077
5078 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005079 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 out.clear();
5081 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5082 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5083 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5084 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5085 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5086 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5087 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5088 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5089 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5090 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5091 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5092 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5093 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5094 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5095 } else {
5096 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5097 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5098 }
5099
5100 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005101 PointerProperties& properties =
5102 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 uint32_t id = in.id;
5104 properties.clear();
5105 properties.id = id;
5106 properties.toolType = in.toolType;
5107
5108 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005109 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
5111}
5112
5113void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5114 PointerUsage pointerUsage) {
5115 if (pointerUsage != mPointerUsage) {
5116 abortPointerUsage(when, policyFlags);
5117 mPointerUsage = pointerUsage;
5118 }
5119
5120 switch (mPointerUsage) {
5121 case POINTER_USAGE_GESTURES:
5122 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5123 break;
5124 case POINTER_USAGE_STYLUS:
5125 dispatchPointerStylus(when, policyFlags);
5126 break;
5127 case POINTER_USAGE_MOUSE:
5128 dispatchPointerMouse(when, policyFlags);
5129 break;
5130 default:
5131 break;
5132 }
5133}
5134
5135void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5136 switch (mPointerUsage) {
5137 case POINTER_USAGE_GESTURES:
5138 abortPointerGestures(when, policyFlags);
5139 break;
5140 case POINTER_USAGE_STYLUS:
5141 abortPointerStylus(when, policyFlags);
5142 break;
5143 case POINTER_USAGE_MOUSE:
5144 abortPointerMouse(when, policyFlags);
5145 break;
5146 default:
5147 break;
5148 }
5149
5150 mPointerUsage = POINTER_USAGE_NONE;
5151}
5152
5153void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5154 bool isTimeout) {
5155 // Update current gesture coordinates.
5156 bool cancelPreviousGesture, finishPreviousGesture;
5157 bool sendEvents = preparePointerGestures(when,
5158 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5159 if (!sendEvents) {
5160 return;
5161 }
5162 if (finishPreviousGesture) {
5163 cancelPreviousGesture = false;
5164 }
5165
5166 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005167 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5168 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 if (finishPreviousGesture || cancelPreviousGesture) {
5170 mPointerController->clearSpots();
5171 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005172
5173 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5174 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5175 mPointerGesture.currentGestureIdToIndex,
5176 mPointerGesture.currentGestureIdBits);
5177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 } else {
5179 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5180 }
5181
5182 // Show or hide the pointer if needed.
5183 switch (mPointerGesture.currentGestureMode) {
5184 case PointerGesture::NEUTRAL:
5185 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005186 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5187 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 // Remind the user of where the pointer is after finishing a gesture with spots.
5189 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5190 }
5191 break;
5192 case PointerGesture::TAP:
5193 case PointerGesture::TAP_DRAG:
5194 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5195 case PointerGesture::HOVER:
5196 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005197 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 // Unfade the pointer when the current gesture manipulates the
5199 // area directly under the pointer.
5200 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5201 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 case PointerGesture::FREEFORM:
5203 // Fade the pointer when the current gesture manipulates a different
5204 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005205 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5207 } else {
5208 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5209 }
5210 break;
5211 }
5212
5213 // Send events!
5214 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005215 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216
5217 // Update last coordinates of pointers that have moved so that we observe the new
5218 // pointer positions at the same time as other pointers that have just gone up.
5219 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5220 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5221 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5222 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5223 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5224 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5225 bool moveNeeded = false;
5226 if (down && !cancelPreviousGesture && !finishPreviousGesture
5227 && !mPointerGesture.lastGestureIdBits.isEmpty()
5228 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5229 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5230 & mPointerGesture.lastGestureIdBits.value);
5231 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5232 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5233 mPointerGesture.lastGestureProperties,
5234 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5235 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005236 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237 moveNeeded = true;
5238 }
5239 }
5240
5241 // Send motion events for all pointers that went up or were canceled.
5242 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5243 if (!dispatchedGestureIdBits.isEmpty()) {
5244 if (cancelPreviousGesture) {
5245 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005246 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 AMOTION_EVENT_EDGE_FLAG_NONE,
5248 mPointerGesture.lastGestureProperties,
5249 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005250 dispatchedGestureIdBits, -1, 0,
5251 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252
5253 dispatchedGestureIdBits.clear();
5254 } else {
5255 BitSet32 upGestureIdBits;
5256 if (finishPreviousGesture) {
5257 upGestureIdBits = dispatchedGestureIdBits;
5258 } else {
5259 upGestureIdBits.value = dispatchedGestureIdBits.value
5260 & ~mPointerGesture.currentGestureIdBits.value;
5261 }
5262 while (!upGestureIdBits.isEmpty()) {
5263 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5264
5265 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005266 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5268 mPointerGesture.lastGestureProperties,
5269 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5270 dispatchedGestureIdBits, id,
5271 0, 0, mPointerGesture.downTime);
5272
5273 dispatchedGestureIdBits.clearBit(id);
5274 }
5275 }
5276 }
5277
5278 // Send motion events for all pointers that moved.
5279 if (moveNeeded) {
5280 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005281 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5282 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 mPointerGesture.currentGestureProperties,
5284 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5285 dispatchedGestureIdBits, -1,
5286 0, 0, mPointerGesture.downTime);
5287 }
5288
5289 // Send motion events for all pointers that went down.
5290 if (down) {
5291 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5292 & ~dispatchedGestureIdBits.value);
5293 while (!downGestureIdBits.isEmpty()) {
5294 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5295 dispatchedGestureIdBits.markBit(id);
5296
5297 if (dispatchedGestureIdBits.count() == 1) {
5298 mPointerGesture.downTime = when;
5299 }
5300
5301 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005302 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 mPointerGesture.currentGestureProperties,
5304 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5305 dispatchedGestureIdBits, id,
5306 0, 0, mPointerGesture.downTime);
5307 }
5308 }
5309
5310 // Send motion events for hover.
5311 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5312 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005313 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5315 mPointerGesture.currentGestureProperties,
5316 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5317 mPointerGesture.currentGestureIdBits, -1,
5318 0, 0, mPointerGesture.downTime);
5319 } else if (dispatchedGestureIdBits.isEmpty()
5320 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5321 // Synthesize a hover move event after all pointers go up to indicate that
5322 // the pointer is hovering again even if the user is not currently touching
5323 // the touch pad. This ensures that a view will receive a fresh hover enter
5324 // event after a tap.
5325 float x, y;
5326 mPointerController->getPosition(&x, &y);
5327
5328 PointerProperties pointerProperties;
5329 pointerProperties.clear();
5330 pointerProperties.id = 0;
5331 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5332
5333 PointerCoords pointerCoords;
5334 pointerCoords.clear();
5335 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5336 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5337
5338 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005339 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5341 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5342 0, 0, mPointerGesture.downTime);
5343 getListener()->notifyMotion(&args);
5344 }
5345
5346 // Update state.
5347 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5348 if (!down) {
5349 mPointerGesture.lastGestureIdBits.clear();
5350 } else {
5351 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5352 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5353 uint32_t id = idBits.clearFirstMarkedBit();
5354 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5355 mPointerGesture.lastGestureProperties[index].copyFrom(
5356 mPointerGesture.currentGestureProperties[index]);
5357 mPointerGesture.lastGestureCoords[index].copyFrom(
5358 mPointerGesture.currentGestureCoords[index]);
5359 mPointerGesture.lastGestureIdToIndex[id] = index;
5360 }
5361 }
5362}
5363
5364void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5365 // Cancel previously dispatches pointers.
5366 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5367 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005368 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005370 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 AMOTION_EVENT_EDGE_FLAG_NONE,
5372 mPointerGesture.lastGestureProperties,
5373 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5374 mPointerGesture.lastGestureIdBits, -1,
5375 0, 0, mPointerGesture.downTime);
5376 }
5377
5378 // Reset the current pointer gesture.
5379 mPointerGesture.reset();
5380 mPointerVelocityControl.reset();
5381
5382 // Remove any current spots.
5383 if (mPointerController != NULL) {
5384 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5385 mPointerController->clearSpots();
5386 }
5387}
5388
5389bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5390 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5391 *outCancelPreviousGesture = false;
5392 *outFinishPreviousGesture = false;
5393
5394 // Handle TAP timeout.
5395 if (isTimeout) {
5396#if DEBUG_GESTURES
5397 ALOGD("Gestures: Processing timeout");
5398#endif
5399
5400 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5401 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5402 // The tap/drag timeout has not yet expired.
5403 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5404 + mConfig.pointerGestureTapDragInterval);
5405 } else {
5406 // The tap is finished.
5407#if DEBUG_GESTURES
5408 ALOGD("Gestures: TAP finished");
5409#endif
5410 *outFinishPreviousGesture = true;
5411
5412 mPointerGesture.activeGestureId = -1;
5413 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5414 mPointerGesture.currentGestureIdBits.clear();
5415
5416 mPointerVelocityControl.reset();
5417 return true;
5418 }
5419 }
5420
5421 // We did not handle this timeout.
5422 return false;
5423 }
5424
Michael Wright842500e2015-03-13 17:32:02 -07005425 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5426 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427
5428 // Update the velocity tracker.
5429 {
5430 VelocityTracker::Position positions[MAX_POINTERS];
5431 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005432 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005434 const RawPointerData::Pointer& pointer =
5435 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 positions[count].x = pointer.x * mPointerXMovementScale;
5437 positions[count].y = pointer.y * mPointerYMovementScale;
5438 }
5439 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005440 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 }
5442
5443 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5444 // to NEUTRAL, then we should not generate tap event.
5445 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5446 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5447 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5448 mPointerGesture.resetTap();
5449 }
5450
5451 // Pick a new active touch id if needed.
5452 // Choose an arbitrary pointer that just went down, if there is one.
5453 // Otherwise choose an arbitrary remaining pointer.
5454 // This guarantees we always have an active touch id when there is at least one pointer.
5455 // We keep the same active touch id for as long as possible.
5456 bool activeTouchChanged = false;
5457 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5458 int32_t activeTouchId = lastActiveTouchId;
5459 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005460 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 activeTouchChanged = true;
5462 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005463 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 mPointerGesture.firstTouchTime = when;
5465 }
Michael Wright842500e2015-03-13 17:32:02 -07005466 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005468 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005470 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 } else {
5472 activeTouchId = mPointerGesture.activeTouchId = -1;
5473 }
5474 }
5475
5476 // Determine whether we are in quiet time.
5477 bool isQuietTime = false;
5478 if (activeTouchId < 0) {
5479 mPointerGesture.resetQuietTime();
5480 } else {
5481 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5482 if (!isQuietTime) {
5483 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5484 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5485 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5486 && currentFingerCount < 2) {
5487 // Enter quiet time when exiting swipe or freeform state.
5488 // This is to prevent accidentally entering the hover state and flinging the
5489 // pointer when finishing a swipe and there is still one pointer left onscreen.
5490 isQuietTime = true;
5491 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5492 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005493 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494 // Enter quiet time when releasing the button and there are still two or more
5495 // fingers down. This may indicate that one finger was used to press the button
5496 // but it has not gone up yet.
5497 isQuietTime = true;
5498 }
5499 if (isQuietTime) {
5500 mPointerGesture.quietTime = when;
5501 }
5502 }
5503 }
5504
5505 // Switch states based on button and pointer state.
5506 if (isQuietTime) {
5507 // Case 1: Quiet time. (QUIET)
5508#if DEBUG_GESTURES
5509 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5510 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5511#endif
5512 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5513 *outFinishPreviousGesture = true;
5514 }
5515
5516 mPointerGesture.activeGestureId = -1;
5517 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5518 mPointerGesture.currentGestureIdBits.clear();
5519
5520 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005521 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5523 // The pointer follows the active touch point.
5524 // Emit DOWN, MOVE, UP events at the pointer location.
5525 //
5526 // Only the active touch matters; other fingers are ignored. This policy helps
5527 // to handle the case where the user places a second finger on the touch pad
5528 // to apply the necessary force to depress an integrated button below the surface.
5529 // We don't want the second finger to be delivered to applications.
5530 //
5531 // For this to work well, we need to make sure to track the pointer that is really
5532 // active. If the user first puts one finger down to click then adds another
5533 // finger to drag then the active pointer should switch to the finger that is
5534 // being dragged.
5535#if DEBUG_GESTURES
5536 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5537 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5538#endif
5539 // Reset state when just starting.
5540 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5541 *outFinishPreviousGesture = true;
5542 mPointerGesture.activeGestureId = 0;
5543 }
5544
5545 // Switch pointers if needed.
5546 // Find the fastest pointer and follow it.
5547 if (activeTouchId >= 0 && currentFingerCount > 1) {
5548 int32_t bestId = -1;
5549 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005550 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 uint32_t id = idBits.clearFirstMarkedBit();
5552 float vx, vy;
5553 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5554 float speed = hypotf(vx, vy);
5555 if (speed > bestSpeed) {
5556 bestId = id;
5557 bestSpeed = speed;
5558 }
5559 }
5560 }
5561 if (bestId >= 0 && bestId != activeTouchId) {
5562 mPointerGesture.activeTouchId = activeTouchId = bestId;
5563 activeTouchChanged = true;
5564#if DEBUG_GESTURES
5565 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5566 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5567#endif
5568 }
5569 }
5570
Jun Mukaifa1706a2015-12-03 01:14:46 -08005571 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005572 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005574 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005576 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005577 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5578 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579
5580 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5581 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5582
5583 // Move the pointer using a relative motion.
5584 // When using spots, the click will occur at the position of the anchor
5585 // spot and all other spots will move there.
5586 mPointerController->move(deltaX, deltaY);
5587 } else {
5588 mPointerVelocityControl.reset();
5589 }
5590
5591 float x, y;
5592 mPointerController->getPosition(&x, &y);
5593
5594 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5595 mPointerGesture.currentGestureIdBits.clear();
5596 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5597 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5598 mPointerGesture.currentGestureProperties[0].clear();
5599 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5600 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5601 mPointerGesture.currentGestureCoords[0].clear();
5602 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5603 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5604 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5605 } else if (currentFingerCount == 0) {
5606 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5607 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5608 *outFinishPreviousGesture = true;
5609 }
5610
5611 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5612 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5613 bool tapped = false;
5614 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5615 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5616 && lastFingerCount == 1) {
5617 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5618 float x, y;
5619 mPointerController->getPosition(&x, &y);
5620 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5621 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5622#if DEBUG_GESTURES
5623 ALOGD("Gestures: TAP");
5624#endif
5625
5626 mPointerGesture.tapUpTime = when;
5627 getContext()->requestTimeoutAtTime(when
5628 + mConfig.pointerGestureTapDragInterval);
5629
5630 mPointerGesture.activeGestureId = 0;
5631 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5632 mPointerGesture.currentGestureIdBits.clear();
5633 mPointerGesture.currentGestureIdBits.markBit(
5634 mPointerGesture.activeGestureId);
5635 mPointerGesture.currentGestureIdToIndex[
5636 mPointerGesture.activeGestureId] = 0;
5637 mPointerGesture.currentGestureProperties[0].clear();
5638 mPointerGesture.currentGestureProperties[0].id =
5639 mPointerGesture.activeGestureId;
5640 mPointerGesture.currentGestureProperties[0].toolType =
5641 AMOTION_EVENT_TOOL_TYPE_FINGER;
5642 mPointerGesture.currentGestureCoords[0].clear();
5643 mPointerGesture.currentGestureCoords[0].setAxisValue(
5644 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5645 mPointerGesture.currentGestureCoords[0].setAxisValue(
5646 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5647 mPointerGesture.currentGestureCoords[0].setAxisValue(
5648 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5649
5650 tapped = true;
5651 } else {
5652#if DEBUG_GESTURES
5653 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5654 x - mPointerGesture.tapX,
5655 y - mPointerGesture.tapY);
5656#endif
5657 }
5658 } else {
5659#if DEBUG_GESTURES
5660 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5661 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5662 (when - mPointerGesture.tapDownTime) * 0.000001f);
5663 } else {
5664 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5665 }
5666#endif
5667 }
5668 }
5669
5670 mPointerVelocityControl.reset();
5671
5672 if (!tapped) {
5673#if DEBUG_GESTURES
5674 ALOGD("Gestures: NEUTRAL");
5675#endif
5676 mPointerGesture.activeGestureId = -1;
5677 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5678 mPointerGesture.currentGestureIdBits.clear();
5679 }
5680 } else if (currentFingerCount == 1) {
5681 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5682 // The pointer follows the active touch point.
5683 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5684 // When in TAP_DRAG, emit MOVE events at the pointer location.
5685 ALOG_ASSERT(activeTouchId >= 0);
5686
5687 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5688 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5689 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5690 float x, y;
5691 mPointerController->getPosition(&x, &y);
5692 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5693 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5694 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5695 } else {
5696#if DEBUG_GESTURES
5697 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5698 x - mPointerGesture.tapX,
5699 y - mPointerGesture.tapY);
5700#endif
5701 }
5702 } else {
5703#if DEBUG_GESTURES
5704 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5705 (when - mPointerGesture.tapUpTime) * 0.000001f);
5706#endif
5707 }
5708 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5709 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5710 }
5711
Jun Mukaifa1706a2015-12-03 01:14:46 -08005712 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005713 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005715 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005717 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005718 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5719 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720
5721 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5722 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5723
5724 // Move the pointer using a relative motion.
5725 // When using spots, the hover or drag will occur at the position of the anchor spot.
5726 mPointerController->move(deltaX, deltaY);
5727 } else {
5728 mPointerVelocityControl.reset();
5729 }
5730
5731 bool down;
5732 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5733#if DEBUG_GESTURES
5734 ALOGD("Gestures: TAP_DRAG");
5735#endif
5736 down = true;
5737 } else {
5738#if DEBUG_GESTURES
5739 ALOGD("Gestures: HOVER");
5740#endif
5741 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5742 *outFinishPreviousGesture = true;
5743 }
5744 mPointerGesture.activeGestureId = 0;
5745 down = false;
5746 }
5747
5748 float x, y;
5749 mPointerController->getPosition(&x, &y);
5750
5751 mPointerGesture.currentGestureIdBits.clear();
5752 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5753 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5754 mPointerGesture.currentGestureProperties[0].clear();
5755 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5756 mPointerGesture.currentGestureProperties[0].toolType =
5757 AMOTION_EVENT_TOOL_TYPE_FINGER;
5758 mPointerGesture.currentGestureCoords[0].clear();
5759 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5760 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5761 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5762 down ? 1.0f : 0.0f);
5763
5764 if (lastFingerCount == 0 && currentFingerCount != 0) {
5765 mPointerGesture.resetTap();
5766 mPointerGesture.tapDownTime = when;
5767 mPointerGesture.tapX = x;
5768 mPointerGesture.tapY = y;
5769 }
5770 } else {
5771 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5772 // We need to provide feedback for each finger that goes down so we cannot wait
5773 // for the fingers to move before deciding what to do.
5774 //
5775 // The ambiguous case is deciding what to do when there are two fingers down but they
5776 // have not moved enough to determine whether they are part of a drag or part of a
5777 // freeform gesture, or just a press or long-press at the pointer location.
5778 //
5779 // When there are two fingers we start with the PRESS hypothesis and we generate a
5780 // down at the pointer location.
5781 //
5782 // When the two fingers move enough or when additional fingers are added, we make
5783 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5784 ALOG_ASSERT(activeTouchId >= 0);
5785
5786 bool settled = when >= mPointerGesture.firstTouchTime
5787 + mConfig.pointerGestureMultitouchSettleInterval;
5788 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5789 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5790 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5791 *outFinishPreviousGesture = true;
5792 } else if (!settled && currentFingerCount > lastFingerCount) {
5793 // Additional pointers have gone down but not yet settled.
5794 // Reset the gesture.
5795#if DEBUG_GESTURES
5796 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5797 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5798 + mConfig.pointerGestureMultitouchSettleInterval - when)
5799 * 0.000001f);
5800#endif
5801 *outCancelPreviousGesture = true;
5802 } else {
5803 // Continue previous gesture.
5804 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5805 }
5806
5807 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5808 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5809 mPointerGesture.activeGestureId = 0;
5810 mPointerGesture.referenceIdBits.clear();
5811 mPointerVelocityControl.reset();
5812
5813 // Use the centroid and pointer location as the reference points for the gesture.
5814#if DEBUG_GESTURES
5815 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5816 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5817 + mConfig.pointerGestureMultitouchSettleInterval - when)
5818 * 0.000001f);
5819#endif
Michael Wright842500e2015-03-13 17:32:02 -07005820 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 &mPointerGesture.referenceTouchX,
5822 &mPointerGesture.referenceTouchY);
5823 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5824 &mPointerGesture.referenceGestureY);
5825 }
5826
5827 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005828 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5830 uint32_t id = idBits.clearFirstMarkedBit();
5831 mPointerGesture.referenceDeltas[id].dx = 0;
5832 mPointerGesture.referenceDeltas[id].dy = 0;
5833 }
Michael Wright842500e2015-03-13 17:32:02 -07005834 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835
5836 // Add delta for all fingers and calculate a common movement delta.
5837 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005838 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5839 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5841 bool first = (idBits == commonIdBits);
5842 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005843 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5844 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5846 delta.dx += cpd.x - lpd.x;
5847 delta.dy += cpd.y - lpd.y;
5848
5849 if (first) {
5850 commonDeltaX = delta.dx;
5851 commonDeltaY = delta.dy;
5852 } else {
5853 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5854 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5855 }
5856 }
5857
5858 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5859 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5860 float dist[MAX_POINTER_ID + 1];
5861 int32_t distOverThreshold = 0;
5862 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5863 uint32_t id = idBits.clearFirstMarkedBit();
5864 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5865 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5866 delta.dy * mPointerYZoomScale);
5867 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5868 distOverThreshold += 1;
5869 }
5870 }
5871
5872 // Only transition when at least two pointers have moved further than
5873 // the minimum distance threshold.
5874 if (distOverThreshold >= 2) {
5875 if (currentFingerCount > 2) {
5876 // There are more than two pointers, switch to FREEFORM.
5877#if DEBUG_GESTURES
5878 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5879 currentFingerCount);
5880#endif
5881 *outCancelPreviousGesture = true;
5882 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5883 } else {
5884 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005885 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 uint32_t id1 = idBits.clearFirstMarkedBit();
5887 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005888 const RawPointerData::Pointer& p1 =
5889 mCurrentRawState.rawPointerData.pointerForId(id1);
5890 const RawPointerData::Pointer& p2 =
5891 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5893 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5894 // There are two pointers but they are too far apart for a SWIPE,
5895 // switch to FREEFORM.
5896#if DEBUG_GESTURES
5897 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5898 mutualDistance, mPointerGestureMaxSwipeWidth);
5899#endif
5900 *outCancelPreviousGesture = true;
5901 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5902 } else {
5903 // There are two pointers. Wait for both pointers to start moving
5904 // before deciding whether this is a SWIPE or FREEFORM gesture.
5905 float dist1 = dist[id1];
5906 float dist2 = dist[id2];
5907 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5908 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5909 // Calculate the dot product of the displacement vectors.
5910 // When the vectors are oriented in approximately the same direction,
5911 // the angle betweeen them is near zero and the cosine of the angle
5912 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5913 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5914 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5915 float dx1 = delta1.dx * mPointerXZoomScale;
5916 float dy1 = delta1.dy * mPointerYZoomScale;
5917 float dx2 = delta2.dx * mPointerXZoomScale;
5918 float dy2 = delta2.dy * mPointerYZoomScale;
5919 float dot = dx1 * dx2 + dy1 * dy2;
5920 float cosine = dot / (dist1 * dist2); // denominator always > 0
5921 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5922 // Pointers are moving in the same direction. Switch to SWIPE.
5923#if DEBUG_GESTURES
5924 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5925 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5926 "cosine %0.3f >= %0.3f",
5927 dist1, mConfig.pointerGestureMultitouchMinDistance,
5928 dist2, mConfig.pointerGestureMultitouchMinDistance,
5929 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5930#endif
5931 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5932 } else {
5933 // Pointers are moving in different directions. Switch to FREEFORM.
5934#if DEBUG_GESTURES
5935 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5936 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5937 "cosine %0.3f < %0.3f",
5938 dist1, mConfig.pointerGestureMultitouchMinDistance,
5939 dist2, mConfig.pointerGestureMultitouchMinDistance,
5940 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5941#endif
5942 *outCancelPreviousGesture = true;
5943 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5944 }
5945 }
5946 }
5947 }
5948 }
5949 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5950 // Switch from SWIPE to FREEFORM if additional pointers go down.
5951 // Cancel previous gesture.
5952 if (currentFingerCount > 2) {
5953#if DEBUG_GESTURES
5954 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5955 currentFingerCount);
5956#endif
5957 *outCancelPreviousGesture = true;
5958 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5959 }
5960 }
5961
5962 // Move the reference points based on the overall group motion of the fingers
5963 // except in PRESS mode while waiting for a transition to occur.
5964 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5965 && (commonDeltaX || commonDeltaY)) {
5966 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5967 uint32_t id = idBits.clearFirstMarkedBit();
5968 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5969 delta.dx = 0;
5970 delta.dy = 0;
5971 }
5972
5973 mPointerGesture.referenceTouchX += commonDeltaX;
5974 mPointerGesture.referenceTouchY += commonDeltaY;
5975
5976 commonDeltaX *= mPointerXMovementScale;
5977 commonDeltaY *= mPointerYMovementScale;
5978
5979 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5980 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5981
5982 mPointerGesture.referenceGestureX += commonDeltaX;
5983 mPointerGesture.referenceGestureY += commonDeltaY;
5984 }
5985
5986 // Report gestures.
5987 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5988 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5989 // PRESS or SWIPE mode.
5990#if DEBUG_GESTURES
5991 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5992 "activeGestureId=%d, currentTouchPointerCount=%d",
5993 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5994#endif
5995 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5996
5997 mPointerGesture.currentGestureIdBits.clear();
5998 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5999 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6000 mPointerGesture.currentGestureProperties[0].clear();
6001 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6002 mPointerGesture.currentGestureProperties[0].toolType =
6003 AMOTION_EVENT_TOOL_TYPE_FINGER;
6004 mPointerGesture.currentGestureCoords[0].clear();
6005 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6006 mPointerGesture.referenceGestureX);
6007 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6008 mPointerGesture.referenceGestureY);
6009 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6010 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6011 // FREEFORM mode.
6012#if DEBUG_GESTURES
6013 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6014 "activeGestureId=%d, currentTouchPointerCount=%d",
6015 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6016#endif
6017 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6018
6019 mPointerGesture.currentGestureIdBits.clear();
6020
6021 BitSet32 mappedTouchIdBits;
6022 BitSet32 usedGestureIdBits;
6023 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6024 // Initially, assign the active gesture id to the active touch point
6025 // if there is one. No other touch id bits are mapped yet.
6026 if (!*outCancelPreviousGesture) {
6027 mappedTouchIdBits.markBit(activeTouchId);
6028 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6029 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6030 mPointerGesture.activeGestureId;
6031 } else {
6032 mPointerGesture.activeGestureId = -1;
6033 }
6034 } else {
6035 // Otherwise, assume we mapped all touches from the previous frame.
6036 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006037 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6038 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6040
6041 // Check whether we need to choose a new active gesture id because the
6042 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006043 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6044 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 !upTouchIdBits.isEmpty(); ) {
6046 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6047 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6048 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6049 mPointerGesture.activeGestureId = -1;
6050 break;
6051 }
6052 }
6053 }
6054
6055#if DEBUG_GESTURES
6056 ALOGD("Gestures: FREEFORM follow up "
6057 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6058 "activeGestureId=%d",
6059 mappedTouchIdBits.value, usedGestureIdBits.value,
6060 mPointerGesture.activeGestureId);
6061#endif
6062
Michael Wright842500e2015-03-13 17:32:02 -07006063 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064 for (uint32_t i = 0; i < currentFingerCount; i++) {
6065 uint32_t touchId = idBits.clearFirstMarkedBit();
6066 uint32_t gestureId;
6067 if (!mappedTouchIdBits.hasBit(touchId)) {
6068 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6069 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6070#if DEBUG_GESTURES
6071 ALOGD("Gestures: FREEFORM "
6072 "new mapping for touch id %d -> gesture id %d",
6073 touchId, gestureId);
6074#endif
6075 } else {
6076 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6077#if DEBUG_GESTURES
6078 ALOGD("Gestures: FREEFORM "
6079 "existing mapping for touch id %d -> gesture id %d",
6080 touchId, gestureId);
6081#endif
6082 }
6083 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6084 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6085
6086 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006087 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6089 * mPointerXZoomScale;
6090 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6091 * mPointerYZoomScale;
6092 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6093
6094 mPointerGesture.currentGestureProperties[i].clear();
6095 mPointerGesture.currentGestureProperties[i].id = gestureId;
6096 mPointerGesture.currentGestureProperties[i].toolType =
6097 AMOTION_EVENT_TOOL_TYPE_FINGER;
6098 mPointerGesture.currentGestureCoords[i].clear();
6099 mPointerGesture.currentGestureCoords[i].setAxisValue(
6100 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6101 mPointerGesture.currentGestureCoords[i].setAxisValue(
6102 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6103 mPointerGesture.currentGestureCoords[i].setAxisValue(
6104 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6105 }
6106
6107 if (mPointerGesture.activeGestureId < 0) {
6108 mPointerGesture.activeGestureId =
6109 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6110#if DEBUG_GESTURES
6111 ALOGD("Gestures: FREEFORM new "
6112 "activeGestureId=%d", mPointerGesture.activeGestureId);
6113#endif
6114 }
6115 }
6116 }
6117
Michael Wright842500e2015-03-13 17:32:02 -07006118 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119
6120#if DEBUG_GESTURES
6121 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6122 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6123 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6124 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6125 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6126 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6127 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6128 uint32_t id = idBits.clearFirstMarkedBit();
6129 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6130 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6131 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6132 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6133 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6134 id, index, properties.toolType,
6135 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6136 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6137 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6138 }
6139 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6140 uint32_t id = idBits.clearFirstMarkedBit();
6141 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6142 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6143 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6144 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6145 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6146 id, index, properties.toolType,
6147 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6148 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6149 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6150 }
6151#endif
6152 return true;
6153}
6154
6155void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6156 mPointerSimple.currentCoords.clear();
6157 mPointerSimple.currentProperties.clear();
6158
6159 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006160 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6161 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6162 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6163 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6164 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006165 mPointerController->setPosition(x, y);
6166
Michael Wright842500e2015-03-13 17:32:02 -07006167 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006168 down = !hovering;
6169
6170 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006171 mPointerSimple.currentCoords.copyFrom(
6172 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006173 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6174 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6175 mPointerSimple.currentProperties.id = 0;
6176 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006177 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178 } else {
6179 down = false;
6180 hovering = false;
6181 }
6182
6183 dispatchPointerSimple(when, policyFlags, down, hovering);
6184}
6185
6186void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6187 abortPointerSimple(when, policyFlags);
6188}
6189
6190void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6191 mPointerSimple.currentCoords.clear();
6192 mPointerSimple.currentProperties.clear();
6193
6194 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006195 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6196 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6197 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006198 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006199 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6200 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006201 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006202 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006204 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006205 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006206 * mPointerYMovementScale;
6207
6208 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6209 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6210
6211 mPointerController->move(deltaX, deltaY);
6212 } else {
6213 mPointerVelocityControl.reset();
6214 }
6215
Michael Wright842500e2015-03-13 17:32:02 -07006216 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006217 hovering = !down;
6218
6219 float x, y;
6220 mPointerController->getPosition(&x, &y);
6221 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006222 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6224 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6225 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6226 hovering ? 0.0f : 1.0f);
6227 mPointerSimple.currentProperties.id = 0;
6228 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006229 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 } else {
6231 mPointerVelocityControl.reset();
6232
6233 down = false;
6234 hovering = false;
6235 }
6236
6237 dispatchPointerSimple(when, policyFlags, down, hovering);
6238}
6239
6240void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6241 abortPointerSimple(when, policyFlags);
6242
6243 mPointerVelocityControl.reset();
6244}
6245
6246void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6247 bool down, bool hovering) {
6248 int32_t metaState = getContext()->getGlobalMetaState();
6249
6250 if (mPointerController != NULL) {
6251 if (down || hovering) {
6252 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6253 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006254 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6256 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6257 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6258 }
6259 }
6260
6261 if (mPointerSimple.down && !down) {
6262 mPointerSimple.down = false;
6263
6264 // Send up.
6265 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006266 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 mViewport.displayId,
6268 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6269 mOrientedXPrecision, mOrientedYPrecision,
6270 mPointerSimple.downTime);
6271 getListener()->notifyMotion(&args);
6272 }
6273
6274 if (mPointerSimple.hovering && !hovering) {
6275 mPointerSimple.hovering = false;
6276
6277 // Send hover exit.
6278 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006279 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280 mViewport.displayId,
6281 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6282 mOrientedXPrecision, mOrientedYPrecision,
6283 mPointerSimple.downTime);
6284 getListener()->notifyMotion(&args);
6285 }
6286
6287 if (down) {
6288 if (!mPointerSimple.down) {
6289 mPointerSimple.down = true;
6290 mPointerSimple.downTime = when;
6291
6292 // Send down.
6293 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006294 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 mViewport.displayId,
6296 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6297 mOrientedXPrecision, mOrientedYPrecision,
6298 mPointerSimple.downTime);
6299 getListener()->notifyMotion(&args);
6300 }
6301
6302 // Send move.
6303 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006304 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006305 mViewport.displayId,
6306 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6307 mOrientedXPrecision, mOrientedYPrecision,
6308 mPointerSimple.downTime);
6309 getListener()->notifyMotion(&args);
6310 }
6311
6312 if (hovering) {
6313 if (!mPointerSimple.hovering) {
6314 mPointerSimple.hovering = true;
6315
6316 // Send hover enter.
6317 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006318 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006319 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006320 mViewport.displayId,
6321 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6322 mOrientedXPrecision, mOrientedYPrecision,
6323 mPointerSimple.downTime);
6324 getListener()->notifyMotion(&args);
6325 }
6326
6327 // Send hover move.
6328 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006329 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006330 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006331 mViewport.displayId,
6332 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6333 mOrientedXPrecision, mOrientedYPrecision,
6334 mPointerSimple.downTime);
6335 getListener()->notifyMotion(&args);
6336 }
6337
Michael Wright842500e2015-03-13 17:32:02 -07006338 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6339 float vscroll = mCurrentRawState.rawVScroll;
6340 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006341 mWheelYVelocityControl.move(when, NULL, &vscroll);
6342 mWheelXVelocityControl.move(when, &hscroll, NULL);
6343
6344 // Send scroll.
6345 PointerCoords pointerCoords;
6346 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6347 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6348 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6349
6350 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006351 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352 mViewport.displayId,
6353 1, &mPointerSimple.currentProperties, &pointerCoords,
6354 mOrientedXPrecision, mOrientedYPrecision,
6355 mPointerSimple.downTime);
6356 getListener()->notifyMotion(&args);
6357 }
6358
6359 // Save state.
6360 if (down || hovering) {
6361 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6362 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6363 } else {
6364 mPointerSimple.reset();
6365 }
6366}
6367
6368void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6369 mPointerSimple.currentCoords.clear();
6370 mPointerSimple.currentProperties.clear();
6371
6372 dispatchPointerSimple(when, policyFlags, false, false);
6373}
6374
6375void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006376 int32_t action, int32_t actionButton, int32_t flags,
6377 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006378 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006379 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6380 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006381 PointerCoords pointerCoords[MAX_POINTERS];
6382 PointerProperties pointerProperties[MAX_POINTERS];
6383 uint32_t pointerCount = 0;
6384 while (!idBits.isEmpty()) {
6385 uint32_t id = idBits.clearFirstMarkedBit();
6386 uint32_t index = idToIndex[id];
6387 pointerProperties[pointerCount].copyFrom(properties[index]);
6388 pointerCoords[pointerCount].copyFrom(coords[index]);
6389
6390 if (changedId >= 0 && id == uint32_t(changedId)) {
6391 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6392 }
6393
6394 pointerCount += 1;
6395 }
6396
6397 ALOG_ASSERT(pointerCount != 0);
6398
6399 if (changedId >= 0 && pointerCount == 1) {
6400 // Replace initial down and final up action.
6401 // We can compare the action without masking off the changed pointer index
6402 // because we know the index is 0.
6403 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6404 action = AMOTION_EVENT_ACTION_DOWN;
6405 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6406 action = AMOTION_EVENT_ACTION_UP;
6407 } else {
6408 // Can't happen.
6409 ALOG_ASSERT(false);
6410 }
6411 }
6412
6413 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006414 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6416 xPrecision, yPrecision, downTime);
6417 getListener()->notifyMotion(&args);
6418}
6419
6420bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6421 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6422 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6423 BitSet32 idBits) const {
6424 bool changed = false;
6425 while (!idBits.isEmpty()) {
6426 uint32_t id = idBits.clearFirstMarkedBit();
6427 uint32_t inIndex = inIdToIndex[id];
6428 uint32_t outIndex = outIdToIndex[id];
6429
6430 const PointerProperties& curInProperties = inProperties[inIndex];
6431 const PointerCoords& curInCoords = inCoords[inIndex];
6432 PointerProperties& curOutProperties = outProperties[outIndex];
6433 PointerCoords& curOutCoords = outCoords[outIndex];
6434
6435 if (curInProperties != curOutProperties) {
6436 curOutProperties.copyFrom(curInProperties);
6437 changed = true;
6438 }
6439
6440 if (curInCoords != curOutCoords) {
6441 curOutCoords.copyFrom(curInCoords);
6442 changed = true;
6443 }
6444 }
6445 return changed;
6446}
6447
6448void TouchInputMapper::fadePointer() {
6449 if (mPointerController != NULL) {
6450 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6451 }
6452}
6453
Jeff Brownc9aa6282015-02-11 19:03:28 -08006454void TouchInputMapper::cancelTouch(nsecs_t when) {
6455 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006456 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006457}
6458
Michael Wrightd02c5b62014-02-10 15:10:22 -08006459bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6460 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6461 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6462}
6463
6464const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6465 int32_t x, int32_t y) {
6466 size_t numVirtualKeys = mVirtualKeys.size();
6467 for (size_t i = 0; i < numVirtualKeys; i++) {
6468 const VirtualKey& virtualKey = mVirtualKeys[i];
6469
6470#if DEBUG_VIRTUAL_KEYS
6471 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6472 "left=%d, top=%d, right=%d, bottom=%d",
6473 x, y,
6474 virtualKey.keyCode, virtualKey.scanCode,
6475 virtualKey.hitLeft, virtualKey.hitTop,
6476 virtualKey.hitRight, virtualKey.hitBottom);
6477#endif
6478
6479 if (virtualKey.isHit(x, y)) {
6480 return & virtualKey;
6481 }
6482 }
6483
6484 return NULL;
6485}
6486
Michael Wright842500e2015-03-13 17:32:02 -07006487void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6488 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6489 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006490
Michael Wright842500e2015-03-13 17:32:02 -07006491 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006492
6493 if (currentPointerCount == 0) {
6494 // No pointers to assign.
6495 return;
6496 }
6497
6498 if (lastPointerCount == 0) {
6499 // All pointers are new.
6500 for (uint32_t i = 0; i < currentPointerCount; i++) {
6501 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006502 current->rawPointerData.pointers[i].id = id;
6503 current->rawPointerData.idToIndex[id] = i;
6504 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 }
6506 return;
6507 }
6508
6509 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006510 && current->rawPointerData.pointers[0].toolType
6511 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006512 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006513 uint32_t id = last->rawPointerData.pointers[0].id;
6514 current->rawPointerData.pointers[0].id = id;
6515 current->rawPointerData.idToIndex[id] = 0;
6516 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517 return;
6518 }
6519
6520 // General case.
6521 // We build a heap of squared euclidean distances between current and last pointers
6522 // associated with the current and last pointer indices. Then, we find the best
6523 // match (by distance) for each current pointer.
6524 // The pointers must have the same tool type but it is possible for them to
6525 // transition from hovering to touching or vice-versa while retaining the same id.
6526 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6527
6528 uint32_t heapSize = 0;
6529 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6530 currentPointerIndex++) {
6531 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6532 lastPointerIndex++) {
6533 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006534 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006536 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537 if (currentPointer.toolType == lastPointer.toolType) {
6538 int64_t deltaX = currentPointer.x - lastPointer.x;
6539 int64_t deltaY = currentPointer.y - lastPointer.y;
6540
6541 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6542
6543 // Insert new element into the heap (sift up).
6544 heap[heapSize].currentPointerIndex = currentPointerIndex;
6545 heap[heapSize].lastPointerIndex = lastPointerIndex;
6546 heap[heapSize].distance = distance;
6547 heapSize += 1;
6548 }
6549 }
6550 }
6551
6552 // Heapify
6553 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6554 startIndex -= 1;
6555 for (uint32_t parentIndex = startIndex; ;) {
6556 uint32_t childIndex = parentIndex * 2 + 1;
6557 if (childIndex >= heapSize) {
6558 break;
6559 }
6560
6561 if (childIndex + 1 < heapSize
6562 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6563 childIndex += 1;
6564 }
6565
6566 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6567 break;
6568 }
6569
6570 swap(heap[parentIndex], heap[childIndex]);
6571 parentIndex = childIndex;
6572 }
6573 }
6574
6575#if DEBUG_POINTER_ASSIGNMENT
6576 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6577 for (size_t i = 0; i < heapSize; i++) {
6578 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6579 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6580 heap[i].distance);
6581 }
6582#endif
6583
6584 // Pull matches out by increasing order of distance.
6585 // To avoid reassigning pointers that have already been matched, the loop keeps track
6586 // of which last and current pointers have been matched using the matchedXXXBits variables.
6587 // It also tracks the used pointer id bits.
6588 BitSet32 matchedLastBits(0);
6589 BitSet32 matchedCurrentBits(0);
6590 BitSet32 usedIdBits(0);
6591 bool first = true;
6592 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6593 while (heapSize > 0) {
6594 if (first) {
6595 // The first time through the loop, we just consume the root element of
6596 // the heap (the one with smallest distance).
6597 first = false;
6598 } else {
6599 // Previous iterations consumed the root element of the heap.
6600 // Pop root element off of the heap (sift down).
6601 heap[0] = heap[heapSize];
6602 for (uint32_t parentIndex = 0; ;) {
6603 uint32_t childIndex = parentIndex * 2 + 1;
6604 if (childIndex >= heapSize) {
6605 break;
6606 }
6607
6608 if (childIndex + 1 < heapSize
6609 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6610 childIndex += 1;
6611 }
6612
6613 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6614 break;
6615 }
6616
6617 swap(heap[parentIndex], heap[childIndex]);
6618 parentIndex = childIndex;
6619 }
6620
6621#if DEBUG_POINTER_ASSIGNMENT
6622 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6623 for (size_t i = 0; i < heapSize; i++) {
6624 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6625 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6626 heap[i].distance);
6627 }
6628#endif
6629 }
6630
6631 heapSize -= 1;
6632
6633 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6634 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6635
6636 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6637 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6638
6639 matchedCurrentBits.markBit(currentPointerIndex);
6640 matchedLastBits.markBit(lastPointerIndex);
6641
Michael Wright842500e2015-03-13 17:32:02 -07006642 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6643 current->rawPointerData.pointers[currentPointerIndex].id = id;
6644 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6645 current->rawPointerData.markIdBit(id,
6646 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647 usedIdBits.markBit(id);
6648
6649#if DEBUG_POINTER_ASSIGNMENT
6650 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6651 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6652#endif
6653 break;
6654 }
6655 }
6656
6657 // Assign fresh ids to pointers that were not matched in the process.
6658 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6659 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6660 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6661
Michael Wright842500e2015-03-13 17:32:02 -07006662 current->rawPointerData.pointers[currentPointerIndex].id = id;
6663 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6664 current->rawPointerData.markIdBit(id,
6665 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006666
6667#if DEBUG_POINTER_ASSIGNMENT
6668 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6669 currentPointerIndex, id);
6670#endif
6671 }
6672}
6673
6674int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6675 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6676 return AKEY_STATE_VIRTUAL;
6677 }
6678
6679 size_t numVirtualKeys = mVirtualKeys.size();
6680 for (size_t i = 0; i < numVirtualKeys; i++) {
6681 const VirtualKey& virtualKey = mVirtualKeys[i];
6682 if (virtualKey.keyCode == keyCode) {
6683 return AKEY_STATE_UP;
6684 }
6685 }
6686
6687 return AKEY_STATE_UNKNOWN;
6688}
6689
6690int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6691 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6692 return AKEY_STATE_VIRTUAL;
6693 }
6694
6695 size_t numVirtualKeys = mVirtualKeys.size();
6696 for (size_t i = 0; i < numVirtualKeys; i++) {
6697 const VirtualKey& virtualKey = mVirtualKeys[i];
6698 if (virtualKey.scanCode == scanCode) {
6699 return AKEY_STATE_UP;
6700 }
6701 }
6702
6703 return AKEY_STATE_UNKNOWN;
6704}
6705
6706bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6707 const int32_t* keyCodes, uint8_t* outFlags) {
6708 size_t numVirtualKeys = mVirtualKeys.size();
6709 for (size_t i = 0; i < numVirtualKeys; i++) {
6710 const VirtualKey& virtualKey = mVirtualKeys[i];
6711
6712 for (size_t i = 0; i < numCodes; i++) {
6713 if (virtualKey.keyCode == keyCodes[i]) {
6714 outFlags[i] = 1;
6715 }
6716 }
6717 }
6718
6719 return true;
6720}
6721
6722
6723// --- SingleTouchInputMapper ---
6724
6725SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6726 TouchInputMapper(device) {
6727}
6728
6729SingleTouchInputMapper::~SingleTouchInputMapper() {
6730}
6731
6732void SingleTouchInputMapper::reset(nsecs_t when) {
6733 mSingleTouchMotionAccumulator.reset(getDevice());
6734
6735 TouchInputMapper::reset(when);
6736}
6737
6738void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6739 TouchInputMapper::process(rawEvent);
6740
6741 mSingleTouchMotionAccumulator.process(rawEvent);
6742}
6743
Michael Wright842500e2015-03-13 17:32:02 -07006744void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006745 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006746 outState->rawPointerData.pointerCount = 1;
6747 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006748
6749 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6750 && (mTouchButtonAccumulator.isHovering()
6751 || (mRawPointerAxes.pressure.valid
6752 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006753 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006754
Michael Wright842500e2015-03-13 17:32:02 -07006755 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006756 outPointer.id = 0;
6757 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6758 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6759 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6760 outPointer.touchMajor = 0;
6761 outPointer.touchMinor = 0;
6762 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6763 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6764 outPointer.orientation = 0;
6765 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6766 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6767 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6768 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6769 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6770 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6771 }
6772 outPointer.isHovering = isHovering;
6773 }
6774}
6775
6776void SingleTouchInputMapper::configureRawPointerAxes() {
6777 TouchInputMapper::configureRawPointerAxes();
6778
6779 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6780 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6781 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6782 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6783 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6784 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6785 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6786}
6787
6788bool SingleTouchInputMapper::hasStylus() const {
6789 return mTouchButtonAccumulator.hasStylus();
6790}
6791
6792
6793// --- MultiTouchInputMapper ---
6794
6795MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6796 TouchInputMapper(device) {
6797}
6798
6799MultiTouchInputMapper::~MultiTouchInputMapper() {
6800}
6801
6802void MultiTouchInputMapper::reset(nsecs_t when) {
6803 mMultiTouchMotionAccumulator.reset(getDevice());
6804
6805 mPointerIdBits.clear();
6806
6807 TouchInputMapper::reset(when);
6808}
6809
6810void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6811 TouchInputMapper::process(rawEvent);
6812
6813 mMultiTouchMotionAccumulator.process(rawEvent);
6814}
6815
Michael Wright842500e2015-03-13 17:32:02 -07006816void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006817 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6818 size_t outCount = 0;
6819 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006820 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006821
6822 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6823 const MultiTouchMotionAccumulator::Slot* inSlot =
6824 mMultiTouchMotionAccumulator.getSlot(inIndex);
6825 if (!inSlot->isInUse()) {
6826 continue;
6827 }
6828
6829 if (outCount >= MAX_POINTERS) {
6830#if DEBUG_POINTERS
6831 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6832 "ignoring the rest.",
6833 getDeviceName().string(), MAX_POINTERS);
6834#endif
6835 break; // too many fingers!
6836 }
6837
Michael Wright842500e2015-03-13 17:32:02 -07006838 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006839 outPointer.x = inSlot->getX();
6840 outPointer.y = inSlot->getY();
6841 outPointer.pressure = inSlot->getPressure();
6842 outPointer.touchMajor = inSlot->getTouchMajor();
6843 outPointer.touchMinor = inSlot->getTouchMinor();
6844 outPointer.toolMajor = inSlot->getToolMajor();
6845 outPointer.toolMinor = inSlot->getToolMinor();
6846 outPointer.orientation = inSlot->getOrientation();
6847 outPointer.distance = inSlot->getDistance();
6848 outPointer.tiltX = 0;
6849 outPointer.tiltY = 0;
6850
6851 outPointer.toolType = inSlot->getToolType();
6852 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6853 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6854 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6855 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6856 }
6857 }
6858
6859 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6860 && (mTouchButtonAccumulator.isHovering()
6861 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6862 outPointer.isHovering = isHovering;
6863
6864 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006865 if (mHavePointerIds) {
6866 int32_t trackingId = inSlot->getTrackingId();
6867 int32_t id = -1;
6868 if (trackingId >= 0) {
6869 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6870 uint32_t n = idBits.clearFirstMarkedBit();
6871 if (mPointerTrackingIdMap[n] == trackingId) {
6872 id = n;
6873 }
6874 }
6875
6876 if (id < 0 && !mPointerIdBits.isFull()) {
6877 id = mPointerIdBits.markFirstUnmarkedBit();
6878 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006879 }
Michael Wright842500e2015-03-13 17:32:02 -07006880 }
gaoshang1a632de2016-08-24 10:23:50 +08006881 if (id < 0) {
6882 mHavePointerIds = false;
6883 outState->rawPointerData.clearIdBits();
6884 newPointerIdBits.clear();
6885 } else {
6886 outPointer.id = id;
6887 outState->rawPointerData.idToIndex[id] = outCount;
6888 outState->rawPointerData.markIdBit(id, isHovering);
6889 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006890 }
Michael Wright842500e2015-03-13 17:32:02 -07006891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006892 outCount += 1;
6893 }
6894
Michael Wright842500e2015-03-13 17:32:02 -07006895 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006896 mPointerIdBits = newPointerIdBits;
6897
6898 mMultiTouchMotionAccumulator.finishSync();
6899}
6900
6901void MultiTouchInputMapper::configureRawPointerAxes() {
6902 TouchInputMapper::configureRawPointerAxes();
6903
6904 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6905 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6906 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6907 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6908 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6909 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6910 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6911 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6912 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6913 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6914 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6915
6916 if (mRawPointerAxes.trackingId.valid
6917 && mRawPointerAxes.slot.valid
6918 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6919 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6920 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006921 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6922 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006923 getDeviceName().string(), slotCount, MAX_SLOTS);
6924 slotCount = MAX_SLOTS;
6925 }
6926 mMultiTouchMotionAccumulator.configure(getDevice(),
6927 slotCount, true /*usingSlotsProtocol*/);
6928 } else {
6929 mMultiTouchMotionAccumulator.configure(getDevice(),
6930 MAX_POINTERS, false /*usingSlotsProtocol*/);
6931 }
6932}
6933
6934bool MultiTouchInputMapper::hasStylus() const {
6935 return mMultiTouchMotionAccumulator.hasStylus()
6936 || mTouchButtonAccumulator.hasStylus();
6937}
6938
Michael Wright842500e2015-03-13 17:32:02 -07006939// --- ExternalStylusInputMapper
6940
6941ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6942 InputMapper(device) {
6943
6944}
6945
6946uint32_t ExternalStylusInputMapper::getSources() {
6947 return AINPUT_SOURCE_STYLUS;
6948}
6949
6950void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6951 InputMapper::populateDeviceInfo(info);
6952 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6953 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6954}
6955
6956void ExternalStylusInputMapper::dump(String8& dump) {
6957 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6958 dump.append(INDENT3 "Raw Stylus Axes:\n");
6959 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6960 dump.append(INDENT3 "Stylus State:\n");
6961 dumpStylusState(dump, mStylusState);
6962}
6963
6964void ExternalStylusInputMapper::configure(nsecs_t when,
6965 const InputReaderConfiguration* config, uint32_t changes) {
6966 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6967 mTouchButtonAccumulator.configure(getDevice());
6968}
6969
6970void ExternalStylusInputMapper::reset(nsecs_t when) {
6971 InputDevice* device = getDevice();
6972 mSingleTouchMotionAccumulator.reset(device);
6973 mTouchButtonAccumulator.reset(device);
6974 InputMapper::reset(when);
6975}
6976
6977void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6978 mSingleTouchMotionAccumulator.process(rawEvent);
6979 mTouchButtonAccumulator.process(rawEvent);
6980
6981 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6982 sync(rawEvent->when);
6983 }
6984}
6985
6986void ExternalStylusInputMapper::sync(nsecs_t when) {
6987 mStylusState.clear();
6988
6989 mStylusState.when = when;
6990
Michael Wright45ccacf2015-04-21 19:01:58 +01006991 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6992 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6993 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6994 }
6995
Michael Wright842500e2015-03-13 17:32:02 -07006996 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6997 if (mRawPressureAxis.valid) {
6998 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6999 } else if (mTouchButtonAccumulator.isToolActive()) {
7000 mStylusState.pressure = 1.0f;
7001 } else {
7002 mStylusState.pressure = 0.0f;
7003 }
7004
7005 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007006
7007 mContext->dispatchExternalStylusState(mStylusState);
7008}
7009
Michael Wrightd02c5b62014-02-10 15:10:22 -08007010
7011// --- JoystickInputMapper ---
7012
7013JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7014 InputMapper(device) {
7015}
7016
7017JoystickInputMapper::~JoystickInputMapper() {
7018}
7019
7020uint32_t JoystickInputMapper::getSources() {
7021 return AINPUT_SOURCE_JOYSTICK;
7022}
7023
7024void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7025 InputMapper::populateDeviceInfo(info);
7026
7027 for (size_t i = 0; i < mAxes.size(); i++) {
7028 const Axis& axis = mAxes.valueAt(i);
7029 addMotionRange(axis.axisInfo.axis, axis, info);
7030
7031 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7032 addMotionRange(axis.axisInfo.highAxis, axis, info);
7033
7034 }
7035 }
7036}
7037
7038void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7039 InputDeviceInfo* info) {
7040 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7041 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7042 /* In order to ease the transition for developers from using the old axes
7043 * to the newer, more semantically correct axes, we'll continue to register
7044 * the old axes as duplicates of their corresponding new ones. */
7045 int32_t compatAxis = getCompatAxis(axisId);
7046 if (compatAxis >= 0) {
7047 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7048 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7049 }
7050}
7051
7052/* A mapping from axes the joystick actually has to the axes that should be
7053 * artificially created for compatibility purposes.
7054 * Returns -1 if no compatibility axis is needed. */
7055int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7056 switch(axis) {
7057 case AMOTION_EVENT_AXIS_LTRIGGER:
7058 return AMOTION_EVENT_AXIS_BRAKE;
7059 case AMOTION_EVENT_AXIS_RTRIGGER:
7060 return AMOTION_EVENT_AXIS_GAS;
7061 }
7062 return -1;
7063}
7064
7065void JoystickInputMapper::dump(String8& dump) {
7066 dump.append(INDENT2 "Joystick Input Mapper:\n");
7067
7068 dump.append(INDENT3 "Axes:\n");
7069 size_t numAxes = mAxes.size();
7070 for (size_t i = 0; i < numAxes; i++) {
7071 const Axis& axis = mAxes.valueAt(i);
7072 const char* label = getAxisLabel(axis.axisInfo.axis);
7073 if (label) {
7074 dump.appendFormat(INDENT4 "%s", label);
7075 } else {
7076 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7077 }
7078 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7079 label = getAxisLabel(axis.axisInfo.highAxis);
7080 if (label) {
7081 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7082 } else {
7083 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7084 axis.axisInfo.splitValue);
7085 }
7086 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7087 dump.append(" (invert)");
7088 }
7089
7090 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7091 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7092 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7093 "highScale=%0.5f, highOffset=%0.5f\n",
7094 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7095 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7096 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7097 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7098 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7099 }
7100}
7101
7102void JoystickInputMapper::configure(nsecs_t when,
7103 const InputReaderConfiguration* config, uint32_t changes) {
7104 InputMapper::configure(when, config, changes);
7105
7106 if (!changes) { // first time only
7107 // Collect all axes.
7108 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7109 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7110 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7111 continue; // axis must be claimed by a different device
7112 }
7113
7114 RawAbsoluteAxisInfo rawAxisInfo;
7115 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7116 if (rawAxisInfo.valid) {
7117 // Map axis.
7118 AxisInfo axisInfo;
7119 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7120 if (!explicitlyMapped) {
7121 // Axis is not explicitly mapped, will choose a generic axis later.
7122 axisInfo.mode = AxisInfo::MODE_NORMAL;
7123 axisInfo.axis = -1;
7124 }
7125
7126 // Apply flat override.
7127 int32_t rawFlat = axisInfo.flatOverride < 0
7128 ? rawAxisInfo.flat : axisInfo.flatOverride;
7129
7130 // Calculate scaling factors and limits.
7131 Axis axis;
7132 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7133 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7134 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7135 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7136 scale, 0.0f, highScale, 0.0f,
7137 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7138 rawAxisInfo.resolution * scale);
7139 } else if (isCenteredAxis(axisInfo.axis)) {
7140 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7141 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7142 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7143 scale, offset, scale, offset,
7144 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7145 rawAxisInfo.resolution * scale);
7146 } else {
7147 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7148 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7149 scale, 0.0f, scale, 0.0f,
7150 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7151 rawAxisInfo.resolution * scale);
7152 }
7153
7154 // To eliminate noise while the joystick is at rest, filter out small variations
7155 // in axis values up front.
7156 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7157
7158 mAxes.add(abs, axis);
7159 }
7160 }
7161
7162 // If there are too many axes, start dropping them.
7163 // Prefer to keep explicitly mapped axes.
7164 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007165 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007166 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7167 pruneAxes(true);
7168 pruneAxes(false);
7169 }
7170
7171 // Assign generic axis ids to remaining axes.
7172 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7173 size_t numAxes = mAxes.size();
7174 for (size_t i = 0; i < numAxes; i++) {
7175 Axis& axis = mAxes.editValueAt(i);
7176 if (axis.axisInfo.axis < 0) {
7177 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7178 && haveAxis(nextGenericAxisId)) {
7179 nextGenericAxisId += 1;
7180 }
7181
7182 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7183 axis.axisInfo.axis = nextGenericAxisId;
7184 nextGenericAxisId += 1;
7185 } else {
7186 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7187 "have already been assigned to other axes.",
7188 getDeviceName().string(), mAxes.keyAt(i));
7189 mAxes.removeItemsAt(i--);
7190 numAxes -= 1;
7191 }
7192 }
7193 }
7194 }
7195}
7196
7197bool JoystickInputMapper::haveAxis(int32_t axisId) {
7198 size_t numAxes = mAxes.size();
7199 for (size_t i = 0; i < numAxes; i++) {
7200 const Axis& axis = mAxes.valueAt(i);
7201 if (axis.axisInfo.axis == axisId
7202 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7203 && axis.axisInfo.highAxis == axisId)) {
7204 return true;
7205 }
7206 }
7207 return false;
7208}
7209
7210void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7211 size_t i = mAxes.size();
7212 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7213 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7214 continue;
7215 }
7216 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7217 getDeviceName().string(), mAxes.keyAt(i));
7218 mAxes.removeItemsAt(i);
7219 }
7220}
7221
7222bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7223 switch (axis) {
7224 case AMOTION_EVENT_AXIS_X:
7225 case AMOTION_EVENT_AXIS_Y:
7226 case AMOTION_EVENT_AXIS_Z:
7227 case AMOTION_EVENT_AXIS_RX:
7228 case AMOTION_EVENT_AXIS_RY:
7229 case AMOTION_EVENT_AXIS_RZ:
7230 case AMOTION_EVENT_AXIS_HAT_X:
7231 case AMOTION_EVENT_AXIS_HAT_Y:
7232 case AMOTION_EVENT_AXIS_ORIENTATION:
7233 case AMOTION_EVENT_AXIS_RUDDER:
7234 case AMOTION_EVENT_AXIS_WHEEL:
7235 return true;
7236 default:
7237 return false;
7238 }
7239}
7240
7241void JoystickInputMapper::reset(nsecs_t when) {
7242 // Recenter all axes.
7243 size_t numAxes = mAxes.size();
7244 for (size_t i = 0; i < numAxes; i++) {
7245 Axis& axis = mAxes.editValueAt(i);
7246 axis.resetValue();
7247 }
7248
7249 InputMapper::reset(when);
7250}
7251
7252void JoystickInputMapper::process(const RawEvent* rawEvent) {
7253 switch (rawEvent->type) {
7254 case EV_ABS: {
7255 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7256 if (index >= 0) {
7257 Axis& axis = mAxes.editValueAt(index);
7258 float newValue, highNewValue;
7259 switch (axis.axisInfo.mode) {
7260 case AxisInfo::MODE_INVERT:
7261 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7262 * axis.scale + axis.offset;
7263 highNewValue = 0.0f;
7264 break;
7265 case AxisInfo::MODE_SPLIT:
7266 if (rawEvent->value < axis.axisInfo.splitValue) {
7267 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7268 * axis.scale + axis.offset;
7269 highNewValue = 0.0f;
7270 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7271 newValue = 0.0f;
7272 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7273 * axis.highScale + axis.highOffset;
7274 } else {
7275 newValue = 0.0f;
7276 highNewValue = 0.0f;
7277 }
7278 break;
7279 default:
7280 newValue = rawEvent->value * axis.scale + axis.offset;
7281 highNewValue = 0.0f;
7282 break;
7283 }
7284 axis.newValue = newValue;
7285 axis.highNewValue = highNewValue;
7286 }
7287 break;
7288 }
7289
7290 case EV_SYN:
7291 switch (rawEvent->code) {
7292 case SYN_REPORT:
7293 sync(rawEvent->when, false /*force*/);
7294 break;
7295 }
7296 break;
7297 }
7298}
7299
7300void JoystickInputMapper::sync(nsecs_t when, bool force) {
7301 if (!filterAxes(force)) {
7302 return;
7303 }
7304
7305 int32_t metaState = mContext->getGlobalMetaState();
7306 int32_t buttonState = 0;
7307
7308 PointerProperties pointerProperties;
7309 pointerProperties.clear();
7310 pointerProperties.id = 0;
7311 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7312
7313 PointerCoords pointerCoords;
7314 pointerCoords.clear();
7315
7316 size_t numAxes = mAxes.size();
7317 for (size_t i = 0; i < numAxes; i++) {
7318 const Axis& axis = mAxes.valueAt(i);
7319 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7320 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7321 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7322 axis.highCurrentValue);
7323 }
7324 }
7325
7326 // Moving a joystick axis should not wake the device because joysticks can
7327 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7328 // button will likely wake the device.
7329 // TODO: Use the input device configuration to control this behavior more finely.
7330 uint32_t policyFlags = 0;
7331
7332 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007333 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007334 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7335 getListener()->notifyMotion(&args);
7336}
7337
7338void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7339 int32_t axis, float value) {
7340 pointerCoords->setAxisValue(axis, value);
7341 /* In order to ease the transition for developers from using the old axes
7342 * to the newer, more semantically correct axes, we'll continue to produce
7343 * values for the old axes as mirrors of the value of their corresponding
7344 * new axes. */
7345 int32_t compatAxis = getCompatAxis(axis);
7346 if (compatAxis >= 0) {
7347 pointerCoords->setAxisValue(compatAxis, value);
7348 }
7349}
7350
7351bool JoystickInputMapper::filterAxes(bool force) {
7352 bool atLeastOneSignificantChange = force;
7353 size_t numAxes = mAxes.size();
7354 for (size_t i = 0; i < numAxes; i++) {
7355 Axis& axis = mAxes.editValueAt(i);
7356 if (force || hasValueChangedSignificantly(axis.filter,
7357 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7358 axis.currentValue = axis.newValue;
7359 atLeastOneSignificantChange = true;
7360 }
7361 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7362 if (force || hasValueChangedSignificantly(axis.filter,
7363 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7364 axis.highCurrentValue = axis.highNewValue;
7365 atLeastOneSignificantChange = true;
7366 }
7367 }
7368 }
7369 return atLeastOneSignificantChange;
7370}
7371
7372bool JoystickInputMapper::hasValueChangedSignificantly(
7373 float filter, float newValue, float currentValue, float min, float max) {
7374 if (newValue != currentValue) {
7375 // Filter out small changes in value unless the value is converging on the axis
7376 // bounds or center point. This is intended to reduce the amount of information
7377 // sent to applications by particularly noisy joysticks (such as PS3).
7378 if (fabs(newValue - currentValue) > filter
7379 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7380 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7381 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7382 return true;
7383 }
7384 }
7385 return false;
7386}
7387
7388bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7389 float filter, float newValue, float currentValue, float thresholdValue) {
7390 float newDistance = fabs(newValue - thresholdValue);
7391 if (newDistance < filter) {
7392 float oldDistance = fabs(currentValue - thresholdValue);
7393 if (newDistance < oldDistance) {
7394 return true;
7395 }
7396 }
7397 return false;
7398}
7399
7400} // namespace android