blob: 27009d03b514bfdd3a15fd07f381724a7d7b4c4c [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
Ivan Podogovb9afef32017-02-13 15:34:32 +0000150static int32_t rotateStemKey(int32_t value, int32_t orientation,
151 const int32_t map[][2], size_t mapSize) {
152 if (orientation == DISPLAY_ORIENTATION_180) {
153 for (size_t i = 0; i < mapSize; i++) {
154 if (value == map[i][0]) {
155 return map[i][1];
156 }
157 }
158 }
159 return value;
160}
161
162// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
163static int32_t stemKeyRotationMap[][2] = {
164 // key codes enumerated with the original (unrotated) key first
165 // no rotation, 180 degree rotation
166 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
167 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
168 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
169 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
170};
171static const size_t stemKeyRotationMapSize =
172 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
173
Michael Wrightd02c5b62014-02-10 15:10:22 -0800174static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000175 keyCode = rotateStemKey(keyCode, orientation,
176 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 return rotateValueUsingRotationMap(keyCode, orientation,
178 keyCodeRotationMap, keyCodeRotationMapSize);
179}
180
181static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
182 float temp;
183 switch (orientation) {
184 case DISPLAY_ORIENTATION_90:
185 temp = *deltaX;
186 *deltaX = *deltaY;
187 *deltaY = -temp;
188 break;
189
190 case DISPLAY_ORIENTATION_180:
191 *deltaX = -*deltaX;
192 *deltaY = -*deltaY;
193 break;
194
195 case DISPLAY_ORIENTATION_270:
196 temp = *deltaX;
197 *deltaX = -*deltaY;
198 *deltaY = temp;
199 break;
200 }
201}
202
203static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
204 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
205}
206
207// Returns true if the pointer should be reported as being down given the specified
208// button states. This determines whether the event is reported as a touch event.
209static bool isPointerDown(int32_t buttonState) {
210 return buttonState &
211 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
212 | AMOTION_EVENT_BUTTON_TERTIARY);
213}
214
215static float calculateCommonVector(float a, float b) {
216 if (a > 0 && b > 0) {
217 return a < b ? a : b;
218 } else if (a < 0 && b < 0) {
219 return a > b ? a : b;
220 } else {
221 return 0;
222 }
223}
224
225static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
226 nsecs_t when, int32_t deviceId, uint32_t source,
227 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
228 int32_t buttonState, int32_t keyCode) {
229 if (
230 (action == AKEY_EVENT_ACTION_DOWN
231 && !(lastButtonState & buttonState)
232 && (currentButtonState & buttonState))
233 || (action == AKEY_EVENT_ACTION_UP
234 && (lastButtonState & buttonState)
235 && !(currentButtonState & buttonState))) {
236 NotifyKeyArgs args(when, deviceId, source, policyFlags,
237 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
238 context->getListener()->notifyKey(&args);
239 }
240}
241
242static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
243 nsecs_t when, int32_t deviceId, uint32_t source,
244 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
245 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
246 lastButtonState, currentButtonState,
247 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
248 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
251}
252
253
254// --- InputReaderConfiguration ---
255
Santos Cordonfa5cf462017-04-05 10:37:00 -0700256bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType,
257 const String8* uniqueDisplayId, DisplayViewport* outViewport) const {
258 const DisplayViewport* viewport = NULL;
259 if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != NULL) {
260 for (DisplayViewport currentViewport : mVirtualDisplays) {
261 if (currentViewport.uniqueId == *uniqueDisplayId) {
262 viewport = &currentViewport;
263 break;
264 }
265 }
266 } else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
267 viewport = &mExternalDisplay;
268 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
269 viewport = &mInternalDisplay;
270 }
271
272 if (viewport != NULL && viewport->displayId >= 0) {
273 *outViewport = *viewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274 return true;
275 }
276 return false;
277}
278
Santos Cordonfa5cf462017-04-05 10:37:00 -0700279void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType,
280 const DisplayViewport& viewport) {
281 if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
282 mExternalDisplay = viewport;
283 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
284 mInternalDisplay = viewport;
285 }
286}
287
288void InputReaderConfiguration::setVirtualDisplayViewports(
289 const Vector<DisplayViewport>& viewports) {
290 mVirtualDisplays = viewports;
291}
292
293void InputReaderConfiguration::dump(String8& dump) const {
294 dump.append(INDENT4 "ViewportInternal:\n");
295 dumpViewport(dump, mInternalDisplay);
296 dump.append(INDENT4 "ViewportExternal:\n");
297 dumpViewport(dump, mExternalDisplay);
298 dump.append(INDENT4 "ViewportVirtual:\n");
299 for (const DisplayViewport& viewport : mVirtualDisplays) {
300 dumpViewport(dump, viewport);
301 }
302}
303
304void InputReaderConfiguration::dumpViewport(String8& dump, const DisplayViewport& viewport) const {
305 dump.appendFormat(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', "
306 "logicalFrame=[%d, %d, %d, %d], "
307 "physicalFrame=[%d, %d, %d, %d], "
308 "deviceSize=[%d, %d]\n",
309 viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(),
310 viewport.logicalLeft, viewport.logicalTop,
311 viewport.logicalRight, viewport.logicalBottom,
312 viewport.physicalLeft, viewport.physicalTop,
313 viewport.physicalRight, viewport.physicalBottom,
314 viewport.deviceWidth, viewport.deviceHeight);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800315}
316
317
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700318// -- TouchAffineTransformation --
319void TouchAffineTransformation::applyTo(float& x, float& y) const {
320 float newX, newY;
321 newX = x * x_scale + y * x_ymix + x_offset;
322 newY = x * y_xmix + y * y_scale + y_offset;
323
324 x = newX;
325 y = newY;
326}
327
328
Michael Wrightd02c5b62014-02-10 15:10:22 -0800329// --- InputReader ---
330
331InputReader::InputReader(const sp<EventHubInterface>& eventHub,
332 const sp<InputReaderPolicyInterface>& policy,
333 const sp<InputListenerInterface>& listener) :
334 mContext(this), mEventHub(eventHub), mPolicy(policy),
335 mGlobalMetaState(0), mGeneration(1),
336 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
337 mConfigurationChangesToRefresh(0) {
338 mQueuedListener = new QueuedInputListener(listener);
339
340 { // acquire lock
341 AutoMutex _l(mLock);
342
343 refreshConfigurationLocked(0);
344 updateGlobalMetaStateLocked();
345 } // release lock
346}
347
348InputReader::~InputReader() {
349 for (size_t i = 0; i < mDevices.size(); i++) {
350 delete mDevices.valueAt(i);
351 }
352}
353
354void InputReader::loopOnce() {
355 int32_t oldGeneration;
356 int32_t timeoutMillis;
357 bool inputDevicesChanged = false;
358 Vector<InputDeviceInfo> inputDevices;
359 { // acquire lock
360 AutoMutex _l(mLock);
361
362 oldGeneration = mGeneration;
363 timeoutMillis = -1;
364
365 uint32_t changes = mConfigurationChangesToRefresh;
366 if (changes) {
367 mConfigurationChangesToRefresh = 0;
368 timeoutMillis = 0;
369 refreshConfigurationLocked(changes);
370 } else if (mNextTimeout != LLONG_MAX) {
371 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
372 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
373 }
374 } // release lock
375
376 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
377
378 { // acquire lock
379 AutoMutex _l(mLock);
380 mReaderIsAliveCondition.broadcast();
381
382 if (count) {
383 processEventsLocked(mEventBuffer, count);
384 }
385
386 if (mNextTimeout != LLONG_MAX) {
387 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
388 if (now >= mNextTimeout) {
389#if DEBUG_RAW_EVENTS
390 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
391#endif
392 mNextTimeout = LLONG_MAX;
393 timeoutExpiredLocked(now);
394 }
395 }
396
397 if (oldGeneration != mGeneration) {
398 inputDevicesChanged = true;
399 getInputDevicesLocked(inputDevices);
400 }
401 } // release lock
402
403 // Send out a message that the describes the changed input devices.
404 if (inputDevicesChanged) {
405 mPolicy->notifyInputDevicesChanged(inputDevices);
406 }
407
408 // Flush queued events out to the listener.
409 // This must happen outside of the lock because the listener could potentially call
410 // back into the InputReader's methods, such as getScanCodeState, or become blocked
411 // on another thread similarly waiting to acquire the InputReader lock thereby
412 // resulting in a deadlock. This situation is actually quite plausible because the
413 // listener is actually the input dispatcher, which calls into the window manager,
414 // which occasionally calls into the input reader.
415 mQueuedListener->flush();
416}
417
418void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
419 for (const RawEvent* rawEvent = rawEvents; count;) {
420 int32_t type = rawEvent->type;
421 size_t batchSize = 1;
422 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
423 int32_t deviceId = rawEvent->deviceId;
424 while (batchSize < count) {
425 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
426 || rawEvent[batchSize].deviceId != deviceId) {
427 break;
428 }
429 batchSize += 1;
430 }
431#if DEBUG_RAW_EVENTS
432 ALOGD("BatchSize: %d Count: %d", batchSize, count);
433#endif
434 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
435 } else {
436 switch (rawEvent->type) {
437 case EventHubInterface::DEVICE_ADDED:
438 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
439 break;
440 case EventHubInterface::DEVICE_REMOVED:
441 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
442 break;
443 case EventHubInterface::FINISHED_DEVICE_SCAN:
444 handleConfigurationChangedLocked(rawEvent->when);
445 break;
446 default:
447 ALOG_ASSERT(false); // can't happen
448 break;
449 }
450 }
451 count -= batchSize;
452 rawEvent += batchSize;
453 }
454}
455
456void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
457 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
458 if (deviceIndex >= 0) {
459 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
460 return;
461 }
462
463 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
464 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
465 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
466
467 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
468 device->configure(when, &mConfig, 0);
469 device->reset(when);
470
471 if (device->isIgnored()) {
472 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
473 identifier.name.string());
474 } else {
475 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
476 identifier.name.string(), device->getSources());
477 }
478
479 mDevices.add(deviceId, device);
480 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700481
482 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
483 notifyExternalStylusPresenceChanged();
484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485}
486
487void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
488 InputDevice* device = NULL;
489 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
490 if (deviceIndex < 0) {
491 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
492 return;
493 }
494
495 device = mDevices.valueAt(deviceIndex);
496 mDevices.removeItemsAt(deviceIndex, 1);
497 bumpGenerationLocked();
498
499 if (device->isIgnored()) {
500 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
501 device->getId(), device->getName().string());
502 } else {
503 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
504 device->getId(), device->getName().string(), device->getSources());
505 }
506
Michael Wright842500e2015-03-13 17:32:02 -0700507 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
508 notifyExternalStylusPresenceChanged();
509 }
510
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 device->reset(when);
512 delete device;
513}
514
515InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
516 const InputDeviceIdentifier& identifier, uint32_t classes) {
517 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
518 controllerNumber, identifier, classes);
519
520 // External devices.
521 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
522 device->setExternal(true);
523 }
524
Tim Kilbourn063ff532015-04-08 10:26:18 -0700525 // Devices with mics.
526 if (classes & INPUT_DEVICE_CLASS_MIC) {
527 device->setMic(true);
528 }
529
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 // Switch-like devices.
531 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
532 device->addMapper(new SwitchInputMapper(device));
533 }
534
Prashant Malani1941ff52015-08-11 18:29:28 -0700535 // Scroll wheel-like devices.
536 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
537 device->addMapper(new RotaryEncoderInputMapper(device));
538 }
539
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 // Vibrator-like devices.
541 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
542 device->addMapper(new VibratorInputMapper(device));
543 }
544
545 // Keyboard-like devices.
546 uint32_t keyboardSource = 0;
547 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
548 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
549 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
550 }
551 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
552 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
553 }
554 if (classes & INPUT_DEVICE_CLASS_DPAD) {
555 keyboardSource |= AINPUT_SOURCE_DPAD;
556 }
557 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
558 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
559 }
560
561 if (keyboardSource != 0) {
562 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
563 }
564
565 // Cursor-like devices.
566 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
567 device->addMapper(new CursorInputMapper(device));
568 }
569
570 // Touchscreens and touchpad devices.
571 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
572 device->addMapper(new MultiTouchInputMapper(device));
573 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
574 device->addMapper(new SingleTouchInputMapper(device));
575 }
576
577 // Joystick-like devices.
578 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
579 device->addMapper(new JoystickInputMapper(device));
580 }
581
Michael Wright842500e2015-03-13 17:32:02 -0700582 // External stylus-like devices.
583 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
584 device->addMapper(new ExternalStylusInputMapper(device));
585 }
586
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 return device;
588}
589
590void InputReader::processEventsForDeviceLocked(int32_t deviceId,
591 const RawEvent* rawEvents, size_t count) {
592 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
593 if (deviceIndex < 0) {
594 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
595 return;
596 }
597
598 InputDevice* device = mDevices.valueAt(deviceIndex);
599 if (device->isIgnored()) {
600 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
601 return;
602 }
603
604 device->process(rawEvents, count);
605}
606
607void InputReader::timeoutExpiredLocked(nsecs_t when) {
608 for (size_t i = 0; i < mDevices.size(); i++) {
609 InputDevice* device = mDevices.valueAt(i);
610 if (!device->isIgnored()) {
611 device->timeoutExpired(when);
612 }
613 }
614}
615
616void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
617 // Reset global meta state because it depends on the list of all configured devices.
618 updateGlobalMetaStateLocked();
619
620 // Enqueue configuration changed.
621 NotifyConfigurationChangedArgs args(when);
622 mQueuedListener->notifyConfigurationChanged(&args);
623}
624
625void InputReader::refreshConfigurationLocked(uint32_t changes) {
626 mPolicy->getReaderConfiguration(&mConfig);
627 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
628
629 if (changes) {
630 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
631 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
632
633 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
634 mEventHub->requestReopenDevices();
635 } else {
636 for (size_t i = 0; i < mDevices.size(); i++) {
637 InputDevice* device = mDevices.valueAt(i);
638 device->configure(now, &mConfig, changes);
639 }
640 }
641 }
642}
643
644void InputReader::updateGlobalMetaStateLocked() {
645 mGlobalMetaState = 0;
646
647 for (size_t i = 0; i < mDevices.size(); i++) {
648 InputDevice* device = mDevices.valueAt(i);
649 mGlobalMetaState |= device->getMetaState();
650 }
651}
652
653int32_t InputReader::getGlobalMetaStateLocked() {
654 return mGlobalMetaState;
655}
656
Michael Wright842500e2015-03-13 17:32:02 -0700657void InputReader::notifyExternalStylusPresenceChanged() {
658 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
659}
660
661void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
662 for (size_t i = 0; i < mDevices.size(); i++) {
663 InputDevice* device = mDevices.valueAt(i);
664 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
665 outDevices.push();
666 device->getDeviceInfo(&outDevices.editTop());
667 }
668 }
669}
670
671void InputReader::dispatchExternalStylusState(const StylusState& state) {
672 for (size_t i = 0; i < mDevices.size(); i++) {
673 InputDevice* device = mDevices.valueAt(i);
674 device->updateExternalStylusState(state);
675 }
676}
677
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
679 mDisableVirtualKeysTimeout = time;
680}
681
682bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
683 InputDevice* device, int32_t keyCode, int32_t scanCode) {
684 if (now < mDisableVirtualKeysTimeout) {
685 ALOGI("Dropping virtual key from device %s because virtual keys are "
686 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
687 device->getName().string(),
688 (mDisableVirtualKeysTimeout - now) * 0.000001,
689 keyCode, scanCode);
690 return true;
691 } else {
692 return false;
693 }
694}
695
696void InputReader::fadePointerLocked() {
697 for (size_t i = 0; i < mDevices.size(); i++) {
698 InputDevice* device = mDevices.valueAt(i);
699 device->fadePointer();
700 }
701}
702
703void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
704 if (when < mNextTimeout) {
705 mNextTimeout = when;
706 mEventHub->wake();
707 }
708}
709
710int32_t InputReader::bumpGenerationLocked() {
711 return ++mGeneration;
712}
713
714void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
715 AutoMutex _l(mLock);
716 getInputDevicesLocked(outInputDevices);
717}
718
719void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
720 outInputDevices.clear();
721
722 size_t numDevices = mDevices.size();
723 for (size_t i = 0; i < numDevices; i++) {
724 InputDevice* device = mDevices.valueAt(i);
725 if (!device->isIgnored()) {
726 outInputDevices.push();
727 device->getDeviceInfo(&outInputDevices.editTop());
728 }
729 }
730}
731
732int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
733 int32_t keyCode) {
734 AutoMutex _l(mLock);
735
736 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
737}
738
739int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
740 int32_t scanCode) {
741 AutoMutex _l(mLock);
742
743 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
744}
745
746int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
747 AutoMutex _l(mLock);
748
749 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
750}
751
752int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
753 GetStateFunc getStateFunc) {
754 int32_t result = AKEY_STATE_UNKNOWN;
755 if (deviceId >= 0) {
756 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
757 if (deviceIndex >= 0) {
758 InputDevice* device = mDevices.valueAt(deviceIndex);
759 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
760 result = (device->*getStateFunc)(sourceMask, code);
761 }
762 }
763 } else {
764 size_t numDevices = mDevices.size();
765 for (size_t i = 0; i < numDevices; i++) {
766 InputDevice* device = mDevices.valueAt(i);
767 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
768 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
769 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
770 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
771 if (currentResult >= AKEY_STATE_DOWN) {
772 return currentResult;
773 } else if (currentResult == AKEY_STATE_UP) {
774 result = currentResult;
775 }
776 }
777 }
778 }
779 return result;
780}
781
Andrii Kulian763a3a42016-03-08 10:46:16 -0800782void InputReader::toggleCapsLockState(int32_t deviceId) {
783 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
784 if (deviceIndex < 0) {
785 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
786 return;
787 }
788
789 InputDevice* device = mDevices.valueAt(deviceIndex);
790 if (device->isIgnored()) {
791 return;
792 }
793
794 device->updateMetaState(AKEYCODE_CAPS_LOCK);
795}
796
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
798 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
799 AutoMutex _l(mLock);
800
801 memset(outFlags, 0, numCodes);
802 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
803}
804
805bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
806 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
807 bool result = false;
808 if (deviceId >= 0) {
809 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
810 if (deviceIndex >= 0) {
811 InputDevice* device = mDevices.valueAt(deviceIndex);
812 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
813 result = device->markSupportedKeyCodes(sourceMask,
814 numCodes, keyCodes, outFlags);
815 }
816 }
817 } else {
818 size_t numDevices = mDevices.size();
819 for (size_t i = 0; i < numDevices; i++) {
820 InputDevice* device = mDevices.valueAt(i);
821 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
822 result |= device->markSupportedKeyCodes(sourceMask,
823 numCodes, keyCodes, outFlags);
824 }
825 }
826 }
827 return result;
828}
829
830void InputReader::requestRefreshConfiguration(uint32_t changes) {
831 AutoMutex _l(mLock);
832
833 if (changes) {
834 bool needWake = !mConfigurationChangesToRefresh;
835 mConfigurationChangesToRefresh |= changes;
836
837 if (needWake) {
838 mEventHub->wake();
839 }
840 }
841}
842
843void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
844 ssize_t repeat, int32_t token) {
845 AutoMutex _l(mLock);
846
847 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
848 if (deviceIndex >= 0) {
849 InputDevice* device = mDevices.valueAt(deviceIndex);
850 device->vibrate(pattern, patternSize, repeat, token);
851 }
852}
853
854void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
855 AutoMutex _l(mLock);
856
857 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
858 if (deviceIndex >= 0) {
859 InputDevice* device = mDevices.valueAt(deviceIndex);
860 device->cancelVibrate(token);
861 }
862}
863
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700864bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
865 AutoMutex _l(mLock);
866
867 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
868 if (deviceIndex >= 0) {
869 InputDevice* device = mDevices.valueAt(deviceIndex);
870 return device->isEnabled();
871 }
872 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
873 return false;
874}
875
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876void InputReader::dump(String8& dump) {
877 AutoMutex _l(mLock);
878
879 mEventHub->dump(dump);
880 dump.append("\n");
881
882 dump.append("Input Reader State:\n");
883
884 for (size_t i = 0; i < mDevices.size(); i++) {
885 mDevices.valueAt(i)->dump(dump);
886 }
887
888 dump.append(INDENT "Configuration:\n");
889 dump.append(INDENT2 "ExcludedDeviceNames: [");
890 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
891 if (i != 0) {
892 dump.append(", ");
893 }
894 dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
895 }
896 dump.append("]\n");
897 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
898 mConfig.virtualKeyQuietTime * 0.000001f);
899
900 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
901 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
902 mConfig.pointerVelocityControlParameters.scale,
903 mConfig.pointerVelocityControlParameters.lowThreshold,
904 mConfig.pointerVelocityControlParameters.highThreshold,
905 mConfig.pointerVelocityControlParameters.acceleration);
906
907 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
908 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
909 mConfig.wheelVelocityControlParameters.scale,
910 mConfig.wheelVelocityControlParameters.lowThreshold,
911 mConfig.wheelVelocityControlParameters.highThreshold,
912 mConfig.wheelVelocityControlParameters.acceleration);
913
914 dump.appendFormat(INDENT2 "PointerGesture:\n");
915 dump.appendFormat(INDENT3 "Enabled: %s\n",
916 toString(mConfig.pointerGesturesEnabled));
917 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
918 mConfig.pointerGestureQuietInterval * 0.000001f);
919 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
920 mConfig.pointerGestureDragMinSwitchSpeed);
921 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
922 mConfig.pointerGestureTapInterval * 0.000001f);
923 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
924 mConfig.pointerGestureTapDragInterval * 0.000001f);
925 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
926 mConfig.pointerGestureTapSlop);
927 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
928 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
929 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
930 mConfig.pointerGestureMultitouchMinDistance);
931 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
932 mConfig.pointerGestureSwipeTransitionAngleCosine);
933 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
934 mConfig.pointerGestureSwipeMaxWidthRatio);
935 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
936 mConfig.pointerGestureMovementSpeedRatio);
937 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
938 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700939
940 dump.append(INDENT3 "Viewports:\n");
941 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942}
943
944void InputReader::monitor() {
945 // Acquire and release the lock to ensure that the reader has not deadlocked.
946 mLock.lock();
947 mEventHub->wake();
948 mReaderIsAliveCondition.wait(mLock);
949 mLock.unlock();
950
951 // Check the EventHub
952 mEventHub->monitor();
953}
954
955
956// --- InputReader::ContextImpl ---
957
958InputReader::ContextImpl::ContextImpl(InputReader* reader) :
959 mReader(reader) {
960}
961
962void InputReader::ContextImpl::updateGlobalMetaState() {
963 // lock is already held by the input loop
964 mReader->updateGlobalMetaStateLocked();
965}
966
967int32_t InputReader::ContextImpl::getGlobalMetaState() {
968 // lock is already held by the input loop
969 return mReader->getGlobalMetaStateLocked();
970}
971
972void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
973 // lock is already held by the input loop
974 mReader->disableVirtualKeysUntilLocked(time);
975}
976
977bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
978 InputDevice* device, int32_t keyCode, int32_t scanCode) {
979 // lock is already held by the input loop
980 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
981}
982
983void InputReader::ContextImpl::fadePointer() {
984 // lock is already held by the input loop
985 mReader->fadePointerLocked();
986}
987
988void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
989 // lock is already held by the input loop
990 mReader->requestTimeoutAtTimeLocked(when);
991}
992
993int32_t InputReader::ContextImpl::bumpGeneration() {
994 // lock is already held by the input loop
995 return mReader->bumpGenerationLocked();
996}
997
Michael Wright842500e2015-03-13 17:32:02 -0700998void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
999 // lock is already held by whatever called refreshConfigurationLocked
1000 mReader->getExternalStylusDevicesLocked(outDevices);
1001}
1002
1003void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
1004 mReader->dispatchExternalStylusState(state);
1005}
1006
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
1008 return mReader->mPolicy.get();
1009}
1010
1011InputListenerInterface* InputReader::ContextImpl::getListener() {
1012 return mReader->mQueuedListener.get();
1013}
1014
1015EventHubInterface* InputReader::ContextImpl::getEventHub() {
1016 return mReader->mEventHub.get();
1017}
1018
1019
1020// --- InputReaderThread ---
1021
1022InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
1023 Thread(/*canCallJava*/ true), mReader(reader) {
1024}
1025
1026InputReaderThread::~InputReaderThread() {
1027}
1028
1029bool InputReaderThread::threadLoop() {
1030 mReader->loopOnce();
1031 return true;
1032}
1033
1034
1035// --- InputDevice ---
1036
1037InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1038 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1039 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1040 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001041 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042}
1043
1044InputDevice::~InputDevice() {
1045 size_t numMappers = mMappers.size();
1046 for (size_t i = 0; i < numMappers; i++) {
1047 delete mMappers[i];
1048 }
1049 mMappers.clear();
1050}
1051
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001052bool InputDevice::isEnabled() {
1053 return getEventHub()->isDeviceEnabled(mId);
1054}
1055
1056void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1057 if (isEnabled() == enabled) {
1058 return;
1059 }
1060
1061 if (enabled) {
1062 getEventHub()->enableDevice(mId);
1063 reset(when);
1064 } else {
1065 reset(when);
1066 getEventHub()->disableDevice(mId);
1067 }
1068 // Must change generation to flag this device as changed
1069 bumpGeneration();
1070}
1071
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072void InputDevice::dump(String8& dump) {
1073 InputDeviceInfo deviceInfo;
1074 getDeviceInfo(& deviceInfo);
1075
1076 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
1077 deviceInfo.getDisplayName().string());
1078 dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
1079 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Tim Kilbourn063ff532015-04-08 10:26:18 -07001080 dump.appendFormat(INDENT2 "HasMic: %s\n", toString(mHasMic));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1082 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
1083
1084 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1085 if (!ranges.isEmpty()) {
1086 dump.append(INDENT2 "Motion Ranges:\n");
1087 for (size_t i = 0; i < ranges.size(); i++) {
1088 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1089 const char* label = getAxisLabel(range.axis);
1090 char name[32];
1091 if (label) {
1092 strncpy(name, label, sizeof(name));
1093 name[sizeof(name) - 1] = '\0';
1094 } else {
1095 snprintf(name, sizeof(name), "%d", range.axis);
1096 }
1097 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
1098 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1099 name, range.source, range.min, range.max, range.flat, range.fuzz,
1100 range.resolution);
1101 }
1102 }
1103
1104 size_t numMappers = mMappers.size();
1105 for (size_t i = 0; i < numMappers; i++) {
1106 InputMapper* mapper = mMappers[i];
1107 mapper->dump(dump);
1108 }
1109}
1110
1111void InputDevice::addMapper(InputMapper* mapper) {
1112 mMappers.add(mapper);
1113}
1114
1115void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1116 mSources = 0;
1117
1118 if (!isIgnored()) {
1119 if (!changes) { // first time only
1120 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1121 }
1122
1123 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1124 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1125 sp<KeyCharacterMap> keyboardLayout =
1126 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1127 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1128 bumpGeneration();
1129 }
1130 }
1131 }
1132
1133 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1134 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1135 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1136 if (mAlias != alias) {
1137 mAlias = alias;
1138 bumpGeneration();
1139 }
1140 }
1141 }
1142
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001143 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1144 ssize_t index = config->disabledDevices.indexOf(mId);
1145 bool enabled = index < 0;
1146 setEnabled(enabled, when);
1147 }
1148
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 size_t numMappers = mMappers.size();
1150 for (size_t i = 0; i < numMappers; i++) {
1151 InputMapper* mapper = mMappers[i];
1152 mapper->configure(when, config, changes);
1153 mSources |= mapper->getSources();
1154 }
1155 }
1156}
1157
1158void InputDevice::reset(nsecs_t when) {
1159 size_t numMappers = mMappers.size();
1160 for (size_t i = 0; i < numMappers; i++) {
1161 InputMapper* mapper = mMappers[i];
1162 mapper->reset(when);
1163 }
1164
1165 mContext->updateGlobalMetaState();
1166
1167 notifyReset(when);
1168}
1169
1170void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1171 // Process all of the events in order for each mapper.
1172 // We cannot simply ask each mapper to process them in bulk because mappers may
1173 // have side-effects that must be interleaved. For example, joystick movement events and
1174 // gamepad button presses are handled by different mappers but they should be dispatched
1175 // in the order received.
1176 size_t numMappers = mMappers.size();
1177 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
1178#if DEBUG_RAW_EVENTS
1179 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
1180 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1181 rawEvent->when);
1182#endif
1183
1184 if (mDropUntilNextSync) {
1185 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1186 mDropUntilNextSync = false;
1187#if DEBUG_RAW_EVENTS
1188 ALOGD("Recovered from input event buffer overrun.");
1189#endif
1190 } else {
1191#if DEBUG_RAW_EVENTS
1192 ALOGD("Dropped input event while waiting for next input sync.");
1193#endif
1194 }
1195 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1196 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1197 mDropUntilNextSync = true;
1198 reset(rawEvent->when);
1199 } else {
1200 for (size_t i = 0; i < numMappers; i++) {
1201 InputMapper* mapper = mMappers[i];
1202 mapper->process(rawEvent);
1203 }
1204 }
1205 }
1206}
1207
1208void InputDevice::timeoutExpired(nsecs_t when) {
1209 size_t numMappers = mMappers.size();
1210 for (size_t i = 0; i < numMappers; i++) {
1211 InputMapper* mapper = mMappers[i];
1212 mapper->timeoutExpired(when);
1213 }
1214}
1215
Michael Wright842500e2015-03-13 17:32:02 -07001216void InputDevice::updateExternalStylusState(const StylusState& state) {
1217 size_t numMappers = mMappers.size();
1218 for (size_t i = 0; i < numMappers; i++) {
1219 InputMapper* mapper = mMappers[i];
1220 mapper->updateExternalStylusState(state);
1221 }
1222}
1223
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1225 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001226 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 size_t numMappers = mMappers.size();
1228 for (size_t i = 0; i < numMappers; i++) {
1229 InputMapper* mapper = mMappers[i];
1230 mapper->populateDeviceInfo(outDeviceInfo);
1231 }
1232}
1233
1234int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1235 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1236}
1237
1238int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1239 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1240}
1241
1242int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1243 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1244}
1245
1246int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1247 int32_t result = AKEY_STATE_UNKNOWN;
1248 size_t numMappers = mMappers.size();
1249 for (size_t i = 0; i < numMappers; i++) {
1250 InputMapper* mapper = mMappers[i];
1251 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1252 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1253 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1254 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1255 if (currentResult >= AKEY_STATE_DOWN) {
1256 return currentResult;
1257 } else if (currentResult == AKEY_STATE_UP) {
1258 result = currentResult;
1259 }
1260 }
1261 }
1262 return result;
1263}
1264
1265bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1266 const int32_t* keyCodes, uint8_t* outFlags) {
1267 bool result = false;
1268 size_t numMappers = mMappers.size();
1269 for (size_t i = 0; i < numMappers; i++) {
1270 InputMapper* mapper = mMappers[i];
1271 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1272 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1273 }
1274 }
1275 return result;
1276}
1277
1278void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1279 int32_t token) {
1280 size_t numMappers = mMappers.size();
1281 for (size_t i = 0; i < numMappers; i++) {
1282 InputMapper* mapper = mMappers[i];
1283 mapper->vibrate(pattern, patternSize, repeat, token);
1284 }
1285}
1286
1287void InputDevice::cancelVibrate(int32_t token) {
1288 size_t numMappers = mMappers.size();
1289 for (size_t i = 0; i < numMappers; i++) {
1290 InputMapper* mapper = mMappers[i];
1291 mapper->cancelVibrate(token);
1292 }
1293}
1294
Jeff Brownc9aa6282015-02-11 19:03:28 -08001295void InputDevice::cancelTouch(nsecs_t when) {
1296 size_t numMappers = mMappers.size();
1297 for (size_t i = 0; i < numMappers; i++) {
1298 InputMapper* mapper = mMappers[i];
1299 mapper->cancelTouch(when);
1300 }
1301}
1302
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303int32_t InputDevice::getMetaState() {
1304 int32_t result = 0;
1305 size_t numMappers = mMappers.size();
1306 for (size_t i = 0; i < numMappers; i++) {
1307 InputMapper* mapper = mMappers[i];
1308 result |= mapper->getMetaState();
1309 }
1310 return result;
1311}
1312
Andrii Kulian763a3a42016-03-08 10:46:16 -08001313void InputDevice::updateMetaState(int32_t keyCode) {
1314 size_t numMappers = mMappers.size();
1315 for (size_t i = 0; i < numMappers; i++) {
1316 mMappers[i]->updateMetaState(keyCode);
1317 }
1318}
1319
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320void InputDevice::fadePointer() {
1321 size_t numMappers = mMappers.size();
1322 for (size_t i = 0; i < numMappers; i++) {
1323 InputMapper* mapper = mMappers[i];
1324 mapper->fadePointer();
1325 }
1326}
1327
1328void InputDevice::bumpGeneration() {
1329 mGeneration = mContext->bumpGeneration();
1330}
1331
1332void InputDevice::notifyReset(nsecs_t when) {
1333 NotifyDeviceResetArgs args(when, mId);
1334 mContext->getListener()->notifyDeviceReset(&args);
1335}
1336
1337
1338// --- CursorButtonAccumulator ---
1339
1340CursorButtonAccumulator::CursorButtonAccumulator() {
1341 clearButtons();
1342}
1343
1344void CursorButtonAccumulator::reset(InputDevice* device) {
1345 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1346 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1347 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1348 mBtnBack = device->isKeyPressed(BTN_BACK);
1349 mBtnSide = device->isKeyPressed(BTN_SIDE);
1350 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1351 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1352 mBtnTask = device->isKeyPressed(BTN_TASK);
1353}
1354
1355void CursorButtonAccumulator::clearButtons() {
1356 mBtnLeft = 0;
1357 mBtnRight = 0;
1358 mBtnMiddle = 0;
1359 mBtnBack = 0;
1360 mBtnSide = 0;
1361 mBtnForward = 0;
1362 mBtnExtra = 0;
1363 mBtnTask = 0;
1364}
1365
1366void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1367 if (rawEvent->type == EV_KEY) {
1368 switch (rawEvent->code) {
1369 case BTN_LEFT:
1370 mBtnLeft = rawEvent->value;
1371 break;
1372 case BTN_RIGHT:
1373 mBtnRight = rawEvent->value;
1374 break;
1375 case BTN_MIDDLE:
1376 mBtnMiddle = rawEvent->value;
1377 break;
1378 case BTN_BACK:
1379 mBtnBack = rawEvent->value;
1380 break;
1381 case BTN_SIDE:
1382 mBtnSide = rawEvent->value;
1383 break;
1384 case BTN_FORWARD:
1385 mBtnForward = rawEvent->value;
1386 break;
1387 case BTN_EXTRA:
1388 mBtnExtra = rawEvent->value;
1389 break;
1390 case BTN_TASK:
1391 mBtnTask = rawEvent->value;
1392 break;
1393 }
1394 }
1395}
1396
1397uint32_t CursorButtonAccumulator::getButtonState() const {
1398 uint32_t result = 0;
1399 if (mBtnLeft) {
1400 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1401 }
1402 if (mBtnRight) {
1403 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1404 }
1405 if (mBtnMiddle) {
1406 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1407 }
1408 if (mBtnBack || mBtnSide) {
1409 result |= AMOTION_EVENT_BUTTON_BACK;
1410 }
1411 if (mBtnForward || mBtnExtra) {
1412 result |= AMOTION_EVENT_BUTTON_FORWARD;
1413 }
1414 return result;
1415}
1416
1417
1418// --- CursorMotionAccumulator ---
1419
1420CursorMotionAccumulator::CursorMotionAccumulator() {
1421 clearRelativeAxes();
1422}
1423
1424void CursorMotionAccumulator::reset(InputDevice* device) {
1425 clearRelativeAxes();
1426}
1427
1428void CursorMotionAccumulator::clearRelativeAxes() {
1429 mRelX = 0;
1430 mRelY = 0;
1431}
1432
1433void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1434 if (rawEvent->type == EV_REL) {
1435 switch (rawEvent->code) {
1436 case REL_X:
1437 mRelX = rawEvent->value;
1438 break;
1439 case REL_Y:
1440 mRelY = rawEvent->value;
1441 break;
1442 }
1443 }
1444}
1445
1446void CursorMotionAccumulator::finishSync() {
1447 clearRelativeAxes();
1448}
1449
1450
1451// --- CursorScrollAccumulator ---
1452
1453CursorScrollAccumulator::CursorScrollAccumulator() :
1454 mHaveRelWheel(false), mHaveRelHWheel(false) {
1455 clearRelativeAxes();
1456}
1457
1458void CursorScrollAccumulator::configure(InputDevice* device) {
1459 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1460 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1461}
1462
1463void CursorScrollAccumulator::reset(InputDevice* device) {
1464 clearRelativeAxes();
1465}
1466
1467void CursorScrollAccumulator::clearRelativeAxes() {
1468 mRelWheel = 0;
1469 mRelHWheel = 0;
1470}
1471
1472void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1473 if (rawEvent->type == EV_REL) {
1474 switch (rawEvent->code) {
1475 case REL_WHEEL:
1476 mRelWheel = rawEvent->value;
1477 break;
1478 case REL_HWHEEL:
1479 mRelHWheel = rawEvent->value;
1480 break;
1481 }
1482 }
1483}
1484
1485void CursorScrollAccumulator::finishSync() {
1486 clearRelativeAxes();
1487}
1488
1489
1490// --- TouchButtonAccumulator ---
1491
1492TouchButtonAccumulator::TouchButtonAccumulator() :
1493 mHaveBtnTouch(false), mHaveStylus(false) {
1494 clearButtons();
1495}
1496
1497void TouchButtonAccumulator::configure(InputDevice* device) {
1498 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1499 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1500 || device->hasKey(BTN_TOOL_RUBBER)
1501 || device->hasKey(BTN_TOOL_BRUSH)
1502 || device->hasKey(BTN_TOOL_PENCIL)
1503 || device->hasKey(BTN_TOOL_AIRBRUSH);
1504}
1505
1506void TouchButtonAccumulator::reset(InputDevice* device) {
1507 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1508 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001509 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1510 mBtnStylus2 =
1511 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1513 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1514 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1515 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1516 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1517 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1518 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1519 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1520 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1521 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1522 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1523}
1524
1525void TouchButtonAccumulator::clearButtons() {
1526 mBtnTouch = 0;
1527 mBtnStylus = 0;
1528 mBtnStylus2 = 0;
1529 mBtnToolFinger = 0;
1530 mBtnToolPen = 0;
1531 mBtnToolRubber = 0;
1532 mBtnToolBrush = 0;
1533 mBtnToolPencil = 0;
1534 mBtnToolAirbrush = 0;
1535 mBtnToolMouse = 0;
1536 mBtnToolLens = 0;
1537 mBtnToolDoubleTap = 0;
1538 mBtnToolTripleTap = 0;
1539 mBtnToolQuadTap = 0;
1540}
1541
1542void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1543 if (rawEvent->type == EV_KEY) {
1544 switch (rawEvent->code) {
1545 case BTN_TOUCH:
1546 mBtnTouch = rawEvent->value;
1547 break;
1548 case BTN_STYLUS:
1549 mBtnStylus = rawEvent->value;
1550 break;
1551 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001552 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 mBtnStylus2 = rawEvent->value;
1554 break;
1555 case BTN_TOOL_FINGER:
1556 mBtnToolFinger = rawEvent->value;
1557 break;
1558 case BTN_TOOL_PEN:
1559 mBtnToolPen = rawEvent->value;
1560 break;
1561 case BTN_TOOL_RUBBER:
1562 mBtnToolRubber = rawEvent->value;
1563 break;
1564 case BTN_TOOL_BRUSH:
1565 mBtnToolBrush = rawEvent->value;
1566 break;
1567 case BTN_TOOL_PENCIL:
1568 mBtnToolPencil = rawEvent->value;
1569 break;
1570 case BTN_TOOL_AIRBRUSH:
1571 mBtnToolAirbrush = rawEvent->value;
1572 break;
1573 case BTN_TOOL_MOUSE:
1574 mBtnToolMouse = rawEvent->value;
1575 break;
1576 case BTN_TOOL_LENS:
1577 mBtnToolLens = rawEvent->value;
1578 break;
1579 case BTN_TOOL_DOUBLETAP:
1580 mBtnToolDoubleTap = rawEvent->value;
1581 break;
1582 case BTN_TOOL_TRIPLETAP:
1583 mBtnToolTripleTap = rawEvent->value;
1584 break;
1585 case BTN_TOOL_QUADTAP:
1586 mBtnToolQuadTap = rawEvent->value;
1587 break;
1588 }
1589 }
1590}
1591
1592uint32_t TouchButtonAccumulator::getButtonState() const {
1593 uint32_t result = 0;
1594 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001595 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 }
1597 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001598 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
1600 return result;
1601}
1602
1603int32_t TouchButtonAccumulator::getToolType() const {
1604 if (mBtnToolMouse || mBtnToolLens) {
1605 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1606 }
1607 if (mBtnToolRubber) {
1608 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1609 }
1610 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1611 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1612 }
1613 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1614 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1615 }
1616 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1617}
1618
1619bool TouchButtonAccumulator::isToolActive() const {
1620 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1621 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1622 || mBtnToolMouse || mBtnToolLens
1623 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1624}
1625
1626bool TouchButtonAccumulator::isHovering() const {
1627 return mHaveBtnTouch && !mBtnTouch;
1628}
1629
1630bool TouchButtonAccumulator::hasStylus() const {
1631 return mHaveStylus;
1632}
1633
1634
1635// --- RawPointerAxes ---
1636
1637RawPointerAxes::RawPointerAxes() {
1638 clear();
1639}
1640
1641void RawPointerAxes::clear() {
1642 x.clear();
1643 y.clear();
1644 pressure.clear();
1645 touchMajor.clear();
1646 touchMinor.clear();
1647 toolMajor.clear();
1648 toolMinor.clear();
1649 orientation.clear();
1650 distance.clear();
1651 tiltX.clear();
1652 tiltY.clear();
1653 trackingId.clear();
1654 slot.clear();
1655}
1656
1657
1658// --- RawPointerData ---
1659
1660RawPointerData::RawPointerData() {
1661 clear();
1662}
1663
1664void RawPointerData::clear() {
1665 pointerCount = 0;
1666 clearIdBits();
1667}
1668
1669void RawPointerData::copyFrom(const RawPointerData& other) {
1670 pointerCount = other.pointerCount;
1671 hoveringIdBits = other.hoveringIdBits;
1672 touchingIdBits = other.touchingIdBits;
1673
1674 for (uint32_t i = 0; i < pointerCount; i++) {
1675 pointers[i] = other.pointers[i];
1676
1677 int id = pointers[i].id;
1678 idToIndex[id] = other.idToIndex[id];
1679 }
1680}
1681
1682void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1683 float x = 0, y = 0;
1684 uint32_t count = touchingIdBits.count();
1685 if (count) {
1686 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1687 uint32_t id = idBits.clearFirstMarkedBit();
1688 const Pointer& pointer = pointerForId(id);
1689 x += pointer.x;
1690 y += pointer.y;
1691 }
1692 x /= count;
1693 y /= count;
1694 }
1695 *outX = x;
1696 *outY = y;
1697}
1698
1699
1700// --- CookedPointerData ---
1701
1702CookedPointerData::CookedPointerData() {
1703 clear();
1704}
1705
1706void CookedPointerData::clear() {
1707 pointerCount = 0;
1708 hoveringIdBits.clear();
1709 touchingIdBits.clear();
1710}
1711
1712void CookedPointerData::copyFrom(const CookedPointerData& other) {
1713 pointerCount = other.pointerCount;
1714 hoveringIdBits = other.hoveringIdBits;
1715 touchingIdBits = other.touchingIdBits;
1716
1717 for (uint32_t i = 0; i < pointerCount; i++) {
1718 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1719 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1720
1721 int id = pointerProperties[i].id;
1722 idToIndex[id] = other.idToIndex[id];
1723 }
1724}
1725
1726
1727// --- SingleTouchMotionAccumulator ---
1728
1729SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1730 clearAbsoluteAxes();
1731}
1732
1733void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1734 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1735 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1736 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1737 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1738 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1739 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1740 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1741}
1742
1743void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1744 mAbsX = 0;
1745 mAbsY = 0;
1746 mAbsPressure = 0;
1747 mAbsToolWidth = 0;
1748 mAbsDistance = 0;
1749 mAbsTiltX = 0;
1750 mAbsTiltY = 0;
1751}
1752
1753void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1754 if (rawEvent->type == EV_ABS) {
1755 switch (rawEvent->code) {
1756 case ABS_X:
1757 mAbsX = rawEvent->value;
1758 break;
1759 case ABS_Y:
1760 mAbsY = rawEvent->value;
1761 break;
1762 case ABS_PRESSURE:
1763 mAbsPressure = rawEvent->value;
1764 break;
1765 case ABS_TOOL_WIDTH:
1766 mAbsToolWidth = rawEvent->value;
1767 break;
1768 case ABS_DISTANCE:
1769 mAbsDistance = rawEvent->value;
1770 break;
1771 case ABS_TILT_X:
1772 mAbsTiltX = rawEvent->value;
1773 break;
1774 case ABS_TILT_Y:
1775 mAbsTiltY = rawEvent->value;
1776 break;
1777 }
1778 }
1779}
1780
1781
1782// --- MultiTouchMotionAccumulator ---
1783
1784MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1785 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1786 mHaveStylus(false) {
1787}
1788
1789MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1790 delete[] mSlots;
1791}
1792
1793void MultiTouchMotionAccumulator::configure(InputDevice* device,
1794 size_t slotCount, bool usingSlotsProtocol) {
1795 mSlotCount = slotCount;
1796 mUsingSlotsProtocol = usingSlotsProtocol;
1797 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1798
1799 delete[] mSlots;
1800 mSlots = new Slot[slotCount];
1801}
1802
1803void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1804 // Unfortunately there is no way to read the initial contents of the slots.
1805 // So when we reset the accumulator, we must assume they are all zeroes.
1806 if (mUsingSlotsProtocol) {
1807 // Query the driver for the current slot index and use it as the initial slot
1808 // before we start reading events from the device. It is possible that the
1809 // current slot index will not be the same as it was when the first event was
1810 // written into the evdev buffer, which means the input mapper could start
1811 // out of sync with the initial state of the events in the evdev buffer.
1812 // In the extremely unlikely case that this happens, the data from
1813 // two slots will be confused until the next ABS_MT_SLOT event is received.
1814 // This can cause the touch point to "jump", but at least there will be
1815 // no stuck touches.
1816 int32_t initialSlot;
1817 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1818 ABS_MT_SLOT, &initialSlot);
1819 if (status) {
1820 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1821 initialSlot = -1;
1822 }
1823 clearSlots(initialSlot);
1824 } else {
1825 clearSlots(-1);
1826 }
1827}
1828
1829void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1830 if (mSlots) {
1831 for (size_t i = 0; i < mSlotCount; i++) {
1832 mSlots[i].clear();
1833 }
1834 }
1835 mCurrentSlot = initialSlot;
1836}
1837
1838void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1839 if (rawEvent->type == EV_ABS) {
1840 bool newSlot = false;
1841 if (mUsingSlotsProtocol) {
1842 if (rawEvent->code == ABS_MT_SLOT) {
1843 mCurrentSlot = rawEvent->value;
1844 newSlot = true;
1845 }
1846 } else if (mCurrentSlot < 0) {
1847 mCurrentSlot = 0;
1848 }
1849
1850 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1851#if DEBUG_POINTERS
1852 if (newSlot) {
1853 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1854 "should be between 0 and %d; ignoring this slot.",
1855 mCurrentSlot, mSlotCount - 1);
1856 }
1857#endif
1858 } else {
1859 Slot* slot = &mSlots[mCurrentSlot];
1860
1861 switch (rawEvent->code) {
1862 case ABS_MT_POSITION_X:
1863 slot->mInUse = true;
1864 slot->mAbsMTPositionX = rawEvent->value;
1865 break;
1866 case ABS_MT_POSITION_Y:
1867 slot->mInUse = true;
1868 slot->mAbsMTPositionY = rawEvent->value;
1869 break;
1870 case ABS_MT_TOUCH_MAJOR:
1871 slot->mInUse = true;
1872 slot->mAbsMTTouchMajor = rawEvent->value;
1873 break;
1874 case ABS_MT_TOUCH_MINOR:
1875 slot->mInUse = true;
1876 slot->mAbsMTTouchMinor = rawEvent->value;
1877 slot->mHaveAbsMTTouchMinor = true;
1878 break;
1879 case ABS_MT_WIDTH_MAJOR:
1880 slot->mInUse = true;
1881 slot->mAbsMTWidthMajor = rawEvent->value;
1882 break;
1883 case ABS_MT_WIDTH_MINOR:
1884 slot->mInUse = true;
1885 slot->mAbsMTWidthMinor = rawEvent->value;
1886 slot->mHaveAbsMTWidthMinor = true;
1887 break;
1888 case ABS_MT_ORIENTATION:
1889 slot->mInUse = true;
1890 slot->mAbsMTOrientation = rawEvent->value;
1891 break;
1892 case ABS_MT_TRACKING_ID:
1893 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1894 // The slot is no longer in use but it retains its previous contents,
1895 // which may be reused for subsequent touches.
1896 slot->mInUse = false;
1897 } else {
1898 slot->mInUse = true;
1899 slot->mAbsMTTrackingId = rawEvent->value;
1900 }
1901 break;
1902 case ABS_MT_PRESSURE:
1903 slot->mInUse = true;
1904 slot->mAbsMTPressure = rawEvent->value;
1905 break;
1906 case ABS_MT_DISTANCE:
1907 slot->mInUse = true;
1908 slot->mAbsMTDistance = rawEvent->value;
1909 break;
1910 case ABS_MT_TOOL_TYPE:
1911 slot->mInUse = true;
1912 slot->mAbsMTToolType = rawEvent->value;
1913 slot->mHaveAbsMTToolType = true;
1914 break;
1915 }
1916 }
1917 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1918 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1919 mCurrentSlot += 1;
1920 }
1921}
1922
1923void MultiTouchMotionAccumulator::finishSync() {
1924 if (!mUsingSlotsProtocol) {
1925 clearSlots(-1);
1926 }
1927}
1928
1929bool MultiTouchMotionAccumulator::hasStylus() const {
1930 return mHaveStylus;
1931}
1932
1933
1934// --- MultiTouchMotionAccumulator::Slot ---
1935
1936MultiTouchMotionAccumulator::Slot::Slot() {
1937 clear();
1938}
1939
1940void MultiTouchMotionAccumulator::Slot::clear() {
1941 mInUse = false;
1942 mHaveAbsMTTouchMinor = false;
1943 mHaveAbsMTWidthMinor = false;
1944 mHaveAbsMTToolType = false;
1945 mAbsMTPositionX = 0;
1946 mAbsMTPositionY = 0;
1947 mAbsMTTouchMajor = 0;
1948 mAbsMTTouchMinor = 0;
1949 mAbsMTWidthMajor = 0;
1950 mAbsMTWidthMinor = 0;
1951 mAbsMTOrientation = 0;
1952 mAbsMTTrackingId = -1;
1953 mAbsMTPressure = 0;
1954 mAbsMTDistance = 0;
1955 mAbsMTToolType = 0;
1956}
1957
1958int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1959 if (mHaveAbsMTToolType) {
1960 switch (mAbsMTToolType) {
1961 case MT_TOOL_FINGER:
1962 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1963 case MT_TOOL_PEN:
1964 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1965 }
1966 }
1967 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1968}
1969
1970
1971// --- InputMapper ---
1972
1973InputMapper::InputMapper(InputDevice* device) :
1974 mDevice(device), mContext(device->getContext()) {
1975}
1976
1977InputMapper::~InputMapper() {
1978}
1979
1980void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1981 info->addSource(getSources());
1982}
1983
1984void InputMapper::dump(String8& dump) {
1985}
1986
1987void InputMapper::configure(nsecs_t when,
1988 const InputReaderConfiguration* config, uint32_t changes) {
1989}
1990
1991void InputMapper::reset(nsecs_t when) {
1992}
1993
1994void InputMapper::timeoutExpired(nsecs_t when) {
1995}
1996
1997int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1998 return AKEY_STATE_UNKNOWN;
1999}
2000
2001int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2002 return AKEY_STATE_UNKNOWN;
2003}
2004
2005int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2006 return AKEY_STATE_UNKNOWN;
2007}
2008
2009bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2010 const int32_t* keyCodes, uint8_t* outFlags) {
2011 return false;
2012}
2013
2014void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2015 int32_t token) {
2016}
2017
2018void InputMapper::cancelVibrate(int32_t token) {
2019}
2020
Jeff Brownc9aa6282015-02-11 19:03:28 -08002021void InputMapper::cancelTouch(nsecs_t when) {
2022}
2023
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024int32_t InputMapper::getMetaState() {
2025 return 0;
2026}
2027
Andrii Kulian763a3a42016-03-08 10:46:16 -08002028void InputMapper::updateMetaState(int32_t keyCode) {
2029}
2030
Michael Wright842500e2015-03-13 17:32:02 -07002031void InputMapper::updateExternalStylusState(const StylusState& state) {
2032
2033}
2034
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035void InputMapper::fadePointer() {
2036}
2037
2038status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2039 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2040}
2041
2042void InputMapper::bumpGeneration() {
2043 mDevice->bumpGeneration();
2044}
2045
2046void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
2047 const RawAbsoluteAxisInfo& axis, const char* name) {
2048 if (axis.valid) {
2049 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
2050 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2051 } else {
2052 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
2053 }
2054}
2055
Michael Wright842500e2015-03-13 17:32:02 -07002056void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
2057 dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
2058 dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
2059 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
2060 dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
2061}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062
2063// --- SwitchInputMapper ---
2064
2065SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002066 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067}
2068
2069SwitchInputMapper::~SwitchInputMapper() {
2070}
2071
2072uint32_t SwitchInputMapper::getSources() {
2073 return AINPUT_SOURCE_SWITCH;
2074}
2075
2076void SwitchInputMapper::process(const RawEvent* rawEvent) {
2077 switch (rawEvent->type) {
2078 case EV_SW:
2079 processSwitch(rawEvent->code, rawEvent->value);
2080 break;
2081
2082 case EV_SYN:
2083 if (rawEvent->code == SYN_REPORT) {
2084 sync(rawEvent->when);
2085 }
2086 }
2087}
2088
2089void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2090 if (switchCode >= 0 && switchCode < 32) {
2091 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002092 mSwitchValues |= 1 << switchCode;
2093 } else {
2094 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 }
2096 mUpdatedSwitchMask |= 1 << switchCode;
2097 }
2098}
2099
2100void SwitchInputMapper::sync(nsecs_t when) {
2101 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002102 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002103 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 getListener()->notifySwitch(&args);
2105
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 mUpdatedSwitchMask = 0;
2107 }
2108}
2109
2110int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2111 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2112}
2113
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002114void SwitchInputMapper::dump(String8& dump) {
2115 dump.append(INDENT2 "Switch Input Mapper:\n");
2116 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
2117}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118
2119// --- VibratorInputMapper ---
2120
2121VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2122 InputMapper(device), mVibrating(false) {
2123}
2124
2125VibratorInputMapper::~VibratorInputMapper() {
2126}
2127
2128uint32_t VibratorInputMapper::getSources() {
2129 return 0;
2130}
2131
2132void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2133 InputMapper::populateDeviceInfo(info);
2134
2135 info->setVibrator(true);
2136}
2137
2138void VibratorInputMapper::process(const RawEvent* rawEvent) {
2139 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2140}
2141
2142void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2143 int32_t token) {
2144#if DEBUG_VIBRATOR
2145 String8 patternStr;
2146 for (size_t i = 0; i < patternSize; i++) {
2147 if (i != 0) {
2148 patternStr.append(", ");
2149 }
2150 patternStr.appendFormat("%lld", pattern[i]);
2151 }
2152 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
2153 getDeviceId(), patternStr.string(), repeat, token);
2154#endif
2155
2156 mVibrating = true;
2157 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2158 mPatternSize = patternSize;
2159 mRepeat = repeat;
2160 mToken = token;
2161 mIndex = -1;
2162
2163 nextStep();
2164}
2165
2166void VibratorInputMapper::cancelVibrate(int32_t token) {
2167#if DEBUG_VIBRATOR
2168 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2169#endif
2170
2171 if (mVibrating && mToken == token) {
2172 stopVibrating();
2173 }
2174}
2175
2176void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2177 if (mVibrating) {
2178 if (when >= mNextStepTime) {
2179 nextStep();
2180 } else {
2181 getContext()->requestTimeoutAtTime(mNextStepTime);
2182 }
2183 }
2184}
2185
2186void VibratorInputMapper::nextStep() {
2187 mIndex += 1;
2188 if (size_t(mIndex) >= mPatternSize) {
2189 if (mRepeat < 0) {
2190 // We are done.
2191 stopVibrating();
2192 return;
2193 }
2194 mIndex = mRepeat;
2195 }
2196
2197 bool vibratorOn = mIndex & 1;
2198 nsecs_t duration = mPattern[mIndex];
2199 if (vibratorOn) {
2200#if DEBUG_VIBRATOR
2201 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
2202 getDeviceId(), duration);
2203#endif
2204 getEventHub()->vibrate(getDeviceId(), duration);
2205 } else {
2206#if DEBUG_VIBRATOR
2207 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2208#endif
2209 getEventHub()->cancelVibrate(getDeviceId());
2210 }
2211 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2212 mNextStepTime = now + duration;
2213 getContext()->requestTimeoutAtTime(mNextStepTime);
2214#if DEBUG_VIBRATOR
2215 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2216#endif
2217}
2218
2219void VibratorInputMapper::stopVibrating() {
2220 mVibrating = false;
2221#if DEBUG_VIBRATOR
2222 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2223#endif
2224 getEventHub()->cancelVibrate(getDeviceId());
2225}
2226
2227void VibratorInputMapper::dump(String8& dump) {
2228 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2229 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2230}
2231
2232
2233// --- KeyboardInputMapper ---
2234
2235KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2236 uint32_t source, int32_t keyboardType) :
2237 InputMapper(device), mSource(source),
2238 mKeyboardType(keyboardType) {
2239}
2240
2241KeyboardInputMapper::~KeyboardInputMapper() {
2242}
2243
2244uint32_t KeyboardInputMapper::getSources() {
2245 return mSource;
2246}
2247
2248void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2249 InputMapper::populateDeviceInfo(info);
2250
2251 info->setKeyboardType(mKeyboardType);
2252 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2253}
2254
2255void KeyboardInputMapper::dump(String8& dump) {
2256 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2257 dumpParameters(dump);
2258 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2259 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002260 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002262 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263}
2264
2265
2266void KeyboardInputMapper::configure(nsecs_t when,
2267 const InputReaderConfiguration* config, uint32_t changes) {
2268 InputMapper::configure(when, config, changes);
2269
2270 if (!changes) { // first time only
2271 // Configure basic parameters.
2272 configureParameters();
2273 }
2274
2275 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2276 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2277 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002278 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 mOrientation = v.orientation;
2280 } else {
2281 mOrientation = DISPLAY_ORIENTATION_0;
2282 }
2283 } else {
2284 mOrientation = DISPLAY_ORIENTATION_0;
2285 }
2286 }
2287}
2288
Ivan Podogovb9afef32017-02-13 15:34:32 +00002289static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2290 int32_t mapped = 0;
2291 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2292 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2293 if (stemKeyRotationMap[i][0] == keyCode) {
2294 stemKeyRotationMap[i][1] = mapped;
2295 return;
2296 }
2297 }
2298 }
2299}
2300
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301void KeyboardInputMapper::configureParameters() {
2302 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002303 const PropertyMap& config = getDevice()->getConfiguration();
2304 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 mParameters.orientationAware);
2306
2307 mParameters.hasAssociatedDisplay = false;
2308 if (mParameters.orientationAware) {
2309 mParameters.hasAssociatedDisplay = true;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002310
2311 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2312 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2313 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2314 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002316
2317 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002318 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002319 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320}
2321
2322void KeyboardInputMapper::dumpParameters(String8& dump) {
2323 dump.append(INDENT3 "Parameters:\n");
2324 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2325 toString(mParameters.hasAssociatedDisplay));
2326 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2327 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002328 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2329 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330}
2331
2332void KeyboardInputMapper::reset(nsecs_t when) {
2333 mMetaState = AMETA_NONE;
2334 mDownTime = 0;
2335 mKeyDowns.clear();
2336 mCurrentHidUsage = 0;
2337
2338 resetLedState();
2339
2340 InputMapper::reset(when);
2341}
2342
2343void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2344 switch (rawEvent->type) {
2345 case EV_KEY: {
2346 int32_t scanCode = rawEvent->code;
2347 int32_t usageCode = mCurrentHidUsage;
2348 mCurrentHidUsage = 0;
2349
2350 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002351 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353 break;
2354 }
2355 case EV_MSC: {
2356 if (rawEvent->code == MSC_SCAN) {
2357 mCurrentHidUsage = rawEvent->value;
2358 }
2359 break;
2360 }
2361 case EV_SYN: {
2362 if (rawEvent->code == SYN_REPORT) {
2363 mCurrentHidUsage = 0;
2364 }
2365 }
2366 }
2367}
2368
2369bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2370 return scanCode < BTN_MOUSE
2371 || scanCode >= KEY_OK
2372 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2373 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2374}
2375
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002376void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2377 int32_t usageCode) {
2378 int32_t keyCode;
2379 int32_t keyMetaState;
2380 uint32_t policyFlags;
2381
2382 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2383 &keyCode, &keyMetaState, &policyFlags)) {
2384 keyCode = AKEYCODE_UNKNOWN;
2385 keyMetaState = mMetaState;
2386 policyFlags = 0;
2387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388
2389 if (down) {
2390 // Rotate key codes according to orientation if needed.
2391 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2392 keyCode = rotateKeyCode(keyCode, mOrientation);
2393 }
2394
2395 // Add key down.
2396 ssize_t keyDownIndex = findKeyDown(scanCode);
2397 if (keyDownIndex >= 0) {
2398 // key repeat, be sure to use same keycode as before in case of rotation
2399 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2400 } else {
2401 // key down
2402 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2403 && mContext->shouldDropVirtualKey(when,
2404 getDevice(), keyCode, scanCode)) {
2405 return;
2406 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002407 if (policyFlags & POLICY_FLAG_GESTURE) {
2408 mDevice->cancelTouch(when);
2409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410
2411 mKeyDowns.push();
2412 KeyDown& keyDown = mKeyDowns.editTop();
2413 keyDown.keyCode = keyCode;
2414 keyDown.scanCode = scanCode;
2415 }
2416
2417 mDownTime = when;
2418 } else {
2419 // Remove key down.
2420 ssize_t keyDownIndex = findKeyDown(scanCode);
2421 if (keyDownIndex >= 0) {
2422 // key up, be sure to use same keycode as before in case of rotation
2423 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2424 mKeyDowns.removeAt(size_t(keyDownIndex));
2425 } else {
2426 // key was not actually down
2427 ALOGI("Dropping key up from device %s because the key was not down. "
2428 "keyCode=%d, scanCode=%d",
2429 getDeviceName().string(), keyCode, scanCode);
2430 return;
2431 }
2432 }
2433
Andrii Kulian763a3a42016-03-08 10:46:16 -08002434 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002435 // If global meta state changed send it along with the key.
2436 // If it has not changed then we'll use what keymap gave us,
2437 // since key replacement logic might temporarily reset a few
2438 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002439 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441
2442 nsecs_t downTime = mDownTime;
2443
2444 // Key down on external an keyboard should wake the device.
2445 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2446 // For internal keyboards, the key layout file should specify the policy flags for
2447 // each wake key individually.
2448 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright872db4f2014-04-22 15:03:51 -07002449 if (down && getDevice()->isExternal()) {
2450 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
2452
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002453 if (mParameters.handlesKeyRepeat) {
2454 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2455 }
2456
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2458 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002459 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 getListener()->notifyKey(&args);
2461}
2462
2463ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2464 size_t n = mKeyDowns.size();
2465 for (size_t i = 0; i < n; i++) {
2466 if (mKeyDowns[i].scanCode == scanCode) {
2467 return i;
2468 }
2469 }
2470 return -1;
2471}
2472
2473int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2474 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2475}
2476
2477int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2478 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2479}
2480
2481bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2482 const int32_t* keyCodes, uint8_t* outFlags) {
2483 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2484}
2485
2486int32_t KeyboardInputMapper::getMetaState() {
2487 return mMetaState;
2488}
2489
Andrii Kulian763a3a42016-03-08 10:46:16 -08002490void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2491 updateMetaStateIfNeeded(keyCode, false);
2492}
2493
2494bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2495 int32_t oldMetaState = mMetaState;
2496 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2497 bool metaStateChanged = oldMetaState != newMetaState;
2498 if (metaStateChanged) {
2499 mMetaState = newMetaState;
2500 updateLedState(false);
2501
2502 getContext()->updateGlobalMetaState();
2503 }
2504
2505 return metaStateChanged;
2506}
2507
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508void KeyboardInputMapper::resetLedState() {
2509 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2510 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2511 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2512
2513 updateLedState(true);
2514}
2515
2516void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2517 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2518 ledState.on = false;
2519}
2520
2521void KeyboardInputMapper::updateLedState(bool reset) {
2522 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2523 AMETA_CAPS_LOCK_ON, reset);
2524 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2525 AMETA_NUM_LOCK_ON, reset);
2526 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2527 AMETA_SCROLL_LOCK_ON, reset);
2528}
2529
2530void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2531 int32_t led, int32_t modifier, bool reset) {
2532 if (ledState.avail) {
2533 bool desiredState = (mMetaState & modifier) != 0;
2534 if (reset || ledState.on != desiredState) {
2535 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2536 ledState.on = desiredState;
2537 }
2538 }
2539}
2540
2541
2542// --- CursorInputMapper ---
2543
2544CursorInputMapper::CursorInputMapper(InputDevice* device) :
2545 InputMapper(device) {
2546}
2547
2548CursorInputMapper::~CursorInputMapper() {
2549}
2550
2551uint32_t CursorInputMapper::getSources() {
2552 return mSource;
2553}
2554
2555void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2556 InputMapper::populateDeviceInfo(info);
2557
2558 if (mParameters.mode == Parameters::MODE_POINTER) {
2559 float minX, minY, maxX, maxY;
2560 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2561 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2562 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2563 }
2564 } else {
2565 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2566 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2567 }
2568 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2569
2570 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2571 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2572 }
2573 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2574 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2575 }
2576}
2577
2578void CursorInputMapper::dump(String8& dump) {
2579 dump.append(INDENT2 "Cursor Input Mapper:\n");
2580 dumpParameters(dump);
2581 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2582 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2583 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2584 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2585 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2586 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2587 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2588 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2589 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2590 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2591 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2592 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2593 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002594 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595}
2596
2597void CursorInputMapper::configure(nsecs_t when,
2598 const InputReaderConfiguration* config, uint32_t changes) {
2599 InputMapper::configure(when, config, changes);
2600
2601 if (!changes) { // first time only
2602 mCursorScrollAccumulator.configure(getDevice());
2603
2604 // Configure basic parameters.
2605 configureParameters();
2606
2607 // Configure device mode.
2608 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002609 case Parameters::MODE_POINTER_RELATIVE:
2610 // Should not happen during first time configuration.
2611 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2612 mParameters.mode = Parameters::MODE_POINTER;
2613 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 case Parameters::MODE_POINTER:
2615 mSource = AINPUT_SOURCE_MOUSE;
2616 mXPrecision = 1.0f;
2617 mYPrecision = 1.0f;
2618 mXScale = 1.0f;
2619 mYScale = 1.0f;
2620 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2621 break;
2622 case Parameters::MODE_NAVIGATION:
2623 mSource = AINPUT_SOURCE_TRACKBALL;
2624 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2625 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2626 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2627 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2628 break;
2629 }
2630
2631 mVWheelScale = 1.0f;
2632 mHWheelScale = 1.0f;
2633 }
2634
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002635 if ((!changes && config->pointerCapture)
2636 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2637 if (config->pointerCapture) {
2638 if (mParameters.mode == Parameters::MODE_POINTER) {
2639 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2640 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2641 // Keep PointerController around in order to preserve the pointer position.
2642 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2643 } else {
2644 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2645 }
2646 } else {
2647 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2648 mParameters.mode = Parameters::MODE_POINTER;
2649 mSource = AINPUT_SOURCE_MOUSE;
2650 } else {
2651 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2652 }
2653 }
2654 bumpGeneration();
2655 if (changes) {
2656 getDevice()->notifyReset(when);
2657 }
2658 }
2659
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2661 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2662 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2663 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2664 }
2665
2666 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2667 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2668 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002669 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 mOrientation = v.orientation;
2671 } else {
2672 mOrientation = DISPLAY_ORIENTATION_0;
2673 }
2674 } else {
2675 mOrientation = DISPLAY_ORIENTATION_0;
2676 }
2677 bumpGeneration();
2678 }
2679}
2680
2681void CursorInputMapper::configureParameters() {
2682 mParameters.mode = Parameters::MODE_POINTER;
2683 String8 cursorModeString;
2684 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2685 if (cursorModeString == "navigation") {
2686 mParameters.mode = Parameters::MODE_NAVIGATION;
2687 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2688 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2689 }
2690 }
2691
2692 mParameters.orientationAware = false;
2693 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2694 mParameters.orientationAware);
2695
2696 mParameters.hasAssociatedDisplay = false;
2697 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2698 mParameters.hasAssociatedDisplay = true;
2699 }
2700}
2701
2702void CursorInputMapper::dumpParameters(String8& dump) {
2703 dump.append(INDENT3 "Parameters:\n");
2704 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2705 toString(mParameters.hasAssociatedDisplay));
2706
2707 switch (mParameters.mode) {
2708 case Parameters::MODE_POINTER:
2709 dump.append(INDENT4 "Mode: pointer\n");
2710 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002711 case Parameters::MODE_POINTER_RELATIVE:
2712 dump.append(INDENT4 "Mode: relative pointer\n");
2713 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 case Parameters::MODE_NAVIGATION:
2715 dump.append(INDENT4 "Mode: navigation\n");
2716 break;
2717 default:
2718 ALOG_ASSERT(false);
2719 }
2720
2721 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2722 toString(mParameters.orientationAware));
2723}
2724
2725void CursorInputMapper::reset(nsecs_t when) {
2726 mButtonState = 0;
2727 mDownTime = 0;
2728
2729 mPointerVelocityControl.reset();
2730 mWheelXVelocityControl.reset();
2731 mWheelYVelocityControl.reset();
2732
2733 mCursorButtonAccumulator.reset(getDevice());
2734 mCursorMotionAccumulator.reset(getDevice());
2735 mCursorScrollAccumulator.reset(getDevice());
2736
2737 InputMapper::reset(when);
2738}
2739
2740void CursorInputMapper::process(const RawEvent* rawEvent) {
2741 mCursorButtonAccumulator.process(rawEvent);
2742 mCursorMotionAccumulator.process(rawEvent);
2743 mCursorScrollAccumulator.process(rawEvent);
2744
2745 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2746 sync(rawEvent->when);
2747 }
2748}
2749
2750void CursorInputMapper::sync(nsecs_t when) {
2751 int32_t lastButtonState = mButtonState;
2752 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2753 mButtonState = currentButtonState;
2754
2755 bool wasDown = isPointerDown(lastButtonState);
2756 bool down = isPointerDown(currentButtonState);
2757 bool downChanged;
2758 if (!wasDown && down) {
2759 mDownTime = when;
2760 downChanged = true;
2761 } else if (wasDown && !down) {
2762 downChanged = true;
2763 } else {
2764 downChanged = false;
2765 }
2766 nsecs_t downTime = mDownTime;
2767 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002768 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2769 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
2771 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2772 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2773 bool moved = deltaX != 0 || deltaY != 0;
2774
2775 // Rotate delta according to orientation if needed.
2776 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2777 && (deltaX != 0.0f || deltaY != 0.0f)) {
2778 rotateDelta(mOrientation, &deltaX, &deltaY);
2779 }
2780
2781 // Move the pointer.
2782 PointerProperties pointerProperties;
2783 pointerProperties.clear();
2784 pointerProperties.id = 0;
2785 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2786
2787 PointerCoords pointerCoords;
2788 pointerCoords.clear();
2789
2790 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2791 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2792 bool scrolled = vscroll != 0 || hscroll != 0;
2793
2794 mWheelYVelocityControl.move(when, NULL, &vscroll);
2795 mWheelXVelocityControl.move(when, &hscroll, NULL);
2796
2797 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2798
2799 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002800 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 if (moved || scrolled || buttonsChanged) {
2802 mPointerController->setPresentation(
2803 PointerControllerInterface::PRESENTATION_POINTER);
2804
2805 if (moved) {
2806 mPointerController->move(deltaX, deltaY);
2807 }
2808
2809 if (buttonsChanged) {
2810 mPointerController->setButtonState(currentButtonState);
2811 }
2812
2813 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2814 }
2815
2816 float x, y;
2817 mPointerController->getPosition(&x, &y);
2818 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2819 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002820 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2821 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 displayId = ADISPLAY_ID_DEFAULT;
2823 } else {
2824 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2825 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2826 displayId = ADISPLAY_ID_NONE;
2827 }
2828
2829 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2830
2831 // Moving an external trackball or mouse should wake the device.
2832 // We don't do this for internal cursor devices to prevent them from waking up
2833 // the device in your pocket.
2834 // TODO: Use the input device configuration to control this behavior more finely.
2835 uint32_t policyFlags = 0;
2836 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002837 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 }
2839
2840 // Synthesize key down from buttons if needed.
2841 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2842 policyFlags, lastButtonState, currentButtonState);
2843
2844 // Send motion event.
2845 if (downChanged || moved || scrolled || buttonsChanged) {
2846 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002847 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 int32_t motionEventAction;
2849 if (downChanged) {
2850 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002851 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2853 } else {
2854 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2855 }
2856
Michael Wright7b159c92015-05-14 14:48:03 +01002857 if (buttonsReleased) {
2858 BitSet32 released(buttonsReleased);
2859 while (!released.isEmpty()) {
2860 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2861 buttonState &= ~actionButton;
2862 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2863 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2864 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2865 displayId, 1, &pointerProperties, &pointerCoords,
2866 mXPrecision, mYPrecision, downTime);
2867 getListener()->notifyMotion(&releaseArgs);
2868 }
2869 }
2870
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002872 motionEventAction, 0, 0, metaState, currentButtonState,
2873 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 displayId, 1, &pointerProperties, &pointerCoords,
2875 mXPrecision, mYPrecision, downTime);
2876 getListener()->notifyMotion(&args);
2877
Michael Wright7b159c92015-05-14 14:48:03 +01002878 if (buttonsPressed) {
2879 BitSet32 pressed(buttonsPressed);
2880 while (!pressed.isEmpty()) {
2881 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2882 buttonState |= actionButton;
2883 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2884 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2885 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2886 displayId, 1, &pointerProperties, &pointerCoords,
2887 mXPrecision, mYPrecision, downTime);
2888 getListener()->notifyMotion(&pressArgs);
2889 }
2890 }
2891
2892 ALOG_ASSERT(buttonState == currentButtonState);
2893
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 // Send hover move after UP to tell the application that the mouse is hovering now.
2895 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002896 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002898 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2900 displayId, 1, &pointerProperties, &pointerCoords,
2901 mXPrecision, mYPrecision, downTime);
2902 getListener()->notifyMotion(&hoverArgs);
2903 }
2904
2905 // Send scroll events.
2906 if (scrolled) {
2907 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2908 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2909
2910 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002911 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 AMOTION_EVENT_EDGE_FLAG_NONE,
2913 displayId, 1, &pointerProperties, &pointerCoords,
2914 mXPrecision, mYPrecision, downTime);
2915 getListener()->notifyMotion(&scrollArgs);
2916 }
2917 }
2918
2919 // Synthesize key up from buttons if needed.
2920 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2921 policyFlags, lastButtonState, currentButtonState);
2922
2923 mCursorMotionAccumulator.finishSync();
2924 mCursorScrollAccumulator.finishSync();
2925}
2926
2927int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2928 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2929 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2930 } else {
2931 return AKEY_STATE_UNKNOWN;
2932 }
2933}
2934
2935void CursorInputMapper::fadePointer() {
2936 if (mPointerController != NULL) {
2937 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2938 }
2939}
2940
Prashant Malani1941ff52015-08-11 18:29:28 -07002941// --- RotaryEncoderInputMapper ---
2942
2943RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002944 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002945 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2946}
2947
2948RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2949}
2950
2951uint32_t RotaryEncoderInputMapper::getSources() {
2952 return mSource;
2953}
2954
2955void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2956 InputMapper::populateDeviceInfo(info);
2957
2958 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002959 float res = 0.0f;
2960 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2961 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2962 }
2963 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2964 mScalingFactor)) {
2965 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2966 "default to 1.0!\n");
2967 mScalingFactor = 1.0f;
2968 }
2969 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2970 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002971 }
2972}
2973
2974void RotaryEncoderInputMapper::dump(String8& dump) {
2975 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2976 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2977 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2978}
2979
2980void RotaryEncoderInputMapper::configure(nsecs_t when,
2981 const InputReaderConfiguration* config, uint32_t changes) {
2982 InputMapper::configure(when, config, changes);
2983 if (!changes) {
2984 mRotaryEncoderScrollAccumulator.configure(getDevice());
2985 }
Ivan Podogovad437252016-09-29 16:29:55 +01002986 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2987 DisplayViewport v;
2988 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
2989 mOrientation = v.orientation;
2990 } else {
2991 mOrientation = DISPLAY_ORIENTATION_0;
2992 }
2993 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002994}
2995
2996void RotaryEncoderInputMapper::reset(nsecs_t when) {
2997 mRotaryEncoderScrollAccumulator.reset(getDevice());
2998
2999 InputMapper::reset(when);
3000}
3001
3002void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3003 mRotaryEncoderScrollAccumulator.process(rawEvent);
3004
3005 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3006 sync(rawEvent->when);
3007 }
3008}
3009
3010void RotaryEncoderInputMapper::sync(nsecs_t when) {
3011 PointerCoords pointerCoords;
3012 pointerCoords.clear();
3013
3014 PointerProperties pointerProperties;
3015 pointerProperties.clear();
3016 pointerProperties.id = 0;
3017 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3018
3019 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3020 bool scrolled = scroll != 0;
3021
3022 // This is not a pointer, so it's not associated with a display.
3023 int32_t displayId = ADISPLAY_ID_NONE;
3024
3025 // Moving the rotary encoder should wake the device (if specified).
3026 uint32_t policyFlags = 0;
3027 if (scrolled && getDevice()->isExternal()) {
3028 policyFlags |= POLICY_FLAG_WAKE;
3029 }
3030
Ivan Podogovad437252016-09-29 16:29:55 +01003031 if (mOrientation == DISPLAY_ORIENTATION_180) {
3032 scroll = -scroll;
3033 }
3034
Prashant Malani1941ff52015-08-11 18:29:28 -07003035 // Send motion event.
3036 if (scrolled) {
3037 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003038 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003039
3040 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3041 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3042 AMOTION_EVENT_EDGE_FLAG_NONE,
3043 displayId, 1, &pointerProperties, &pointerCoords,
3044 0, 0, 0);
3045 getListener()->notifyMotion(&scrollArgs);
3046 }
3047
3048 mRotaryEncoderScrollAccumulator.finishSync();
3049}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050
3051// --- TouchInputMapper ---
3052
3053TouchInputMapper::TouchInputMapper(InputDevice* device) :
3054 InputMapper(device),
3055 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3056 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3057 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3058}
3059
3060TouchInputMapper::~TouchInputMapper() {
3061}
3062
3063uint32_t TouchInputMapper::getSources() {
3064 return mSource;
3065}
3066
3067void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3068 InputMapper::populateDeviceInfo(info);
3069
3070 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3071 info->addMotionRange(mOrientedRanges.x);
3072 info->addMotionRange(mOrientedRanges.y);
3073 info->addMotionRange(mOrientedRanges.pressure);
3074
3075 if (mOrientedRanges.haveSize) {
3076 info->addMotionRange(mOrientedRanges.size);
3077 }
3078
3079 if (mOrientedRanges.haveTouchSize) {
3080 info->addMotionRange(mOrientedRanges.touchMajor);
3081 info->addMotionRange(mOrientedRanges.touchMinor);
3082 }
3083
3084 if (mOrientedRanges.haveToolSize) {
3085 info->addMotionRange(mOrientedRanges.toolMajor);
3086 info->addMotionRange(mOrientedRanges.toolMinor);
3087 }
3088
3089 if (mOrientedRanges.haveOrientation) {
3090 info->addMotionRange(mOrientedRanges.orientation);
3091 }
3092
3093 if (mOrientedRanges.haveDistance) {
3094 info->addMotionRange(mOrientedRanges.distance);
3095 }
3096
3097 if (mOrientedRanges.haveTilt) {
3098 info->addMotionRange(mOrientedRanges.tilt);
3099 }
3100
3101 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3102 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3103 0.0f);
3104 }
3105 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3106 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3107 0.0f);
3108 }
3109 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3110 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3111 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3112 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3113 x.fuzz, x.resolution);
3114 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3115 y.fuzz, y.resolution);
3116 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3117 x.fuzz, x.resolution);
3118 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3119 y.fuzz, y.resolution);
3120 }
3121 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3122 }
3123}
3124
3125void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003126 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 dumpParameters(dump);
3128 dumpVirtualKeys(dump);
3129 dumpRawPointerAxes(dump);
3130 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003131 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 dumpSurface(dump);
3133
3134 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3135 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3136 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3137 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3138 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3139 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3140 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3141 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3142 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3143 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3144 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3145 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3146 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3147 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3148 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3149 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3150 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3151
Michael Wright7b159c92015-05-14 14:48:03 +01003152 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003154 mLastRawState.rawPointerData.pointerCount);
3155 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3156 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3158 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3159 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3160 "toolType=%d, isHovering=%s\n", i,
3161 pointer.id, pointer.x, pointer.y, pointer.pressure,
3162 pointer.touchMajor, pointer.touchMinor,
3163 pointer.toolMajor, pointer.toolMinor,
3164 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3165 pointer.toolType, toString(pointer.isHovering));
3166 }
3167
Michael Wright7b159c92015-05-14 14:48:03 +01003168 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003170 mLastCookedState.cookedPointerData.pointerCount);
3171 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3172 const PointerProperties& pointerProperties =
3173 mLastCookedState.cookedPointerData.pointerProperties[i];
3174 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3176 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3177 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3178 "toolType=%d, isHovering=%s\n", i,
3179 pointerProperties.id,
3180 pointerCoords.getX(),
3181 pointerCoords.getY(),
3182 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3183 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3184 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3185 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3186 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3187 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3188 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3189 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3190 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003191 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 }
3193
Michael Wright842500e2015-03-13 17:32:02 -07003194 dump.append(INDENT3 "Stylus Fusion:\n");
3195 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3196 toString(mExternalStylusConnected));
3197 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3198 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003199 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003200 dump.append(INDENT3 "External Stylus State:\n");
3201 dumpStylusState(dump, mExternalStylusState);
3202
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 if (mDeviceMode == DEVICE_MODE_POINTER) {
3204 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3205 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3206 mPointerXMovementScale);
3207 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3208 mPointerYMovementScale);
3209 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3210 mPointerXZoomScale);
3211 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3212 mPointerYZoomScale);
3213 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3214 mPointerGestureMaxSwipeWidth);
3215 }
3216}
3217
Santos Cordonfa5cf462017-04-05 10:37:00 -07003218const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3219 switch (deviceMode) {
3220 case DEVICE_MODE_DISABLED:
3221 return "disabled";
3222 case DEVICE_MODE_DIRECT:
3223 return "direct";
3224 case DEVICE_MODE_UNSCALED:
3225 return "unscaled";
3226 case DEVICE_MODE_NAVIGATION:
3227 return "navigation";
3228 case DEVICE_MODE_POINTER:
3229 return "pointer";
3230 }
3231 return "unknown";
3232}
3233
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234void TouchInputMapper::configure(nsecs_t when,
3235 const InputReaderConfiguration* config, uint32_t changes) {
3236 InputMapper::configure(when, config, changes);
3237
3238 mConfig = *config;
3239
3240 if (!changes) { // first time only
3241 // Configure basic parameters.
3242 configureParameters();
3243
3244 // Configure common accumulators.
3245 mCursorScrollAccumulator.configure(getDevice());
3246 mTouchButtonAccumulator.configure(getDevice());
3247
3248 // Configure absolute axis information.
3249 configureRawPointerAxes();
3250
3251 // Prepare input device calibration.
3252 parseCalibration();
3253 resolveCalibration();
3254 }
3255
Michael Wright842500e2015-03-13 17:32:02 -07003256 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003257 // Update location calibration to reflect current settings
3258 updateAffineTransformation();
3259 }
3260
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3262 // Update pointer speed.
3263 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3264 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3265 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3266 }
3267
3268 bool resetNeeded = false;
3269 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3270 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003271 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3272 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 // Configure device sources, surface dimensions, orientation and
3274 // scaling factors.
3275 configureSurface(when, &resetNeeded);
3276 }
3277
3278 if (changes && resetNeeded) {
3279 // Send reset, unless this is the first time the device has been configured,
3280 // in which case the reader will call reset itself after all mappers are ready.
3281 getDevice()->notifyReset(when);
3282 }
3283}
3284
Michael Wright842500e2015-03-13 17:32:02 -07003285void TouchInputMapper::resolveExternalStylusPresence() {
3286 Vector<InputDeviceInfo> devices;
3287 mContext->getExternalStylusDevices(devices);
3288 mExternalStylusConnected = !devices.isEmpty();
3289
3290 if (!mExternalStylusConnected) {
3291 resetExternalStylus();
3292 }
3293}
3294
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295void TouchInputMapper::configureParameters() {
3296 // Use the pointer presentation mode for devices that do not support distinct
3297 // multitouch. The spot-based presentation relies on being able to accurately
3298 // locate two or more fingers on the touch pad.
3299 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003300 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 String8 gestureModeString;
3303 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3304 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003305 if (gestureModeString == "single-touch") {
3306 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3307 } else if (gestureModeString == "multi-touch") {
3308 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 } else if (gestureModeString != "default") {
3310 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3311 }
3312 }
3313
3314 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3315 // The device is a touch screen.
3316 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3317 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3318 // The device is a pointing device like a track pad.
3319 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3320 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3321 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3322 // The device is a cursor device with a touch pad attached.
3323 // By default don't use the touch pad to move the pointer.
3324 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3325 } else {
3326 // The device is a touch pad of unknown purpose.
3327 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3328 }
3329
3330 mParameters.hasButtonUnderPad=
3331 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3332
3333 String8 deviceTypeString;
3334 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3335 deviceTypeString)) {
3336 if (deviceTypeString == "touchScreen") {
3337 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3338 } else if (deviceTypeString == "touchPad") {
3339 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3340 } else if (deviceTypeString == "touchNavigation") {
3341 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3342 } else if (deviceTypeString == "pointer") {
3343 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3344 } else if (deviceTypeString != "default") {
3345 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3346 }
3347 }
3348
3349 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3350 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3351 mParameters.orientationAware);
3352
3353 mParameters.hasAssociatedDisplay = false;
3354 mParameters.associatedDisplayIsExternal = false;
3355 if (mParameters.orientationAware
3356 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3357 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3358 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003359 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3360 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3361 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3362 mParameters.uniqueDisplayId);
3363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003365
3366 // Initial downs on external touch devices should wake the device.
3367 // Normally we don't do this for internal touch screens to prevent them from waking
3368 // up in your pocket but you can enable it using the input device configuration.
3369 mParameters.wake = getDevice()->isExternal();
3370 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3371 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372}
3373
3374void TouchInputMapper::dumpParameters(String8& dump) {
3375 dump.append(INDENT3 "Parameters:\n");
3376
3377 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003378 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3379 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003381 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3382 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 break;
3384 default:
3385 assert(false);
3386 }
3387
3388 switch (mParameters.deviceType) {
3389 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3390 dump.append(INDENT4 "DeviceType: touchScreen\n");
3391 break;
3392 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3393 dump.append(INDENT4 "DeviceType: touchPad\n");
3394 break;
3395 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3396 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3397 break;
3398 case Parameters::DEVICE_TYPE_POINTER:
3399 dump.append(INDENT4 "DeviceType: pointer\n");
3400 break;
3401 default:
3402 ALOG_ASSERT(false);
3403 }
3404
Santos Cordonfa5cf462017-04-05 10:37:00 -07003405 dump.appendFormat(
3406 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003408 toString(mParameters.associatedDisplayIsExternal),
3409 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3411 toString(mParameters.orientationAware));
3412}
3413
3414void TouchInputMapper::configureRawPointerAxes() {
3415 mRawPointerAxes.clear();
3416}
3417
3418void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3419 dump.append(INDENT3 "Raw Touch Axes:\n");
3420 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3421 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3422 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3423 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3424 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3425 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3426 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3427 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3428 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3429 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3430 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3431 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3432 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3433}
3434
Michael Wright842500e2015-03-13 17:32:02 -07003435bool TouchInputMapper::hasExternalStylus() const {
3436 return mExternalStylusConnected;
3437}
3438
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3440 int32_t oldDeviceMode = mDeviceMode;
3441
Michael Wright842500e2015-03-13 17:32:02 -07003442 resolveExternalStylusPresence();
3443
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 // Determine device mode.
3445 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3446 && mConfig.pointerGesturesEnabled) {
3447 mSource = AINPUT_SOURCE_MOUSE;
3448 mDeviceMode = DEVICE_MODE_POINTER;
3449 if (hasStylus()) {
3450 mSource |= AINPUT_SOURCE_STYLUS;
3451 }
3452 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3453 && mParameters.hasAssociatedDisplay) {
3454 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3455 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003456 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 mSource |= AINPUT_SOURCE_STYLUS;
3458 }
Michael Wright2f78b682015-06-12 15:25:08 +01003459 if (hasExternalStylus()) {
3460 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3463 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3464 mDeviceMode = DEVICE_MODE_NAVIGATION;
3465 } else {
3466 mSource = AINPUT_SOURCE_TOUCHPAD;
3467 mDeviceMode = DEVICE_MODE_UNSCALED;
3468 }
3469
3470 // Ensure we have valid X and Y axes.
3471 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3472 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3473 "The device will be inoperable.", getDeviceName().string());
3474 mDeviceMode = DEVICE_MODE_DISABLED;
3475 return;
3476 }
3477
3478 // Raw width and height in the natural orientation.
3479 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3480 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3481
3482 // Get associated display dimensions.
3483 DisplayViewport newViewport;
3484 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003485 const String8* uniqueDisplayId = NULL;
3486 ViewportType viewportTypeToUse;
3487
3488 if (mParameters.associatedDisplayIsExternal) {
3489 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3490 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3491 // If the IDC file specified a unique display Id, then it expects to be linked to a
3492 // virtual display with the same unique ID.
3493 uniqueDisplayId = &mParameters.uniqueDisplayId;
3494 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3495 } else {
3496 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3497 }
3498
3499 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3501 "display. The device will be inoperable until the display size "
3502 "becomes available.",
3503 getDeviceName().string());
3504 mDeviceMode = DEVICE_MODE_DISABLED;
3505 return;
3506 }
3507 } else {
3508 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3509 }
3510 bool viewportChanged = mViewport != newViewport;
3511 if (viewportChanged) {
3512 mViewport = newViewport;
3513
3514 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3515 // Convert rotated viewport to natural surface coordinates.
3516 int32_t naturalLogicalWidth, naturalLogicalHeight;
3517 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3518 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3519 int32_t naturalDeviceWidth, naturalDeviceHeight;
3520 switch (mViewport.orientation) {
3521 case DISPLAY_ORIENTATION_90:
3522 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3523 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3524 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3525 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3526 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3527 naturalPhysicalTop = mViewport.physicalLeft;
3528 naturalDeviceWidth = mViewport.deviceHeight;
3529 naturalDeviceHeight = mViewport.deviceWidth;
3530 break;
3531 case DISPLAY_ORIENTATION_180:
3532 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3533 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3534 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3535 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3536 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3537 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3538 naturalDeviceWidth = mViewport.deviceWidth;
3539 naturalDeviceHeight = mViewport.deviceHeight;
3540 break;
3541 case DISPLAY_ORIENTATION_270:
3542 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3543 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3544 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3545 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3546 naturalPhysicalLeft = mViewport.physicalTop;
3547 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3548 naturalDeviceWidth = mViewport.deviceHeight;
3549 naturalDeviceHeight = mViewport.deviceWidth;
3550 break;
3551 case DISPLAY_ORIENTATION_0:
3552 default:
3553 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3554 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3555 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3556 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3557 naturalPhysicalLeft = mViewport.physicalLeft;
3558 naturalPhysicalTop = mViewport.physicalTop;
3559 naturalDeviceWidth = mViewport.deviceWidth;
3560 naturalDeviceHeight = mViewport.deviceHeight;
3561 break;
3562 }
3563
3564 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3565 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3566 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3567 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3568
3569 mSurfaceOrientation = mParameters.orientationAware ?
3570 mViewport.orientation : DISPLAY_ORIENTATION_0;
3571 } else {
3572 mSurfaceWidth = rawWidth;
3573 mSurfaceHeight = rawHeight;
3574 mSurfaceLeft = 0;
3575 mSurfaceTop = 0;
3576 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3577 }
3578 }
3579
3580 // If moving between pointer modes, need to reset some state.
3581 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3582 if (deviceModeChanged) {
3583 mOrientedRanges.clear();
3584 }
3585
3586 // Create pointer controller if needed.
3587 if (mDeviceMode == DEVICE_MODE_POINTER ||
3588 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3589 if (mPointerController == NULL) {
3590 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3591 }
3592 } else {
3593 mPointerController.clear();
3594 }
3595
3596 if (viewportChanged || deviceModeChanged) {
3597 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3598 "display id %d",
3599 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3600 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3601
3602 // Configure X and Y factors.
3603 mXScale = float(mSurfaceWidth) / rawWidth;
3604 mYScale = float(mSurfaceHeight) / rawHeight;
3605 mXTranslate = -mSurfaceLeft;
3606 mYTranslate = -mSurfaceTop;
3607 mXPrecision = 1.0f / mXScale;
3608 mYPrecision = 1.0f / mYScale;
3609
3610 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3611 mOrientedRanges.x.source = mSource;
3612 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3613 mOrientedRanges.y.source = mSource;
3614
3615 configureVirtualKeys();
3616
3617 // Scale factor for terms that are not oriented in a particular axis.
3618 // If the pixels are square then xScale == yScale otherwise we fake it
3619 // by choosing an average.
3620 mGeometricScale = avg(mXScale, mYScale);
3621
3622 // Size of diagonal axis.
3623 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3624
3625 // Size factors.
3626 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3627 if (mRawPointerAxes.touchMajor.valid
3628 && mRawPointerAxes.touchMajor.maxValue != 0) {
3629 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3630 } else if (mRawPointerAxes.toolMajor.valid
3631 && mRawPointerAxes.toolMajor.maxValue != 0) {
3632 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3633 } else {
3634 mSizeScale = 0.0f;
3635 }
3636
3637 mOrientedRanges.haveTouchSize = true;
3638 mOrientedRanges.haveToolSize = true;
3639 mOrientedRanges.haveSize = true;
3640
3641 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3642 mOrientedRanges.touchMajor.source = mSource;
3643 mOrientedRanges.touchMajor.min = 0;
3644 mOrientedRanges.touchMajor.max = diagonalSize;
3645 mOrientedRanges.touchMajor.flat = 0;
3646 mOrientedRanges.touchMajor.fuzz = 0;
3647 mOrientedRanges.touchMajor.resolution = 0;
3648
3649 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3650 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3651
3652 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3653 mOrientedRanges.toolMajor.source = mSource;
3654 mOrientedRanges.toolMajor.min = 0;
3655 mOrientedRanges.toolMajor.max = diagonalSize;
3656 mOrientedRanges.toolMajor.flat = 0;
3657 mOrientedRanges.toolMajor.fuzz = 0;
3658 mOrientedRanges.toolMajor.resolution = 0;
3659
3660 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3661 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3662
3663 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3664 mOrientedRanges.size.source = mSource;
3665 mOrientedRanges.size.min = 0;
3666 mOrientedRanges.size.max = 1.0;
3667 mOrientedRanges.size.flat = 0;
3668 mOrientedRanges.size.fuzz = 0;
3669 mOrientedRanges.size.resolution = 0;
3670 } else {
3671 mSizeScale = 0.0f;
3672 }
3673
3674 // Pressure factors.
3675 mPressureScale = 0;
3676 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3677 || mCalibration.pressureCalibration
3678 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3679 if (mCalibration.havePressureScale) {
3680 mPressureScale = mCalibration.pressureScale;
3681 } else if (mRawPointerAxes.pressure.valid
3682 && mRawPointerAxes.pressure.maxValue != 0) {
3683 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3684 }
3685 }
3686
3687 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3688 mOrientedRanges.pressure.source = mSource;
3689 mOrientedRanges.pressure.min = 0;
3690 mOrientedRanges.pressure.max = 1.0;
3691 mOrientedRanges.pressure.flat = 0;
3692 mOrientedRanges.pressure.fuzz = 0;
3693 mOrientedRanges.pressure.resolution = 0;
3694
3695 // Tilt
3696 mTiltXCenter = 0;
3697 mTiltXScale = 0;
3698 mTiltYCenter = 0;
3699 mTiltYScale = 0;
3700 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3701 if (mHaveTilt) {
3702 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3703 mRawPointerAxes.tiltX.maxValue);
3704 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3705 mRawPointerAxes.tiltY.maxValue);
3706 mTiltXScale = M_PI / 180;
3707 mTiltYScale = M_PI / 180;
3708
3709 mOrientedRanges.haveTilt = true;
3710
3711 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3712 mOrientedRanges.tilt.source = mSource;
3713 mOrientedRanges.tilt.min = 0;
3714 mOrientedRanges.tilt.max = M_PI_2;
3715 mOrientedRanges.tilt.flat = 0;
3716 mOrientedRanges.tilt.fuzz = 0;
3717 mOrientedRanges.tilt.resolution = 0;
3718 }
3719
3720 // Orientation
3721 mOrientationScale = 0;
3722 if (mHaveTilt) {
3723 mOrientedRanges.haveOrientation = true;
3724
3725 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3726 mOrientedRanges.orientation.source = mSource;
3727 mOrientedRanges.orientation.min = -M_PI;
3728 mOrientedRanges.orientation.max = M_PI;
3729 mOrientedRanges.orientation.flat = 0;
3730 mOrientedRanges.orientation.fuzz = 0;
3731 mOrientedRanges.orientation.resolution = 0;
3732 } else if (mCalibration.orientationCalibration !=
3733 Calibration::ORIENTATION_CALIBRATION_NONE) {
3734 if (mCalibration.orientationCalibration
3735 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3736 if (mRawPointerAxes.orientation.valid) {
3737 if (mRawPointerAxes.orientation.maxValue > 0) {
3738 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3739 } else if (mRawPointerAxes.orientation.minValue < 0) {
3740 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3741 } else {
3742 mOrientationScale = 0;
3743 }
3744 }
3745 }
3746
3747 mOrientedRanges.haveOrientation = true;
3748
3749 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3750 mOrientedRanges.orientation.source = mSource;
3751 mOrientedRanges.orientation.min = -M_PI_2;
3752 mOrientedRanges.orientation.max = M_PI_2;
3753 mOrientedRanges.orientation.flat = 0;
3754 mOrientedRanges.orientation.fuzz = 0;
3755 mOrientedRanges.orientation.resolution = 0;
3756 }
3757
3758 // Distance
3759 mDistanceScale = 0;
3760 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3761 if (mCalibration.distanceCalibration
3762 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3763 if (mCalibration.haveDistanceScale) {
3764 mDistanceScale = mCalibration.distanceScale;
3765 } else {
3766 mDistanceScale = 1.0f;
3767 }
3768 }
3769
3770 mOrientedRanges.haveDistance = true;
3771
3772 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3773 mOrientedRanges.distance.source = mSource;
3774 mOrientedRanges.distance.min =
3775 mRawPointerAxes.distance.minValue * mDistanceScale;
3776 mOrientedRanges.distance.max =
3777 mRawPointerAxes.distance.maxValue * mDistanceScale;
3778 mOrientedRanges.distance.flat = 0;
3779 mOrientedRanges.distance.fuzz =
3780 mRawPointerAxes.distance.fuzz * mDistanceScale;
3781 mOrientedRanges.distance.resolution = 0;
3782 }
3783
3784 // Compute oriented precision, scales and ranges.
3785 // Note that the maximum value reported is an inclusive maximum value so it is one
3786 // unit less than the total width or height of surface.
3787 switch (mSurfaceOrientation) {
3788 case DISPLAY_ORIENTATION_90:
3789 case DISPLAY_ORIENTATION_270:
3790 mOrientedXPrecision = mYPrecision;
3791 mOrientedYPrecision = mXPrecision;
3792
3793 mOrientedRanges.x.min = mYTranslate;
3794 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3795 mOrientedRanges.x.flat = 0;
3796 mOrientedRanges.x.fuzz = 0;
3797 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3798
3799 mOrientedRanges.y.min = mXTranslate;
3800 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3801 mOrientedRanges.y.flat = 0;
3802 mOrientedRanges.y.fuzz = 0;
3803 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3804 break;
3805
3806 default:
3807 mOrientedXPrecision = mXPrecision;
3808 mOrientedYPrecision = mYPrecision;
3809
3810 mOrientedRanges.x.min = mXTranslate;
3811 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3812 mOrientedRanges.x.flat = 0;
3813 mOrientedRanges.x.fuzz = 0;
3814 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3815
3816 mOrientedRanges.y.min = mYTranslate;
3817 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3818 mOrientedRanges.y.flat = 0;
3819 mOrientedRanges.y.fuzz = 0;
3820 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3821 break;
3822 }
3823
Jason Gerecke71b16e82014-03-10 09:47:59 -07003824 // Location
3825 updateAffineTransformation();
3826
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 if (mDeviceMode == DEVICE_MODE_POINTER) {
3828 // Compute pointer gesture detection parameters.
3829 float rawDiagonal = hypotf(rawWidth, rawHeight);
3830 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3831
3832 // Scale movements such that one whole swipe of the touch pad covers a
3833 // given area relative to the diagonal size of the display when no acceleration
3834 // is applied.
3835 // Assume that the touch pad has a square aspect ratio such that movements in
3836 // X and Y of the same number of raw units cover the same physical distance.
3837 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3838 * displayDiagonal / rawDiagonal;
3839 mPointerYMovementScale = mPointerXMovementScale;
3840
3841 // Scale zooms to cover a smaller range of the display than movements do.
3842 // This value determines the area around the pointer that is affected by freeform
3843 // pointer gestures.
3844 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3845 * displayDiagonal / rawDiagonal;
3846 mPointerYZoomScale = mPointerXZoomScale;
3847
3848 // Max width between pointers to detect a swipe gesture is more than some fraction
3849 // of the diagonal axis of the touch pad. Touches that are wider than this are
3850 // translated into freeform gestures.
3851 mPointerGestureMaxSwipeWidth =
3852 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3853
3854 // Abort current pointer usages because the state has changed.
3855 abortPointerUsage(when, 0 /*policyFlags*/);
3856 }
3857
3858 // Inform the dispatcher about the changes.
3859 *outResetNeeded = true;
3860 bumpGeneration();
3861 }
3862}
3863
3864void TouchInputMapper::dumpSurface(String8& dump) {
3865 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3866 "logicalFrame=[%d, %d, %d, %d], "
3867 "physicalFrame=[%d, %d, %d, %d], "
3868 "deviceSize=[%d, %d]\n",
3869 mViewport.displayId, mViewport.orientation,
3870 mViewport.logicalLeft, mViewport.logicalTop,
3871 mViewport.logicalRight, mViewport.logicalBottom,
3872 mViewport.physicalLeft, mViewport.physicalTop,
3873 mViewport.physicalRight, mViewport.physicalBottom,
3874 mViewport.deviceWidth, mViewport.deviceHeight);
3875
3876 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3877 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3878 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3879 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3880 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3881}
3882
3883void TouchInputMapper::configureVirtualKeys() {
3884 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3885 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3886
3887 mVirtualKeys.clear();
3888
3889 if (virtualKeyDefinitions.size() == 0) {
3890 return;
3891 }
3892
3893 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3894
3895 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3896 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3897 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3898 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3899
3900 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3901 const VirtualKeyDefinition& virtualKeyDefinition =
3902 virtualKeyDefinitions[i];
3903
3904 mVirtualKeys.add();
3905 VirtualKey& virtualKey = mVirtualKeys.editTop();
3906
3907 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3908 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003909 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003911 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3912 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3914 virtualKey.scanCode);
3915 mVirtualKeys.pop(); // drop the key
3916 continue;
3917 }
3918
3919 virtualKey.keyCode = keyCode;
3920 virtualKey.flags = flags;
3921
3922 // convert the key definition's display coordinates into touch coordinates for a hit box
3923 int32_t halfWidth = virtualKeyDefinition.width / 2;
3924 int32_t halfHeight = virtualKeyDefinition.height / 2;
3925
3926 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3927 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3928 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3929 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3930 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3931 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3932 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3933 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3934 }
3935}
3936
3937void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3938 if (!mVirtualKeys.isEmpty()) {
3939 dump.append(INDENT3 "Virtual Keys:\n");
3940
3941 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3942 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003943 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3945 i, virtualKey.scanCode, virtualKey.keyCode,
3946 virtualKey.hitLeft, virtualKey.hitRight,
3947 virtualKey.hitTop, virtualKey.hitBottom);
3948 }
3949 }
3950}
3951
3952void TouchInputMapper::parseCalibration() {
3953 const PropertyMap& in = getDevice()->getConfiguration();
3954 Calibration& out = mCalibration;
3955
3956 // Size
3957 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3958 String8 sizeCalibrationString;
3959 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3960 if (sizeCalibrationString == "none") {
3961 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3962 } else if (sizeCalibrationString == "geometric") {
3963 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3964 } else if (sizeCalibrationString == "diameter") {
3965 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3966 } else if (sizeCalibrationString == "box") {
3967 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3968 } else if (sizeCalibrationString == "area") {
3969 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3970 } else if (sizeCalibrationString != "default") {
3971 ALOGW("Invalid value for touch.size.calibration: '%s'",
3972 sizeCalibrationString.string());
3973 }
3974 }
3975
3976 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3977 out.sizeScale);
3978 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3979 out.sizeBias);
3980 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3981 out.sizeIsSummed);
3982
3983 // Pressure
3984 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3985 String8 pressureCalibrationString;
3986 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3987 if (pressureCalibrationString == "none") {
3988 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3989 } else if (pressureCalibrationString == "physical") {
3990 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3991 } else if (pressureCalibrationString == "amplitude") {
3992 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3993 } else if (pressureCalibrationString != "default") {
3994 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3995 pressureCalibrationString.string());
3996 }
3997 }
3998
3999 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4000 out.pressureScale);
4001
4002 // Orientation
4003 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4004 String8 orientationCalibrationString;
4005 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4006 if (orientationCalibrationString == "none") {
4007 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4008 } else if (orientationCalibrationString == "interpolated") {
4009 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4010 } else if (orientationCalibrationString == "vector") {
4011 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4012 } else if (orientationCalibrationString != "default") {
4013 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4014 orientationCalibrationString.string());
4015 }
4016 }
4017
4018 // Distance
4019 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4020 String8 distanceCalibrationString;
4021 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4022 if (distanceCalibrationString == "none") {
4023 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4024 } else if (distanceCalibrationString == "scaled") {
4025 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4026 } else if (distanceCalibrationString != "default") {
4027 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4028 distanceCalibrationString.string());
4029 }
4030 }
4031
4032 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4033 out.distanceScale);
4034
4035 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4036 String8 coverageCalibrationString;
4037 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4038 if (coverageCalibrationString == "none") {
4039 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4040 } else if (coverageCalibrationString == "box") {
4041 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4042 } else if (coverageCalibrationString != "default") {
4043 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4044 coverageCalibrationString.string());
4045 }
4046 }
4047}
4048
4049void TouchInputMapper::resolveCalibration() {
4050 // Size
4051 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4052 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4053 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4054 }
4055 } else {
4056 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4057 }
4058
4059 // Pressure
4060 if (mRawPointerAxes.pressure.valid) {
4061 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4062 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4063 }
4064 } else {
4065 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4066 }
4067
4068 // Orientation
4069 if (mRawPointerAxes.orientation.valid) {
4070 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4071 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4072 }
4073 } else {
4074 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4075 }
4076
4077 // Distance
4078 if (mRawPointerAxes.distance.valid) {
4079 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4080 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4081 }
4082 } else {
4083 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4084 }
4085
4086 // Coverage
4087 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4088 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4089 }
4090}
4091
4092void TouchInputMapper::dumpCalibration(String8& dump) {
4093 dump.append(INDENT3 "Calibration:\n");
4094
4095 // Size
4096 switch (mCalibration.sizeCalibration) {
4097 case Calibration::SIZE_CALIBRATION_NONE:
4098 dump.append(INDENT4 "touch.size.calibration: none\n");
4099 break;
4100 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4101 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4102 break;
4103 case Calibration::SIZE_CALIBRATION_DIAMETER:
4104 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4105 break;
4106 case Calibration::SIZE_CALIBRATION_BOX:
4107 dump.append(INDENT4 "touch.size.calibration: box\n");
4108 break;
4109 case Calibration::SIZE_CALIBRATION_AREA:
4110 dump.append(INDENT4 "touch.size.calibration: area\n");
4111 break;
4112 default:
4113 ALOG_ASSERT(false);
4114 }
4115
4116 if (mCalibration.haveSizeScale) {
4117 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4118 mCalibration.sizeScale);
4119 }
4120
4121 if (mCalibration.haveSizeBias) {
4122 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4123 mCalibration.sizeBias);
4124 }
4125
4126 if (mCalibration.haveSizeIsSummed) {
4127 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4128 toString(mCalibration.sizeIsSummed));
4129 }
4130
4131 // Pressure
4132 switch (mCalibration.pressureCalibration) {
4133 case Calibration::PRESSURE_CALIBRATION_NONE:
4134 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4135 break;
4136 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4137 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4138 break;
4139 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4140 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4141 break;
4142 default:
4143 ALOG_ASSERT(false);
4144 }
4145
4146 if (mCalibration.havePressureScale) {
4147 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4148 mCalibration.pressureScale);
4149 }
4150
4151 // Orientation
4152 switch (mCalibration.orientationCalibration) {
4153 case Calibration::ORIENTATION_CALIBRATION_NONE:
4154 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4155 break;
4156 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4157 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4158 break;
4159 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4160 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4161 break;
4162 default:
4163 ALOG_ASSERT(false);
4164 }
4165
4166 // Distance
4167 switch (mCalibration.distanceCalibration) {
4168 case Calibration::DISTANCE_CALIBRATION_NONE:
4169 dump.append(INDENT4 "touch.distance.calibration: none\n");
4170 break;
4171 case Calibration::DISTANCE_CALIBRATION_SCALED:
4172 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4173 break;
4174 default:
4175 ALOG_ASSERT(false);
4176 }
4177
4178 if (mCalibration.haveDistanceScale) {
4179 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4180 mCalibration.distanceScale);
4181 }
4182
4183 switch (mCalibration.coverageCalibration) {
4184 case Calibration::COVERAGE_CALIBRATION_NONE:
4185 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4186 break;
4187 case Calibration::COVERAGE_CALIBRATION_BOX:
4188 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4189 break;
4190 default:
4191 ALOG_ASSERT(false);
4192 }
4193}
4194
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004195void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4196 dump.append(INDENT3 "Affine Transformation:\n");
4197
4198 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4199 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4200 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4201 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4202 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4203 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4204}
4205
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004206void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004207 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4208 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004209}
4210
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211void TouchInputMapper::reset(nsecs_t when) {
4212 mCursorButtonAccumulator.reset(getDevice());
4213 mCursorScrollAccumulator.reset(getDevice());
4214 mTouchButtonAccumulator.reset(getDevice());
4215
4216 mPointerVelocityControl.reset();
4217 mWheelXVelocityControl.reset();
4218 mWheelYVelocityControl.reset();
4219
Michael Wright842500e2015-03-13 17:32:02 -07004220 mRawStatesPending.clear();
4221 mCurrentRawState.clear();
4222 mCurrentCookedState.clear();
4223 mLastRawState.clear();
4224 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 mPointerUsage = POINTER_USAGE_NONE;
4226 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004227 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004228 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 mDownTime = 0;
4230
4231 mCurrentVirtualKey.down = false;
4232
4233 mPointerGesture.reset();
4234 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004235 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236
4237 if (mPointerController != NULL) {
4238 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4239 mPointerController->clearSpots();
4240 }
4241
4242 InputMapper::reset(when);
4243}
4244
Michael Wright842500e2015-03-13 17:32:02 -07004245void TouchInputMapper::resetExternalStylus() {
4246 mExternalStylusState.clear();
4247 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004248 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004249 mExternalStylusDataPending = false;
4250}
4251
Michael Wright43fd19f2015-04-21 19:02:58 +01004252void TouchInputMapper::clearStylusDataPendingFlags() {
4253 mExternalStylusDataPending = false;
4254 mExternalStylusFusionTimeout = LLONG_MAX;
4255}
4256
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257void TouchInputMapper::process(const RawEvent* rawEvent) {
4258 mCursorButtonAccumulator.process(rawEvent);
4259 mCursorScrollAccumulator.process(rawEvent);
4260 mTouchButtonAccumulator.process(rawEvent);
4261
4262 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4263 sync(rawEvent->when);
4264 }
4265}
4266
4267void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004268 const RawState* last = mRawStatesPending.isEmpty() ?
4269 &mCurrentRawState : &mRawStatesPending.top();
4270
4271 // Push a new state.
4272 mRawStatesPending.push();
4273 RawState* next = &mRawStatesPending.editTop();
4274 next->clear();
4275 next->when = when;
4276
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004278 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 | mCursorButtonAccumulator.getButtonState();
4280
Michael Wright842500e2015-03-13 17:32:02 -07004281 // Sync scroll
4282 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4283 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 mCursorScrollAccumulator.finishSync();
4285
Michael Wright842500e2015-03-13 17:32:02 -07004286 // Sync touch
4287 syncTouch(when, next);
4288
4289 // Assign pointer ids.
4290 if (!mHavePointerIds) {
4291 assignPointerIds(last, next);
4292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
4294#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004295 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4296 "hovering ids 0x%08x -> 0x%08x",
4297 last->rawPointerData.pointerCount,
4298 next->rawPointerData.pointerCount,
4299 last->rawPointerData.touchingIdBits.value,
4300 next->rawPointerData.touchingIdBits.value,
4301 last->rawPointerData.hoveringIdBits.value,
4302 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303#endif
4304
Michael Wright842500e2015-03-13 17:32:02 -07004305 processRawTouches(false /*timeout*/);
4306}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Michael Wright842500e2015-03-13 17:32:02 -07004308void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4310 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004311 mCurrentRawState.clear();
4312 mRawStatesPending.clear();
4313 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 }
4315
Michael Wright842500e2015-03-13 17:32:02 -07004316 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4317 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4318 // touching the current state will only observe the events that have been dispatched to the
4319 // rest of the pipeline.
4320 const size_t N = mRawStatesPending.size();
4321 size_t count;
4322 for(count = 0; count < N; count++) {
4323 const RawState& next = mRawStatesPending[count];
4324
4325 // A failure to assign the stylus id means that we're waiting on stylus data
4326 // and so should defer the rest of the pipeline.
4327 if (assignExternalStylusId(next, timeout)) {
4328 break;
4329 }
4330
4331 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004332 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004333 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004334 if (mCurrentRawState.when < mLastRawState.when) {
4335 mCurrentRawState.when = mLastRawState.when;
4336 }
Michael Wright842500e2015-03-13 17:32:02 -07004337 cookAndDispatch(mCurrentRawState.when);
4338 }
4339 if (count != 0) {
4340 mRawStatesPending.removeItemsAt(0, count);
4341 }
4342
Michael Wright842500e2015-03-13 17:32:02 -07004343 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004344 if (timeout) {
4345 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4346 clearStylusDataPendingFlags();
4347 mCurrentRawState.copyFrom(mLastRawState);
4348#if DEBUG_STYLUS_FUSION
4349 ALOGD("Timeout expired, synthesizing event with new stylus data");
4350#endif
4351 cookAndDispatch(when);
4352 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4353 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4354 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4355 }
Michael Wright842500e2015-03-13 17:32:02 -07004356 }
4357}
4358
4359void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4360 // Always start with a clean state.
4361 mCurrentCookedState.clear();
4362
4363 // Apply stylus buttons to current raw state.
4364 applyExternalStylusButtonState(when);
4365
4366 // Handle policy on initial down or hover events.
4367 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4368 && mCurrentRawState.rawPointerData.pointerCount != 0;
4369
4370 uint32_t policyFlags = 0;
4371 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4372 if (initialDown || buttonsPressed) {
4373 // If this is a touch screen, hide the pointer on an initial down.
4374 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4375 getContext()->fadePointer();
4376 }
4377
4378 if (mParameters.wake) {
4379 policyFlags |= POLICY_FLAG_WAKE;
4380 }
4381 }
4382
4383 // Consume raw off-screen touches before cooking pointer data.
4384 // If touches are consumed, subsequent code will not receive any pointer data.
4385 if (consumeRawTouches(when, policyFlags)) {
4386 mCurrentRawState.rawPointerData.clear();
4387 }
4388
4389 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4390 // with cooked pointer data that has the same ids and indices as the raw data.
4391 // The following code can use either the raw or cooked data, as needed.
4392 cookPointerData();
4393
4394 // Apply stylus pressure to current cooked state.
4395 applyExternalStylusTouchState(when);
4396
4397 // Synthesize key down from raw buttons if needed.
4398 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004399 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004400
4401 // Dispatch the touches either directly or by translation through a pointer on screen.
4402 if (mDeviceMode == DEVICE_MODE_POINTER) {
4403 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4404 !idBits.isEmpty(); ) {
4405 uint32_t id = idBits.clearFirstMarkedBit();
4406 const RawPointerData::Pointer& pointer =
4407 mCurrentRawState.rawPointerData.pointerForId(id);
4408 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4409 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4410 mCurrentCookedState.stylusIdBits.markBit(id);
4411 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4412 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4413 mCurrentCookedState.fingerIdBits.markBit(id);
4414 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4415 mCurrentCookedState.mouseIdBits.markBit(id);
4416 }
4417 }
4418 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4419 !idBits.isEmpty(); ) {
4420 uint32_t id = idBits.clearFirstMarkedBit();
4421 const RawPointerData::Pointer& pointer =
4422 mCurrentRawState.rawPointerData.pointerForId(id);
4423 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4424 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4425 mCurrentCookedState.stylusIdBits.markBit(id);
4426 }
4427 }
4428
4429 // Stylus takes precedence over all tools, then mouse, then finger.
4430 PointerUsage pointerUsage = mPointerUsage;
4431 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4432 mCurrentCookedState.mouseIdBits.clear();
4433 mCurrentCookedState.fingerIdBits.clear();
4434 pointerUsage = POINTER_USAGE_STYLUS;
4435 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4436 mCurrentCookedState.fingerIdBits.clear();
4437 pointerUsage = POINTER_USAGE_MOUSE;
4438 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4439 isPointerDown(mCurrentRawState.buttonState)) {
4440 pointerUsage = POINTER_USAGE_GESTURES;
4441 }
4442
4443 dispatchPointerUsage(when, policyFlags, pointerUsage);
4444 } else {
4445 if (mDeviceMode == DEVICE_MODE_DIRECT
4446 && mConfig.showTouches && mPointerController != NULL) {
4447 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4448 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4449
4450 mPointerController->setButtonState(mCurrentRawState.buttonState);
4451 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4452 mCurrentCookedState.cookedPointerData.idToIndex,
4453 mCurrentCookedState.cookedPointerData.touchingIdBits);
4454 }
4455
Michael Wright8e812822015-06-22 16:18:21 +01004456 if (!mCurrentMotionAborted) {
4457 dispatchButtonRelease(when, policyFlags);
4458 dispatchHoverExit(when, policyFlags);
4459 dispatchTouches(when, policyFlags);
4460 dispatchHoverEnterAndMove(when, policyFlags);
4461 dispatchButtonPress(when, policyFlags);
4462 }
4463
4464 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4465 mCurrentMotionAborted = false;
4466 }
Michael Wright842500e2015-03-13 17:32:02 -07004467 }
4468
4469 // Synthesize key up from raw buttons if needed.
4470 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004471 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472
4473 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004474 mCurrentRawState.rawVScroll = 0;
4475 mCurrentRawState.rawHScroll = 0;
4476
4477 // Copy current touch to last touch in preparation for the next cycle.
4478 mLastRawState.copyFrom(mCurrentRawState);
4479 mLastCookedState.copyFrom(mCurrentCookedState);
4480}
4481
4482void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004483 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004484 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4485 }
4486}
4487
4488void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004489 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4490 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004491
Michael Wright53dca3a2015-04-23 17:39:53 +01004492 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4493 float pressure = mExternalStylusState.pressure;
4494 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4495 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4496 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4497 }
4498 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4499 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4500
4501 PointerProperties& properties =
4502 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004503 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4504 properties.toolType = mExternalStylusState.toolType;
4505 }
4506 }
4507}
4508
4509bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4510 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4511 return false;
4512 }
4513
4514 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4515 && state.rawPointerData.pointerCount != 0;
4516 if (initialDown) {
4517 if (mExternalStylusState.pressure != 0.0f) {
4518#if DEBUG_STYLUS_FUSION
4519 ALOGD("Have both stylus and touch data, beginning fusion");
4520#endif
4521 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4522 } else if (timeout) {
4523#if DEBUG_STYLUS_FUSION
4524 ALOGD("Timeout expired, assuming touch is not a stylus.");
4525#endif
4526 resetExternalStylus();
4527 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004528 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4529 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004530 }
4531#if DEBUG_STYLUS_FUSION
4532 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004533 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004534#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004535 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004536 return true;
4537 }
4538 }
4539
4540 // Check if the stylus pointer has gone up.
4541 if (mExternalStylusId != -1 &&
4542 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4543#if DEBUG_STYLUS_FUSION
4544 ALOGD("Stylus pointer is going up");
4545#endif
4546 mExternalStylusId = -1;
4547 }
4548
4549 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550}
4551
4552void TouchInputMapper::timeoutExpired(nsecs_t when) {
4553 if (mDeviceMode == DEVICE_MODE_POINTER) {
4554 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4555 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4556 }
Michael Wright842500e2015-03-13 17:32:02 -07004557 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004558 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004559 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004560 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4561 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004562 }
4563 }
4564}
4565
4566void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004567 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004568 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004569 // We're either in the middle of a fused stream of data or we're waiting on data before
4570 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4571 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004572 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004573 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 }
4575}
4576
4577bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4578 // Check for release of a virtual key.
4579 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004580 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 // Pointer went up while virtual key was down.
4582 mCurrentVirtualKey.down = false;
4583 if (!mCurrentVirtualKey.ignored) {
4584#if DEBUG_VIRTUAL_KEYS
4585 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4586 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4587#endif
4588 dispatchVirtualKey(when, policyFlags,
4589 AKEY_EVENT_ACTION_UP,
4590 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4591 }
4592 return true;
4593 }
4594
Michael Wright842500e2015-03-13 17:32:02 -07004595 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4596 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4597 const RawPointerData::Pointer& pointer =
4598 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4600 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4601 // Pointer is still within the space of the virtual key.
4602 return true;
4603 }
4604 }
4605
4606 // Pointer left virtual key area or another pointer also went down.
4607 // Send key cancellation but do not consume the touch yet.
4608 // This is useful when the user swipes through from the virtual key area
4609 // into the main display surface.
4610 mCurrentVirtualKey.down = false;
4611 if (!mCurrentVirtualKey.ignored) {
4612#if DEBUG_VIRTUAL_KEYS
4613 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4614 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4615#endif
4616 dispatchVirtualKey(when, policyFlags,
4617 AKEY_EVENT_ACTION_UP,
4618 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4619 | AKEY_EVENT_FLAG_CANCELED);
4620 }
4621 }
4622
Michael Wright842500e2015-03-13 17:32:02 -07004623 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4624 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004626 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4627 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4629 // If exactly one pointer went down, check for virtual key hit.
4630 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004631 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4633 if (virtualKey) {
4634 mCurrentVirtualKey.down = true;
4635 mCurrentVirtualKey.downTime = when;
4636 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4637 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4638 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4639 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4640
4641 if (!mCurrentVirtualKey.ignored) {
4642#if DEBUG_VIRTUAL_KEYS
4643 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4644 mCurrentVirtualKey.keyCode,
4645 mCurrentVirtualKey.scanCode);
4646#endif
4647 dispatchVirtualKey(when, policyFlags,
4648 AKEY_EVENT_ACTION_DOWN,
4649 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4650 }
4651 }
4652 }
4653 return true;
4654 }
4655 }
4656
4657 // Disable all virtual key touches that happen within a short time interval of the
4658 // most recent touch within the screen area. The idea is to filter out stray
4659 // virtual key presses when interacting with the touch screen.
4660 //
4661 // Problems we're trying to solve:
4662 //
4663 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4664 // virtual key area that is implemented by a separate touch panel and accidentally
4665 // triggers a virtual key.
4666 //
4667 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4668 // area and accidentally triggers a virtual key. This often happens when virtual keys
4669 // are layed out below the screen near to where the on screen keyboard's space bar
4670 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004671 if (mConfig.virtualKeyQuietTime > 0 &&
4672 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4674 }
4675 return false;
4676}
4677
4678void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4679 int32_t keyEventAction, int32_t keyEventFlags) {
4680 int32_t keyCode = mCurrentVirtualKey.keyCode;
4681 int32_t scanCode = mCurrentVirtualKey.scanCode;
4682 nsecs_t downTime = mCurrentVirtualKey.downTime;
4683 int32_t metaState = mContext->getGlobalMetaState();
4684 policyFlags |= POLICY_FLAG_VIRTUAL;
4685
4686 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4687 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4688 getListener()->notifyKey(&args);
4689}
4690
Michael Wright8e812822015-06-22 16:18:21 +01004691void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4692 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4693 if (!currentIdBits.isEmpty()) {
4694 int32_t metaState = getContext()->getGlobalMetaState();
4695 int32_t buttonState = mCurrentCookedState.buttonState;
4696 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4697 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4698 mCurrentCookedState.cookedPointerData.pointerProperties,
4699 mCurrentCookedState.cookedPointerData.pointerCoords,
4700 mCurrentCookedState.cookedPointerData.idToIndex,
4701 currentIdBits, -1,
4702 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4703 mCurrentMotionAborted = true;
4704 }
4705}
4706
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004708 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4709 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004711 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712
4713 if (currentIdBits == lastIdBits) {
4714 if (!currentIdBits.isEmpty()) {
4715 // No pointer id changes so this is a move event.
4716 // The listener takes care of batching moves so we don't have to deal with that here.
4717 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004718 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004720 mCurrentCookedState.cookedPointerData.pointerProperties,
4721 mCurrentCookedState.cookedPointerData.pointerCoords,
4722 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 currentIdBits, -1,
4724 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4725 }
4726 } else {
4727 // There may be pointers going up and pointers going down and pointers moving
4728 // all at the same time.
4729 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4730 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4731 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4732 BitSet32 dispatchedIdBits(lastIdBits.value);
4733
4734 // Update last coordinates of pointers that have moved so that we observe the new
4735 // pointer positions at the same time as other pointers that have just gone up.
4736 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004737 mCurrentCookedState.cookedPointerData.pointerProperties,
4738 mCurrentCookedState.cookedPointerData.pointerCoords,
4739 mCurrentCookedState.cookedPointerData.idToIndex,
4740 mLastCookedState.cookedPointerData.pointerProperties,
4741 mLastCookedState.cookedPointerData.pointerCoords,
4742 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004744 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 moveNeeded = true;
4746 }
4747
4748 // Dispatch pointer up events.
4749 while (!upIdBits.isEmpty()) {
4750 uint32_t upId = upIdBits.clearFirstMarkedBit();
4751
4752 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004753 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004754 mLastCookedState.cookedPointerData.pointerProperties,
4755 mLastCookedState.cookedPointerData.pointerCoords,
4756 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004757 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 dispatchedIdBits.clearBit(upId);
4759 }
4760
4761 // Dispatch move events if any of the remaining pointers moved from their old locations.
4762 // Although applications receive new locations as part of individual pointer up
4763 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004764 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4766 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004767 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004768 mCurrentCookedState.cookedPointerData.pointerProperties,
4769 mCurrentCookedState.cookedPointerData.pointerCoords,
4770 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004771 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773
4774 // Dispatch pointer down events using the new pointer locations.
4775 while (!downIdBits.isEmpty()) {
4776 uint32_t downId = downIdBits.clearFirstMarkedBit();
4777 dispatchedIdBits.markBit(downId);
4778
4779 if (dispatchedIdBits.count() == 1) {
4780 // First pointer is going down. Set down time.
4781 mDownTime = when;
4782 }
4783
4784 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004785 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004786 mCurrentCookedState.cookedPointerData.pointerProperties,
4787 mCurrentCookedState.cookedPointerData.pointerCoords,
4788 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004789 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 }
4791 }
4792}
4793
4794void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4795 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004796 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4797 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 int32_t metaState = getContext()->getGlobalMetaState();
4799 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004800 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004801 mLastCookedState.cookedPointerData.pointerProperties,
4802 mLastCookedState.cookedPointerData.pointerCoords,
4803 mLastCookedState.cookedPointerData.idToIndex,
4804 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4806 mSentHoverEnter = false;
4807 }
4808}
4809
4810void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004811 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4812 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 int32_t metaState = getContext()->getGlobalMetaState();
4814 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004815 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004816 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004817 mCurrentCookedState.cookedPointerData.pointerProperties,
4818 mCurrentCookedState.cookedPointerData.pointerCoords,
4819 mCurrentCookedState.cookedPointerData.idToIndex,
4820 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4822 mSentHoverEnter = true;
4823 }
4824
4825 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004826 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004827 mCurrentRawState.buttonState, 0,
4828 mCurrentCookedState.cookedPointerData.pointerProperties,
4829 mCurrentCookedState.cookedPointerData.pointerCoords,
4830 mCurrentCookedState.cookedPointerData.idToIndex,
4831 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4833 }
4834}
4835
Michael Wright7b159c92015-05-14 14:48:03 +01004836void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4837 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4838 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4839 const int32_t metaState = getContext()->getGlobalMetaState();
4840 int32_t buttonState = mLastCookedState.buttonState;
4841 while (!releasedButtons.isEmpty()) {
4842 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4843 buttonState &= ~actionButton;
4844 dispatchMotion(when, policyFlags, mSource,
4845 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4846 0, metaState, buttonState, 0,
4847 mCurrentCookedState.cookedPointerData.pointerProperties,
4848 mCurrentCookedState.cookedPointerData.pointerCoords,
4849 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4850 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4851 }
4852}
4853
4854void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4855 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4856 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4857 const int32_t metaState = getContext()->getGlobalMetaState();
4858 int32_t buttonState = mLastCookedState.buttonState;
4859 while (!pressedButtons.isEmpty()) {
4860 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4861 buttonState |= actionButton;
4862 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4863 0, metaState, buttonState, 0,
4864 mCurrentCookedState.cookedPointerData.pointerProperties,
4865 mCurrentCookedState.cookedPointerData.pointerCoords,
4866 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4867 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4868 }
4869}
4870
4871const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4872 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4873 return cookedPointerData.touchingIdBits;
4874 }
4875 return cookedPointerData.hoveringIdBits;
4876}
4877
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004879 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880
Michael Wright842500e2015-03-13 17:32:02 -07004881 mCurrentCookedState.cookedPointerData.clear();
4882 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4883 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4884 mCurrentRawState.rawPointerData.hoveringIdBits;
4885 mCurrentCookedState.cookedPointerData.touchingIdBits =
4886 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887
Michael Wright7b159c92015-05-14 14:48:03 +01004888 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4889 mCurrentCookedState.buttonState = 0;
4890 } else {
4891 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4892 }
4893
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 // Walk through the the active pointers and map device coordinates onto
4895 // surface coordinates and adjust for display orientation.
4896 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004897 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898
4899 // Size
4900 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4901 switch (mCalibration.sizeCalibration) {
4902 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4903 case Calibration::SIZE_CALIBRATION_DIAMETER:
4904 case Calibration::SIZE_CALIBRATION_BOX:
4905 case Calibration::SIZE_CALIBRATION_AREA:
4906 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4907 touchMajor = in.touchMajor;
4908 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4909 toolMajor = in.toolMajor;
4910 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4911 size = mRawPointerAxes.touchMinor.valid
4912 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4913 } else if (mRawPointerAxes.touchMajor.valid) {
4914 toolMajor = touchMajor = in.touchMajor;
4915 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4916 ? in.touchMinor : in.touchMajor;
4917 size = mRawPointerAxes.touchMinor.valid
4918 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4919 } else if (mRawPointerAxes.toolMajor.valid) {
4920 touchMajor = toolMajor = in.toolMajor;
4921 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4922 ? in.toolMinor : in.toolMajor;
4923 size = mRawPointerAxes.toolMinor.valid
4924 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4925 } else {
4926 ALOG_ASSERT(false, "No touch or tool axes. "
4927 "Size calibration should have been resolved to NONE.");
4928 touchMajor = 0;
4929 touchMinor = 0;
4930 toolMajor = 0;
4931 toolMinor = 0;
4932 size = 0;
4933 }
4934
4935 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004936 uint32_t touchingCount =
4937 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 if (touchingCount > 1) {
4939 touchMajor /= touchingCount;
4940 touchMinor /= touchingCount;
4941 toolMajor /= touchingCount;
4942 toolMinor /= touchingCount;
4943 size /= touchingCount;
4944 }
4945 }
4946
4947 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4948 touchMajor *= mGeometricScale;
4949 touchMinor *= mGeometricScale;
4950 toolMajor *= mGeometricScale;
4951 toolMinor *= mGeometricScale;
4952 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4953 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4954 touchMinor = touchMajor;
4955 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4956 toolMinor = toolMajor;
4957 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4958 touchMinor = touchMajor;
4959 toolMinor = toolMajor;
4960 }
4961
4962 mCalibration.applySizeScaleAndBias(&touchMajor);
4963 mCalibration.applySizeScaleAndBias(&touchMinor);
4964 mCalibration.applySizeScaleAndBias(&toolMajor);
4965 mCalibration.applySizeScaleAndBias(&toolMinor);
4966 size *= mSizeScale;
4967 break;
4968 default:
4969 touchMajor = 0;
4970 touchMinor = 0;
4971 toolMajor = 0;
4972 toolMinor = 0;
4973 size = 0;
4974 break;
4975 }
4976
4977 // Pressure
4978 float pressure;
4979 switch (mCalibration.pressureCalibration) {
4980 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4981 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4982 pressure = in.pressure * mPressureScale;
4983 break;
4984 default:
4985 pressure = in.isHovering ? 0 : 1;
4986 break;
4987 }
4988
4989 // Tilt and Orientation
4990 float tilt;
4991 float orientation;
4992 if (mHaveTilt) {
4993 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4994 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4995 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4996 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4997 } else {
4998 tilt = 0;
4999
5000 switch (mCalibration.orientationCalibration) {
5001 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5002 orientation = in.orientation * mOrientationScale;
5003 break;
5004 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5005 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5006 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5007 if (c1 != 0 || c2 != 0) {
5008 orientation = atan2f(c1, c2) * 0.5f;
5009 float confidence = hypotf(c1, c2);
5010 float scale = 1.0f + confidence / 16.0f;
5011 touchMajor *= scale;
5012 touchMinor /= scale;
5013 toolMajor *= scale;
5014 toolMinor /= scale;
5015 } else {
5016 orientation = 0;
5017 }
5018 break;
5019 }
5020 default:
5021 orientation = 0;
5022 }
5023 }
5024
5025 // Distance
5026 float distance;
5027 switch (mCalibration.distanceCalibration) {
5028 case Calibration::DISTANCE_CALIBRATION_SCALED:
5029 distance = in.distance * mDistanceScale;
5030 break;
5031 default:
5032 distance = 0;
5033 }
5034
5035 // Coverage
5036 int32_t rawLeft, rawTop, rawRight, rawBottom;
5037 switch (mCalibration.coverageCalibration) {
5038 case Calibration::COVERAGE_CALIBRATION_BOX:
5039 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5040 rawRight = in.toolMinor & 0x0000ffff;
5041 rawBottom = in.toolMajor & 0x0000ffff;
5042 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5043 break;
5044 default:
5045 rawLeft = rawTop = rawRight = rawBottom = 0;
5046 break;
5047 }
5048
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005049 // Adjust X,Y coords for device calibration
5050 // TODO: Adjust coverage coords?
5051 float xTransformed = in.x, yTransformed = in.y;
5052 mAffineTransform.applyTo(xTransformed, yTransformed);
5053
5054 // Adjust X, Y, and coverage coords for surface orientation.
5055 float x, y;
5056 float left, top, right, bottom;
5057
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 switch (mSurfaceOrientation) {
5059 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005060 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5061 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5063 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5064 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5065 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5066 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005067 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5069 }
5070 break;
5071 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005072 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5073 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5075 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5076 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5077 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5078 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005079 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5081 }
5082 break;
5083 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005084 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5085 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5087 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5088 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5089 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5090 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005091 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5093 }
5094 break;
5095 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005096 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5097 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5099 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5100 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5101 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5102 break;
5103 }
5104
5105 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005106 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 out.clear();
5108 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5109 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5110 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5111 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5112 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5113 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5114 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5115 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5116 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5117 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5118 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5119 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5120 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5121 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5122 } else {
5123 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5124 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5125 }
5126
5127 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005128 PointerProperties& properties =
5129 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 uint32_t id = in.id;
5131 properties.clear();
5132 properties.id = id;
5133 properties.toolType = in.toolType;
5134
5135 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005136 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 }
5138}
5139
5140void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5141 PointerUsage pointerUsage) {
5142 if (pointerUsage != mPointerUsage) {
5143 abortPointerUsage(when, policyFlags);
5144 mPointerUsage = pointerUsage;
5145 }
5146
5147 switch (mPointerUsage) {
5148 case POINTER_USAGE_GESTURES:
5149 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5150 break;
5151 case POINTER_USAGE_STYLUS:
5152 dispatchPointerStylus(when, policyFlags);
5153 break;
5154 case POINTER_USAGE_MOUSE:
5155 dispatchPointerMouse(when, policyFlags);
5156 break;
5157 default:
5158 break;
5159 }
5160}
5161
5162void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5163 switch (mPointerUsage) {
5164 case POINTER_USAGE_GESTURES:
5165 abortPointerGestures(when, policyFlags);
5166 break;
5167 case POINTER_USAGE_STYLUS:
5168 abortPointerStylus(when, policyFlags);
5169 break;
5170 case POINTER_USAGE_MOUSE:
5171 abortPointerMouse(when, policyFlags);
5172 break;
5173 default:
5174 break;
5175 }
5176
5177 mPointerUsage = POINTER_USAGE_NONE;
5178}
5179
5180void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5181 bool isTimeout) {
5182 // Update current gesture coordinates.
5183 bool cancelPreviousGesture, finishPreviousGesture;
5184 bool sendEvents = preparePointerGestures(when,
5185 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5186 if (!sendEvents) {
5187 return;
5188 }
5189 if (finishPreviousGesture) {
5190 cancelPreviousGesture = false;
5191 }
5192
5193 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005194 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5195 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 if (finishPreviousGesture || cancelPreviousGesture) {
5197 mPointerController->clearSpots();
5198 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005199
5200 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5201 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5202 mPointerGesture.currentGestureIdToIndex,
5203 mPointerGesture.currentGestureIdBits);
5204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 } else {
5206 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5207 }
5208
5209 // Show or hide the pointer if needed.
5210 switch (mPointerGesture.currentGestureMode) {
5211 case PointerGesture::NEUTRAL:
5212 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005213 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5214 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 // Remind the user of where the pointer is after finishing a gesture with spots.
5216 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5217 }
5218 break;
5219 case PointerGesture::TAP:
5220 case PointerGesture::TAP_DRAG:
5221 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5222 case PointerGesture::HOVER:
5223 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005224 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225 // Unfade the pointer when the current gesture manipulates the
5226 // area directly under the pointer.
5227 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5228 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 case PointerGesture::FREEFORM:
5230 // Fade the pointer when the current gesture manipulates a different
5231 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005232 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5234 } else {
5235 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5236 }
5237 break;
5238 }
5239
5240 // Send events!
5241 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005242 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243
5244 // Update last coordinates of pointers that have moved so that we observe the new
5245 // pointer positions at the same time as other pointers that have just gone up.
5246 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5247 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5248 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5249 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5250 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5251 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5252 bool moveNeeded = false;
5253 if (down && !cancelPreviousGesture && !finishPreviousGesture
5254 && !mPointerGesture.lastGestureIdBits.isEmpty()
5255 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5256 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5257 & mPointerGesture.lastGestureIdBits.value);
5258 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5259 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5260 mPointerGesture.lastGestureProperties,
5261 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5262 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005263 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 moveNeeded = true;
5265 }
5266 }
5267
5268 // Send motion events for all pointers that went up or were canceled.
5269 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5270 if (!dispatchedGestureIdBits.isEmpty()) {
5271 if (cancelPreviousGesture) {
5272 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005273 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 AMOTION_EVENT_EDGE_FLAG_NONE,
5275 mPointerGesture.lastGestureProperties,
5276 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005277 dispatchedGestureIdBits, -1, 0,
5278 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279
5280 dispatchedGestureIdBits.clear();
5281 } else {
5282 BitSet32 upGestureIdBits;
5283 if (finishPreviousGesture) {
5284 upGestureIdBits = dispatchedGestureIdBits;
5285 } else {
5286 upGestureIdBits.value = dispatchedGestureIdBits.value
5287 & ~mPointerGesture.currentGestureIdBits.value;
5288 }
5289 while (!upGestureIdBits.isEmpty()) {
5290 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5291
5292 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005293 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5295 mPointerGesture.lastGestureProperties,
5296 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5297 dispatchedGestureIdBits, id,
5298 0, 0, mPointerGesture.downTime);
5299
5300 dispatchedGestureIdBits.clearBit(id);
5301 }
5302 }
5303 }
5304
5305 // Send motion events for all pointers that moved.
5306 if (moveNeeded) {
5307 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005308 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5309 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 mPointerGesture.currentGestureProperties,
5311 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5312 dispatchedGestureIdBits, -1,
5313 0, 0, mPointerGesture.downTime);
5314 }
5315
5316 // Send motion events for all pointers that went down.
5317 if (down) {
5318 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5319 & ~dispatchedGestureIdBits.value);
5320 while (!downGestureIdBits.isEmpty()) {
5321 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5322 dispatchedGestureIdBits.markBit(id);
5323
5324 if (dispatchedGestureIdBits.count() == 1) {
5325 mPointerGesture.downTime = when;
5326 }
5327
5328 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005329 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 mPointerGesture.currentGestureProperties,
5331 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5332 dispatchedGestureIdBits, id,
5333 0, 0, mPointerGesture.downTime);
5334 }
5335 }
5336
5337 // Send motion events for hover.
5338 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5339 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005340 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5342 mPointerGesture.currentGestureProperties,
5343 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5344 mPointerGesture.currentGestureIdBits, -1,
5345 0, 0, mPointerGesture.downTime);
5346 } else if (dispatchedGestureIdBits.isEmpty()
5347 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5348 // Synthesize a hover move event after all pointers go up to indicate that
5349 // the pointer is hovering again even if the user is not currently touching
5350 // the touch pad. This ensures that a view will receive a fresh hover enter
5351 // event after a tap.
5352 float x, y;
5353 mPointerController->getPosition(&x, &y);
5354
5355 PointerProperties pointerProperties;
5356 pointerProperties.clear();
5357 pointerProperties.id = 0;
5358 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5359
5360 PointerCoords pointerCoords;
5361 pointerCoords.clear();
5362 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5363 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5364
5365 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005366 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5368 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5369 0, 0, mPointerGesture.downTime);
5370 getListener()->notifyMotion(&args);
5371 }
5372
5373 // Update state.
5374 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5375 if (!down) {
5376 mPointerGesture.lastGestureIdBits.clear();
5377 } else {
5378 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5379 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5380 uint32_t id = idBits.clearFirstMarkedBit();
5381 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5382 mPointerGesture.lastGestureProperties[index].copyFrom(
5383 mPointerGesture.currentGestureProperties[index]);
5384 mPointerGesture.lastGestureCoords[index].copyFrom(
5385 mPointerGesture.currentGestureCoords[index]);
5386 mPointerGesture.lastGestureIdToIndex[id] = index;
5387 }
5388 }
5389}
5390
5391void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5392 // Cancel previously dispatches pointers.
5393 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5394 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005395 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005397 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398 AMOTION_EVENT_EDGE_FLAG_NONE,
5399 mPointerGesture.lastGestureProperties,
5400 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5401 mPointerGesture.lastGestureIdBits, -1,
5402 0, 0, mPointerGesture.downTime);
5403 }
5404
5405 // Reset the current pointer gesture.
5406 mPointerGesture.reset();
5407 mPointerVelocityControl.reset();
5408
5409 // Remove any current spots.
5410 if (mPointerController != NULL) {
5411 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5412 mPointerController->clearSpots();
5413 }
5414}
5415
5416bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5417 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5418 *outCancelPreviousGesture = false;
5419 *outFinishPreviousGesture = false;
5420
5421 // Handle TAP timeout.
5422 if (isTimeout) {
5423#if DEBUG_GESTURES
5424 ALOGD("Gestures: Processing timeout");
5425#endif
5426
5427 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5428 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5429 // The tap/drag timeout has not yet expired.
5430 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5431 + mConfig.pointerGestureTapDragInterval);
5432 } else {
5433 // The tap is finished.
5434#if DEBUG_GESTURES
5435 ALOGD("Gestures: TAP finished");
5436#endif
5437 *outFinishPreviousGesture = true;
5438
5439 mPointerGesture.activeGestureId = -1;
5440 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5441 mPointerGesture.currentGestureIdBits.clear();
5442
5443 mPointerVelocityControl.reset();
5444 return true;
5445 }
5446 }
5447
5448 // We did not handle this timeout.
5449 return false;
5450 }
5451
Michael Wright842500e2015-03-13 17:32:02 -07005452 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5453 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454
5455 // Update the velocity tracker.
5456 {
5457 VelocityTracker::Position positions[MAX_POINTERS];
5458 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005459 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005461 const RawPointerData::Pointer& pointer =
5462 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 positions[count].x = pointer.x * mPointerXMovementScale;
5464 positions[count].y = pointer.y * mPointerYMovementScale;
5465 }
5466 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005467 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 }
5469
5470 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5471 // to NEUTRAL, then we should not generate tap event.
5472 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5473 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5474 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5475 mPointerGesture.resetTap();
5476 }
5477
5478 // Pick a new active touch id if needed.
5479 // Choose an arbitrary pointer that just went down, if there is one.
5480 // Otherwise choose an arbitrary remaining pointer.
5481 // This guarantees we always have an active touch id when there is at least one pointer.
5482 // We keep the same active touch id for as long as possible.
5483 bool activeTouchChanged = false;
5484 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5485 int32_t activeTouchId = lastActiveTouchId;
5486 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005487 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 activeTouchChanged = true;
5489 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005490 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 mPointerGesture.firstTouchTime = when;
5492 }
Michael Wright842500e2015-03-13 17:32:02 -07005493 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005495 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005497 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 } else {
5499 activeTouchId = mPointerGesture.activeTouchId = -1;
5500 }
5501 }
5502
5503 // Determine whether we are in quiet time.
5504 bool isQuietTime = false;
5505 if (activeTouchId < 0) {
5506 mPointerGesture.resetQuietTime();
5507 } else {
5508 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5509 if (!isQuietTime) {
5510 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5511 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5512 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5513 && currentFingerCount < 2) {
5514 // Enter quiet time when exiting swipe or freeform state.
5515 // This is to prevent accidentally entering the hover state and flinging the
5516 // pointer when finishing a swipe and there is still one pointer left onscreen.
5517 isQuietTime = true;
5518 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5519 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005520 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521 // Enter quiet time when releasing the button and there are still two or more
5522 // fingers down. This may indicate that one finger was used to press the button
5523 // but it has not gone up yet.
5524 isQuietTime = true;
5525 }
5526 if (isQuietTime) {
5527 mPointerGesture.quietTime = when;
5528 }
5529 }
5530 }
5531
5532 // Switch states based on button and pointer state.
5533 if (isQuietTime) {
5534 // Case 1: Quiet time. (QUIET)
5535#if DEBUG_GESTURES
5536 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5537 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5538#endif
5539 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5540 *outFinishPreviousGesture = true;
5541 }
5542
5543 mPointerGesture.activeGestureId = -1;
5544 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5545 mPointerGesture.currentGestureIdBits.clear();
5546
5547 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005548 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5550 // The pointer follows the active touch point.
5551 // Emit DOWN, MOVE, UP events at the pointer location.
5552 //
5553 // Only the active touch matters; other fingers are ignored. This policy helps
5554 // to handle the case where the user places a second finger on the touch pad
5555 // to apply the necessary force to depress an integrated button below the surface.
5556 // We don't want the second finger to be delivered to applications.
5557 //
5558 // For this to work well, we need to make sure to track the pointer that is really
5559 // active. If the user first puts one finger down to click then adds another
5560 // finger to drag then the active pointer should switch to the finger that is
5561 // being dragged.
5562#if DEBUG_GESTURES
5563 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5564 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5565#endif
5566 // Reset state when just starting.
5567 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5568 *outFinishPreviousGesture = true;
5569 mPointerGesture.activeGestureId = 0;
5570 }
5571
5572 // Switch pointers if needed.
5573 // Find the fastest pointer and follow it.
5574 if (activeTouchId >= 0 && currentFingerCount > 1) {
5575 int32_t bestId = -1;
5576 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005577 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 uint32_t id = idBits.clearFirstMarkedBit();
5579 float vx, vy;
5580 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5581 float speed = hypotf(vx, vy);
5582 if (speed > bestSpeed) {
5583 bestId = id;
5584 bestSpeed = speed;
5585 }
5586 }
5587 }
5588 if (bestId >= 0 && bestId != activeTouchId) {
5589 mPointerGesture.activeTouchId = activeTouchId = bestId;
5590 activeTouchChanged = true;
5591#if DEBUG_GESTURES
5592 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5593 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5594#endif
5595 }
5596 }
5597
Jun Mukaifa1706a2015-12-03 01:14:46 -08005598 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005599 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005601 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005603 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005604 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5605 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606
5607 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5608 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5609
5610 // Move the pointer using a relative motion.
5611 // When using spots, the click will occur at the position of the anchor
5612 // spot and all other spots will move there.
5613 mPointerController->move(deltaX, deltaY);
5614 } else {
5615 mPointerVelocityControl.reset();
5616 }
5617
5618 float x, y;
5619 mPointerController->getPosition(&x, &y);
5620
5621 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5622 mPointerGesture.currentGestureIdBits.clear();
5623 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5624 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5625 mPointerGesture.currentGestureProperties[0].clear();
5626 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5627 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5628 mPointerGesture.currentGestureCoords[0].clear();
5629 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5630 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5631 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5632 } else if (currentFingerCount == 0) {
5633 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5634 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5635 *outFinishPreviousGesture = true;
5636 }
5637
5638 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5639 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5640 bool tapped = false;
5641 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5642 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5643 && lastFingerCount == 1) {
5644 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5645 float x, y;
5646 mPointerController->getPosition(&x, &y);
5647 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5648 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5649#if DEBUG_GESTURES
5650 ALOGD("Gestures: TAP");
5651#endif
5652
5653 mPointerGesture.tapUpTime = when;
5654 getContext()->requestTimeoutAtTime(when
5655 + mConfig.pointerGestureTapDragInterval);
5656
5657 mPointerGesture.activeGestureId = 0;
5658 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5659 mPointerGesture.currentGestureIdBits.clear();
5660 mPointerGesture.currentGestureIdBits.markBit(
5661 mPointerGesture.activeGestureId);
5662 mPointerGesture.currentGestureIdToIndex[
5663 mPointerGesture.activeGestureId] = 0;
5664 mPointerGesture.currentGestureProperties[0].clear();
5665 mPointerGesture.currentGestureProperties[0].id =
5666 mPointerGesture.activeGestureId;
5667 mPointerGesture.currentGestureProperties[0].toolType =
5668 AMOTION_EVENT_TOOL_TYPE_FINGER;
5669 mPointerGesture.currentGestureCoords[0].clear();
5670 mPointerGesture.currentGestureCoords[0].setAxisValue(
5671 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5672 mPointerGesture.currentGestureCoords[0].setAxisValue(
5673 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5674 mPointerGesture.currentGestureCoords[0].setAxisValue(
5675 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5676
5677 tapped = true;
5678 } else {
5679#if DEBUG_GESTURES
5680 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5681 x - mPointerGesture.tapX,
5682 y - mPointerGesture.tapY);
5683#endif
5684 }
5685 } else {
5686#if DEBUG_GESTURES
5687 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5688 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5689 (when - mPointerGesture.tapDownTime) * 0.000001f);
5690 } else {
5691 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5692 }
5693#endif
5694 }
5695 }
5696
5697 mPointerVelocityControl.reset();
5698
5699 if (!tapped) {
5700#if DEBUG_GESTURES
5701 ALOGD("Gestures: NEUTRAL");
5702#endif
5703 mPointerGesture.activeGestureId = -1;
5704 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5705 mPointerGesture.currentGestureIdBits.clear();
5706 }
5707 } else if (currentFingerCount == 1) {
5708 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5709 // The pointer follows the active touch point.
5710 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5711 // When in TAP_DRAG, emit MOVE events at the pointer location.
5712 ALOG_ASSERT(activeTouchId >= 0);
5713
5714 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5715 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5716 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5717 float x, y;
5718 mPointerController->getPosition(&x, &y);
5719 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5720 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5721 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5722 } else {
5723#if DEBUG_GESTURES
5724 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5725 x - mPointerGesture.tapX,
5726 y - mPointerGesture.tapY);
5727#endif
5728 }
5729 } else {
5730#if DEBUG_GESTURES
5731 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5732 (when - mPointerGesture.tapUpTime) * 0.000001f);
5733#endif
5734 }
5735 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5736 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5737 }
5738
Jun Mukaifa1706a2015-12-03 01:14:46 -08005739 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005740 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005742 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005744 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005745 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5746 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747
5748 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5749 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5750
5751 // Move the pointer using a relative motion.
5752 // When using spots, the hover or drag will occur at the position of the anchor spot.
5753 mPointerController->move(deltaX, deltaY);
5754 } else {
5755 mPointerVelocityControl.reset();
5756 }
5757
5758 bool down;
5759 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5760#if DEBUG_GESTURES
5761 ALOGD("Gestures: TAP_DRAG");
5762#endif
5763 down = true;
5764 } else {
5765#if DEBUG_GESTURES
5766 ALOGD("Gestures: HOVER");
5767#endif
5768 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5769 *outFinishPreviousGesture = true;
5770 }
5771 mPointerGesture.activeGestureId = 0;
5772 down = false;
5773 }
5774
5775 float x, y;
5776 mPointerController->getPosition(&x, &y);
5777
5778 mPointerGesture.currentGestureIdBits.clear();
5779 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5780 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5781 mPointerGesture.currentGestureProperties[0].clear();
5782 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5783 mPointerGesture.currentGestureProperties[0].toolType =
5784 AMOTION_EVENT_TOOL_TYPE_FINGER;
5785 mPointerGesture.currentGestureCoords[0].clear();
5786 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5787 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5788 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5789 down ? 1.0f : 0.0f);
5790
5791 if (lastFingerCount == 0 && currentFingerCount != 0) {
5792 mPointerGesture.resetTap();
5793 mPointerGesture.tapDownTime = when;
5794 mPointerGesture.tapX = x;
5795 mPointerGesture.tapY = y;
5796 }
5797 } else {
5798 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5799 // We need to provide feedback for each finger that goes down so we cannot wait
5800 // for the fingers to move before deciding what to do.
5801 //
5802 // The ambiguous case is deciding what to do when there are two fingers down but they
5803 // have not moved enough to determine whether they are part of a drag or part of a
5804 // freeform gesture, or just a press or long-press at the pointer location.
5805 //
5806 // When there are two fingers we start with the PRESS hypothesis and we generate a
5807 // down at the pointer location.
5808 //
5809 // When the two fingers move enough or when additional fingers are added, we make
5810 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5811 ALOG_ASSERT(activeTouchId >= 0);
5812
5813 bool settled = when >= mPointerGesture.firstTouchTime
5814 + mConfig.pointerGestureMultitouchSettleInterval;
5815 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5816 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5817 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5818 *outFinishPreviousGesture = true;
5819 } else if (!settled && currentFingerCount > lastFingerCount) {
5820 // Additional pointers have gone down but not yet settled.
5821 // Reset the gesture.
5822#if DEBUG_GESTURES
5823 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5824 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5825 + mConfig.pointerGestureMultitouchSettleInterval - when)
5826 * 0.000001f);
5827#endif
5828 *outCancelPreviousGesture = true;
5829 } else {
5830 // Continue previous gesture.
5831 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5832 }
5833
5834 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5835 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5836 mPointerGesture.activeGestureId = 0;
5837 mPointerGesture.referenceIdBits.clear();
5838 mPointerVelocityControl.reset();
5839
5840 // Use the centroid and pointer location as the reference points for the gesture.
5841#if DEBUG_GESTURES
5842 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5843 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5844 + mConfig.pointerGestureMultitouchSettleInterval - when)
5845 * 0.000001f);
5846#endif
Michael Wright842500e2015-03-13 17:32:02 -07005847 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848 &mPointerGesture.referenceTouchX,
5849 &mPointerGesture.referenceTouchY);
5850 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5851 &mPointerGesture.referenceGestureY);
5852 }
5853
5854 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005855 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5857 uint32_t id = idBits.clearFirstMarkedBit();
5858 mPointerGesture.referenceDeltas[id].dx = 0;
5859 mPointerGesture.referenceDeltas[id].dy = 0;
5860 }
Michael Wright842500e2015-03-13 17:32:02 -07005861 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862
5863 // Add delta for all fingers and calculate a common movement delta.
5864 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005865 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5866 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5868 bool first = (idBits == commonIdBits);
5869 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005870 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5871 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5873 delta.dx += cpd.x - lpd.x;
5874 delta.dy += cpd.y - lpd.y;
5875
5876 if (first) {
5877 commonDeltaX = delta.dx;
5878 commonDeltaY = delta.dy;
5879 } else {
5880 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5881 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5882 }
5883 }
5884
5885 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5886 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5887 float dist[MAX_POINTER_ID + 1];
5888 int32_t distOverThreshold = 0;
5889 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5890 uint32_t id = idBits.clearFirstMarkedBit();
5891 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5892 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5893 delta.dy * mPointerYZoomScale);
5894 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5895 distOverThreshold += 1;
5896 }
5897 }
5898
5899 // Only transition when at least two pointers have moved further than
5900 // the minimum distance threshold.
5901 if (distOverThreshold >= 2) {
5902 if (currentFingerCount > 2) {
5903 // There are more than two pointers, switch to FREEFORM.
5904#if DEBUG_GESTURES
5905 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5906 currentFingerCount);
5907#endif
5908 *outCancelPreviousGesture = true;
5909 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5910 } else {
5911 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005912 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 uint32_t id1 = idBits.clearFirstMarkedBit();
5914 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005915 const RawPointerData::Pointer& p1 =
5916 mCurrentRawState.rawPointerData.pointerForId(id1);
5917 const RawPointerData::Pointer& p2 =
5918 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5920 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5921 // There are two pointers but they are too far apart for a SWIPE,
5922 // switch to FREEFORM.
5923#if DEBUG_GESTURES
5924 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5925 mutualDistance, mPointerGestureMaxSwipeWidth);
5926#endif
5927 *outCancelPreviousGesture = true;
5928 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5929 } else {
5930 // There are two pointers. Wait for both pointers to start moving
5931 // before deciding whether this is a SWIPE or FREEFORM gesture.
5932 float dist1 = dist[id1];
5933 float dist2 = dist[id2];
5934 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5935 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5936 // Calculate the dot product of the displacement vectors.
5937 // When the vectors are oriented in approximately the same direction,
5938 // the angle betweeen them is near zero and the cosine of the angle
5939 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5940 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5941 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5942 float dx1 = delta1.dx * mPointerXZoomScale;
5943 float dy1 = delta1.dy * mPointerYZoomScale;
5944 float dx2 = delta2.dx * mPointerXZoomScale;
5945 float dy2 = delta2.dy * mPointerYZoomScale;
5946 float dot = dx1 * dx2 + dy1 * dy2;
5947 float cosine = dot / (dist1 * dist2); // denominator always > 0
5948 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5949 // Pointers are moving in the same direction. Switch to SWIPE.
5950#if DEBUG_GESTURES
5951 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5952 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5953 "cosine %0.3f >= %0.3f",
5954 dist1, mConfig.pointerGestureMultitouchMinDistance,
5955 dist2, mConfig.pointerGestureMultitouchMinDistance,
5956 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5957#endif
5958 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5959 } else {
5960 // Pointers are moving in different directions. Switch to FREEFORM.
5961#if DEBUG_GESTURES
5962 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5963 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5964 "cosine %0.3f < %0.3f",
5965 dist1, mConfig.pointerGestureMultitouchMinDistance,
5966 dist2, mConfig.pointerGestureMultitouchMinDistance,
5967 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5968#endif
5969 *outCancelPreviousGesture = true;
5970 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5971 }
5972 }
5973 }
5974 }
5975 }
5976 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5977 // Switch from SWIPE to FREEFORM if additional pointers go down.
5978 // Cancel previous gesture.
5979 if (currentFingerCount > 2) {
5980#if DEBUG_GESTURES
5981 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5982 currentFingerCount);
5983#endif
5984 *outCancelPreviousGesture = true;
5985 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5986 }
5987 }
5988
5989 // Move the reference points based on the overall group motion of the fingers
5990 // except in PRESS mode while waiting for a transition to occur.
5991 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5992 && (commonDeltaX || commonDeltaY)) {
5993 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5994 uint32_t id = idBits.clearFirstMarkedBit();
5995 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5996 delta.dx = 0;
5997 delta.dy = 0;
5998 }
5999
6000 mPointerGesture.referenceTouchX += commonDeltaX;
6001 mPointerGesture.referenceTouchY += commonDeltaY;
6002
6003 commonDeltaX *= mPointerXMovementScale;
6004 commonDeltaY *= mPointerYMovementScale;
6005
6006 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6007 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6008
6009 mPointerGesture.referenceGestureX += commonDeltaX;
6010 mPointerGesture.referenceGestureY += commonDeltaY;
6011 }
6012
6013 // Report gestures.
6014 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6015 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6016 // PRESS or SWIPE mode.
6017#if DEBUG_GESTURES
6018 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6019 "activeGestureId=%d, currentTouchPointerCount=%d",
6020 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6021#endif
6022 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6023
6024 mPointerGesture.currentGestureIdBits.clear();
6025 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6026 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6027 mPointerGesture.currentGestureProperties[0].clear();
6028 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6029 mPointerGesture.currentGestureProperties[0].toolType =
6030 AMOTION_EVENT_TOOL_TYPE_FINGER;
6031 mPointerGesture.currentGestureCoords[0].clear();
6032 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6033 mPointerGesture.referenceGestureX);
6034 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6035 mPointerGesture.referenceGestureY);
6036 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6037 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6038 // FREEFORM mode.
6039#if DEBUG_GESTURES
6040 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6041 "activeGestureId=%d, currentTouchPointerCount=%d",
6042 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6043#endif
6044 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6045
6046 mPointerGesture.currentGestureIdBits.clear();
6047
6048 BitSet32 mappedTouchIdBits;
6049 BitSet32 usedGestureIdBits;
6050 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6051 // Initially, assign the active gesture id to the active touch point
6052 // if there is one. No other touch id bits are mapped yet.
6053 if (!*outCancelPreviousGesture) {
6054 mappedTouchIdBits.markBit(activeTouchId);
6055 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6056 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6057 mPointerGesture.activeGestureId;
6058 } else {
6059 mPointerGesture.activeGestureId = -1;
6060 }
6061 } else {
6062 // Otherwise, assume we mapped all touches from the previous frame.
6063 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006064 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6065 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6067
6068 // Check whether we need to choose a new active gesture id because the
6069 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006070 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6071 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072 !upTouchIdBits.isEmpty(); ) {
6073 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6074 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6075 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6076 mPointerGesture.activeGestureId = -1;
6077 break;
6078 }
6079 }
6080 }
6081
6082#if DEBUG_GESTURES
6083 ALOGD("Gestures: FREEFORM follow up "
6084 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6085 "activeGestureId=%d",
6086 mappedTouchIdBits.value, usedGestureIdBits.value,
6087 mPointerGesture.activeGestureId);
6088#endif
6089
Michael Wright842500e2015-03-13 17:32:02 -07006090 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 for (uint32_t i = 0; i < currentFingerCount; i++) {
6092 uint32_t touchId = idBits.clearFirstMarkedBit();
6093 uint32_t gestureId;
6094 if (!mappedTouchIdBits.hasBit(touchId)) {
6095 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6096 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6097#if DEBUG_GESTURES
6098 ALOGD("Gestures: FREEFORM "
6099 "new mapping for touch id %d -> gesture id %d",
6100 touchId, gestureId);
6101#endif
6102 } else {
6103 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6104#if DEBUG_GESTURES
6105 ALOGD("Gestures: FREEFORM "
6106 "existing mapping for touch id %d -> gesture id %d",
6107 touchId, gestureId);
6108#endif
6109 }
6110 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6111 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6112
6113 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006114 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006115 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6116 * mPointerXZoomScale;
6117 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6118 * mPointerYZoomScale;
6119 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6120
6121 mPointerGesture.currentGestureProperties[i].clear();
6122 mPointerGesture.currentGestureProperties[i].id = gestureId;
6123 mPointerGesture.currentGestureProperties[i].toolType =
6124 AMOTION_EVENT_TOOL_TYPE_FINGER;
6125 mPointerGesture.currentGestureCoords[i].clear();
6126 mPointerGesture.currentGestureCoords[i].setAxisValue(
6127 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6128 mPointerGesture.currentGestureCoords[i].setAxisValue(
6129 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6130 mPointerGesture.currentGestureCoords[i].setAxisValue(
6131 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6132 }
6133
6134 if (mPointerGesture.activeGestureId < 0) {
6135 mPointerGesture.activeGestureId =
6136 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6137#if DEBUG_GESTURES
6138 ALOGD("Gestures: FREEFORM new "
6139 "activeGestureId=%d", mPointerGesture.activeGestureId);
6140#endif
6141 }
6142 }
6143 }
6144
Michael Wright842500e2015-03-13 17:32:02 -07006145 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146
6147#if DEBUG_GESTURES
6148 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6149 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6150 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6151 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6152 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6153 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6154 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6155 uint32_t id = idBits.clearFirstMarkedBit();
6156 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6157 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6158 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6159 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6160 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6161 id, index, properties.toolType,
6162 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6163 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6164 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6165 }
6166 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6167 uint32_t id = idBits.clearFirstMarkedBit();
6168 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6169 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6170 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6171 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6172 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6173 id, index, properties.toolType,
6174 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6175 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6176 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6177 }
6178#endif
6179 return true;
6180}
6181
6182void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6183 mPointerSimple.currentCoords.clear();
6184 mPointerSimple.currentProperties.clear();
6185
6186 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006187 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6188 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6189 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6190 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6191 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006192 mPointerController->setPosition(x, y);
6193
Michael Wright842500e2015-03-13 17:32:02 -07006194 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006195 down = !hovering;
6196
6197 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006198 mPointerSimple.currentCoords.copyFrom(
6199 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6201 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6202 mPointerSimple.currentProperties.id = 0;
6203 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006204 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205 } else {
6206 down = false;
6207 hovering = false;
6208 }
6209
6210 dispatchPointerSimple(when, policyFlags, down, hovering);
6211}
6212
6213void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6214 abortPointerSimple(when, policyFlags);
6215}
6216
6217void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6218 mPointerSimple.currentCoords.clear();
6219 mPointerSimple.currentProperties.clear();
6220
6221 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006222 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6223 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6224 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006225 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006226 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6227 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006228 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006229 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006231 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006232 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 * mPointerYMovementScale;
6234
6235 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6236 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6237
6238 mPointerController->move(deltaX, deltaY);
6239 } else {
6240 mPointerVelocityControl.reset();
6241 }
6242
Michael Wright842500e2015-03-13 17:32:02 -07006243 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244 hovering = !down;
6245
6246 float x, y;
6247 mPointerController->getPosition(&x, &y);
6248 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006249 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6251 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6252 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6253 hovering ? 0.0f : 1.0f);
6254 mPointerSimple.currentProperties.id = 0;
6255 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006256 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 } else {
6258 mPointerVelocityControl.reset();
6259
6260 down = false;
6261 hovering = false;
6262 }
6263
6264 dispatchPointerSimple(when, policyFlags, down, hovering);
6265}
6266
6267void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6268 abortPointerSimple(when, policyFlags);
6269
6270 mPointerVelocityControl.reset();
6271}
6272
6273void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6274 bool down, bool hovering) {
6275 int32_t metaState = getContext()->getGlobalMetaState();
6276
6277 if (mPointerController != NULL) {
6278 if (down || hovering) {
6279 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6280 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006281 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6283 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6284 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6285 }
6286 }
6287
6288 if (mPointerSimple.down && !down) {
6289 mPointerSimple.down = false;
6290
6291 // Send up.
6292 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006293 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006294 mViewport.displayId,
6295 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6296 mOrientedXPrecision, mOrientedYPrecision,
6297 mPointerSimple.downTime);
6298 getListener()->notifyMotion(&args);
6299 }
6300
6301 if (mPointerSimple.hovering && !hovering) {
6302 mPointerSimple.hovering = false;
6303
6304 // Send hover exit.
6305 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006306 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006307 mViewport.displayId,
6308 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6309 mOrientedXPrecision, mOrientedYPrecision,
6310 mPointerSimple.downTime);
6311 getListener()->notifyMotion(&args);
6312 }
6313
6314 if (down) {
6315 if (!mPointerSimple.down) {
6316 mPointerSimple.down = true;
6317 mPointerSimple.downTime = when;
6318
6319 // Send down.
6320 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006321 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322 mViewport.displayId,
6323 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6324 mOrientedXPrecision, mOrientedYPrecision,
6325 mPointerSimple.downTime);
6326 getListener()->notifyMotion(&args);
6327 }
6328
6329 // Send move.
6330 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006331 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 mViewport.displayId,
6333 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6334 mOrientedXPrecision, mOrientedYPrecision,
6335 mPointerSimple.downTime);
6336 getListener()->notifyMotion(&args);
6337 }
6338
6339 if (hovering) {
6340 if (!mPointerSimple.hovering) {
6341 mPointerSimple.hovering = true;
6342
6343 // Send hover enter.
6344 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006345 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006346 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006347 mViewport.displayId,
6348 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6349 mOrientedXPrecision, mOrientedYPrecision,
6350 mPointerSimple.downTime);
6351 getListener()->notifyMotion(&args);
6352 }
6353
6354 // Send hover move.
6355 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006356 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006357 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358 mViewport.displayId,
6359 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6360 mOrientedXPrecision, mOrientedYPrecision,
6361 mPointerSimple.downTime);
6362 getListener()->notifyMotion(&args);
6363 }
6364
Michael Wright842500e2015-03-13 17:32:02 -07006365 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6366 float vscroll = mCurrentRawState.rawVScroll;
6367 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 mWheelYVelocityControl.move(when, NULL, &vscroll);
6369 mWheelXVelocityControl.move(when, &hscroll, NULL);
6370
6371 // Send scroll.
6372 PointerCoords pointerCoords;
6373 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6374 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6375 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6376
6377 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006378 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379 mViewport.displayId,
6380 1, &mPointerSimple.currentProperties, &pointerCoords,
6381 mOrientedXPrecision, mOrientedYPrecision,
6382 mPointerSimple.downTime);
6383 getListener()->notifyMotion(&args);
6384 }
6385
6386 // Save state.
6387 if (down || hovering) {
6388 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6389 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6390 } else {
6391 mPointerSimple.reset();
6392 }
6393}
6394
6395void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6396 mPointerSimple.currentCoords.clear();
6397 mPointerSimple.currentProperties.clear();
6398
6399 dispatchPointerSimple(when, policyFlags, false, false);
6400}
6401
6402void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006403 int32_t action, int32_t actionButton, int32_t flags,
6404 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006406 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6407 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408 PointerCoords pointerCoords[MAX_POINTERS];
6409 PointerProperties pointerProperties[MAX_POINTERS];
6410 uint32_t pointerCount = 0;
6411 while (!idBits.isEmpty()) {
6412 uint32_t id = idBits.clearFirstMarkedBit();
6413 uint32_t index = idToIndex[id];
6414 pointerProperties[pointerCount].copyFrom(properties[index]);
6415 pointerCoords[pointerCount].copyFrom(coords[index]);
6416
6417 if (changedId >= 0 && id == uint32_t(changedId)) {
6418 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6419 }
6420
6421 pointerCount += 1;
6422 }
6423
6424 ALOG_ASSERT(pointerCount != 0);
6425
6426 if (changedId >= 0 && pointerCount == 1) {
6427 // Replace initial down and final up action.
6428 // We can compare the action without masking off the changed pointer index
6429 // because we know the index is 0.
6430 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6431 action = AMOTION_EVENT_ACTION_DOWN;
6432 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6433 action = AMOTION_EVENT_ACTION_UP;
6434 } else {
6435 // Can't happen.
6436 ALOG_ASSERT(false);
6437 }
6438 }
6439
6440 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006441 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6443 xPrecision, yPrecision, downTime);
6444 getListener()->notifyMotion(&args);
6445}
6446
6447bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6448 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6449 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6450 BitSet32 idBits) const {
6451 bool changed = false;
6452 while (!idBits.isEmpty()) {
6453 uint32_t id = idBits.clearFirstMarkedBit();
6454 uint32_t inIndex = inIdToIndex[id];
6455 uint32_t outIndex = outIdToIndex[id];
6456
6457 const PointerProperties& curInProperties = inProperties[inIndex];
6458 const PointerCoords& curInCoords = inCoords[inIndex];
6459 PointerProperties& curOutProperties = outProperties[outIndex];
6460 PointerCoords& curOutCoords = outCoords[outIndex];
6461
6462 if (curInProperties != curOutProperties) {
6463 curOutProperties.copyFrom(curInProperties);
6464 changed = true;
6465 }
6466
6467 if (curInCoords != curOutCoords) {
6468 curOutCoords.copyFrom(curInCoords);
6469 changed = true;
6470 }
6471 }
6472 return changed;
6473}
6474
6475void TouchInputMapper::fadePointer() {
6476 if (mPointerController != NULL) {
6477 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6478 }
6479}
6480
Jeff Brownc9aa6282015-02-11 19:03:28 -08006481void TouchInputMapper::cancelTouch(nsecs_t when) {
6482 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006483 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006484}
6485
Michael Wrightd02c5b62014-02-10 15:10:22 -08006486bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6487 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6488 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6489}
6490
6491const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6492 int32_t x, int32_t y) {
6493 size_t numVirtualKeys = mVirtualKeys.size();
6494 for (size_t i = 0; i < numVirtualKeys; i++) {
6495 const VirtualKey& virtualKey = mVirtualKeys[i];
6496
6497#if DEBUG_VIRTUAL_KEYS
6498 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6499 "left=%d, top=%d, right=%d, bottom=%d",
6500 x, y,
6501 virtualKey.keyCode, virtualKey.scanCode,
6502 virtualKey.hitLeft, virtualKey.hitTop,
6503 virtualKey.hitRight, virtualKey.hitBottom);
6504#endif
6505
6506 if (virtualKey.isHit(x, y)) {
6507 return & virtualKey;
6508 }
6509 }
6510
6511 return NULL;
6512}
6513
Michael Wright842500e2015-03-13 17:32:02 -07006514void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6515 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6516 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517
Michael Wright842500e2015-03-13 17:32:02 -07006518 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006519
6520 if (currentPointerCount == 0) {
6521 // No pointers to assign.
6522 return;
6523 }
6524
6525 if (lastPointerCount == 0) {
6526 // All pointers are new.
6527 for (uint32_t i = 0; i < currentPointerCount; i++) {
6528 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006529 current->rawPointerData.pointers[i].id = id;
6530 current->rawPointerData.idToIndex[id] = i;
6531 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006532 }
6533 return;
6534 }
6535
6536 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006537 && current->rawPointerData.pointers[0].toolType
6538 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006539 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006540 uint32_t id = last->rawPointerData.pointers[0].id;
6541 current->rawPointerData.pointers[0].id = id;
6542 current->rawPointerData.idToIndex[id] = 0;
6543 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544 return;
6545 }
6546
6547 // General case.
6548 // We build a heap of squared euclidean distances between current and last pointers
6549 // associated with the current and last pointer indices. Then, we find the best
6550 // match (by distance) for each current pointer.
6551 // The pointers must have the same tool type but it is possible for them to
6552 // transition from hovering to touching or vice-versa while retaining the same id.
6553 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6554
6555 uint32_t heapSize = 0;
6556 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6557 currentPointerIndex++) {
6558 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6559 lastPointerIndex++) {
6560 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006561 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006563 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 if (currentPointer.toolType == lastPointer.toolType) {
6565 int64_t deltaX = currentPointer.x - lastPointer.x;
6566 int64_t deltaY = currentPointer.y - lastPointer.y;
6567
6568 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6569
6570 // Insert new element into the heap (sift up).
6571 heap[heapSize].currentPointerIndex = currentPointerIndex;
6572 heap[heapSize].lastPointerIndex = lastPointerIndex;
6573 heap[heapSize].distance = distance;
6574 heapSize += 1;
6575 }
6576 }
6577 }
6578
6579 // Heapify
6580 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6581 startIndex -= 1;
6582 for (uint32_t parentIndex = startIndex; ;) {
6583 uint32_t childIndex = parentIndex * 2 + 1;
6584 if (childIndex >= heapSize) {
6585 break;
6586 }
6587
6588 if (childIndex + 1 < heapSize
6589 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6590 childIndex += 1;
6591 }
6592
6593 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6594 break;
6595 }
6596
6597 swap(heap[parentIndex], heap[childIndex]);
6598 parentIndex = childIndex;
6599 }
6600 }
6601
6602#if DEBUG_POINTER_ASSIGNMENT
6603 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6604 for (size_t i = 0; i < heapSize; i++) {
6605 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6606 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6607 heap[i].distance);
6608 }
6609#endif
6610
6611 // Pull matches out by increasing order of distance.
6612 // To avoid reassigning pointers that have already been matched, the loop keeps track
6613 // of which last and current pointers have been matched using the matchedXXXBits variables.
6614 // It also tracks the used pointer id bits.
6615 BitSet32 matchedLastBits(0);
6616 BitSet32 matchedCurrentBits(0);
6617 BitSet32 usedIdBits(0);
6618 bool first = true;
6619 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6620 while (heapSize > 0) {
6621 if (first) {
6622 // The first time through the loop, we just consume the root element of
6623 // the heap (the one with smallest distance).
6624 first = false;
6625 } else {
6626 // Previous iterations consumed the root element of the heap.
6627 // Pop root element off of the heap (sift down).
6628 heap[0] = heap[heapSize];
6629 for (uint32_t parentIndex = 0; ;) {
6630 uint32_t childIndex = parentIndex * 2 + 1;
6631 if (childIndex >= heapSize) {
6632 break;
6633 }
6634
6635 if (childIndex + 1 < heapSize
6636 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6637 childIndex += 1;
6638 }
6639
6640 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6641 break;
6642 }
6643
6644 swap(heap[parentIndex], heap[childIndex]);
6645 parentIndex = childIndex;
6646 }
6647
6648#if DEBUG_POINTER_ASSIGNMENT
6649 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6650 for (size_t i = 0; i < heapSize; i++) {
6651 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6652 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6653 heap[i].distance);
6654 }
6655#endif
6656 }
6657
6658 heapSize -= 1;
6659
6660 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6661 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6662
6663 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6664 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6665
6666 matchedCurrentBits.markBit(currentPointerIndex);
6667 matchedLastBits.markBit(lastPointerIndex);
6668
Michael Wright842500e2015-03-13 17:32:02 -07006669 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6670 current->rawPointerData.pointers[currentPointerIndex].id = id;
6671 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6672 current->rawPointerData.markIdBit(id,
6673 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006674 usedIdBits.markBit(id);
6675
6676#if DEBUG_POINTER_ASSIGNMENT
6677 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6678 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6679#endif
6680 break;
6681 }
6682 }
6683
6684 // Assign fresh ids to pointers that were not matched in the process.
6685 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6686 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6687 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6688
Michael Wright842500e2015-03-13 17:32:02 -07006689 current->rawPointerData.pointers[currentPointerIndex].id = id;
6690 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6691 current->rawPointerData.markIdBit(id,
6692 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693
6694#if DEBUG_POINTER_ASSIGNMENT
6695 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6696 currentPointerIndex, id);
6697#endif
6698 }
6699}
6700
6701int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6702 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6703 return AKEY_STATE_VIRTUAL;
6704 }
6705
6706 size_t numVirtualKeys = mVirtualKeys.size();
6707 for (size_t i = 0; i < numVirtualKeys; i++) {
6708 const VirtualKey& virtualKey = mVirtualKeys[i];
6709 if (virtualKey.keyCode == keyCode) {
6710 return AKEY_STATE_UP;
6711 }
6712 }
6713
6714 return AKEY_STATE_UNKNOWN;
6715}
6716
6717int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6718 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6719 return AKEY_STATE_VIRTUAL;
6720 }
6721
6722 size_t numVirtualKeys = mVirtualKeys.size();
6723 for (size_t i = 0; i < numVirtualKeys; i++) {
6724 const VirtualKey& virtualKey = mVirtualKeys[i];
6725 if (virtualKey.scanCode == scanCode) {
6726 return AKEY_STATE_UP;
6727 }
6728 }
6729
6730 return AKEY_STATE_UNKNOWN;
6731}
6732
6733bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6734 const int32_t* keyCodes, uint8_t* outFlags) {
6735 size_t numVirtualKeys = mVirtualKeys.size();
6736 for (size_t i = 0; i < numVirtualKeys; i++) {
6737 const VirtualKey& virtualKey = mVirtualKeys[i];
6738
6739 for (size_t i = 0; i < numCodes; i++) {
6740 if (virtualKey.keyCode == keyCodes[i]) {
6741 outFlags[i] = 1;
6742 }
6743 }
6744 }
6745
6746 return true;
6747}
6748
6749
6750// --- SingleTouchInputMapper ---
6751
6752SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6753 TouchInputMapper(device) {
6754}
6755
6756SingleTouchInputMapper::~SingleTouchInputMapper() {
6757}
6758
6759void SingleTouchInputMapper::reset(nsecs_t when) {
6760 mSingleTouchMotionAccumulator.reset(getDevice());
6761
6762 TouchInputMapper::reset(when);
6763}
6764
6765void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6766 TouchInputMapper::process(rawEvent);
6767
6768 mSingleTouchMotionAccumulator.process(rawEvent);
6769}
6770
Michael Wright842500e2015-03-13 17:32:02 -07006771void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006772 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006773 outState->rawPointerData.pointerCount = 1;
6774 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006775
6776 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6777 && (mTouchButtonAccumulator.isHovering()
6778 || (mRawPointerAxes.pressure.valid
6779 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006780 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006781
Michael Wright842500e2015-03-13 17:32:02 -07006782 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006783 outPointer.id = 0;
6784 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6785 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6786 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6787 outPointer.touchMajor = 0;
6788 outPointer.touchMinor = 0;
6789 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6790 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6791 outPointer.orientation = 0;
6792 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6793 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6794 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6795 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6796 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6797 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6798 }
6799 outPointer.isHovering = isHovering;
6800 }
6801}
6802
6803void SingleTouchInputMapper::configureRawPointerAxes() {
6804 TouchInputMapper::configureRawPointerAxes();
6805
6806 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6807 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6808 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6809 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6810 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6811 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6812 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6813}
6814
6815bool SingleTouchInputMapper::hasStylus() const {
6816 return mTouchButtonAccumulator.hasStylus();
6817}
6818
6819
6820// --- MultiTouchInputMapper ---
6821
6822MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6823 TouchInputMapper(device) {
6824}
6825
6826MultiTouchInputMapper::~MultiTouchInputMapper() {
6827}
6828
6829void MultiTouchInputMapper::reset(nsecs_t when) {
6830 mMultiTouchMotionAccumulator.reset(getDevice());
6831
6832 mPointerIdBits.clear();
6833
6834 TouchInputMapper::reset(when);
6835}
6836
6837void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6838 TouchInputMapper::process(rawEvent);
6839
6840 mMultiTouchMotionAccumulator.process(rawEvent);
6841}
6842
Michael Wright842500e2015-03-13 17:32:02 -07006843void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006844 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6845 size_t outCount = 0;
6846 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006847 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006848
6849 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6850 const MultiTouchMotionAccumulator::Slot* inSlot =
6851 mMultiTouchMotionAccumulator.getSlot(inIndex);
6852 if (!inSlot->isInUse()) {
6853 continue;
6854 }
6855
6856 if (outCount >= MAX_POINTERS) {
6857#if DEBUG_POINTERS
6858 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6859 "ignoring the rest.",
6860 getDeviceName().string(), MAX_POINTERS);
6861#endif
6862 break; // too many fingers!
6863 }
6864
Michael Wright842500e2015-03-13 17:32:02 -07006865 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006866 outPointer.x = inSlot->getX();
6867 outPointer.y = inSlot->getY();
6868 outPointer.pressure = inSlot->getPressure();
6869 outPointer.touchMajor = inSlot->getTouchMajor();
6870 outPointer.touchMinor = inSlot->getTouchMinor();
6871 outPointer.toolMajor = inSlot->getToolMajor();
6872 outPointer.toolMinor = inSlot->getToolMinor();
6873 outPointer.orientation = inSlot->getOrientation();
6874 outPointer.distance = inSlot->getDistance();
6875 outPointer.tiltX = 0;
6876 outPointer.tiltY = 0;
6877
6878 outPointer.toolType = inSlot->getToolType();
6879 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6880 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6881 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6882 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6883 }
6884 }
6885
6886 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6887 && (mTouchButtonAccumulator.isHovering()
6888 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6889 outPointer.isHovering = isHovering;
6890
6891 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006892 if (mHavePointerIds) {
6893 int32_t trackingId = inSlot->getTrackingId();
6894 int32_t id = -1;
6895 if (trackingId >= 0) {
6896 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6897 uint32_t n = idBits.clearFirstMarkedBit();
6898 if (mPointerTrackingIdMap[n] == trackingId) {
6899 id = n;
6900 }
6901 }
6902
6903 if (id < 0 && !mPointerIdBits.isFull()) {
6904 id = mPointerIdBits.markFirstUnmarkedBit();
6905 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006906 }
Michael Wright842500e2015-03-13 17:32:02 -07006907 }
gaoshang1a632de2016-08-24 10:23:50 +08006908 if (id < 0) {
6909 mHavePointerIds = false;
6910 outState->rawPointerData.clearIdBits();
6911 newPointerIdBits.clear();
6912 } else {
6913 outPointer.id = id;
6914 outState->rawPointerData.idToIndex[id] = outCount;
6915 outState->rawPointerData.markIdBit(id, isHovering);
6916 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006917 }
Michael Wright842500e2015-03-13 17:32:02 -07006918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006919 outCount += 1;
6920 }
6921
Michael Wright842500e2015-03-13 17:32:02 -07006922 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006923 mPointerIdBits = newPointerIdBits;
6924
6925 mMultiTouchMotionAccumulator.finishSync();
6926}
6927
6928void MultiTouchInputMapper::configureRawPointerAxes() {
6929 TouchInputMapper::configureRawPointerAxes();
6930
6931 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6932 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6933 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6934 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6935 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6936 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6937 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6938 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6939 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6940 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6941 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6942
6943 if (mRawPointerAxes.trackingId.valid
6944 && mRawPointerAxes.slot.valid
6945 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6946 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6947 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006948 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6949 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006950 getDeviceName().string(), slotCount, MAX_SLOTS);
6951 slotCount = MAX_SLOTS;
6952 }
6953 mMultiTouchMotionAccumulator.configure(getDevice(),
6954 slotCount, true /*usingSlotsProtocol*/);
6955 } else {
6956 mMultiTouchMotionAccumulator.configure(getDevice(),
6957 MAX_POINTERS, false /*usingSlotsProtocol*/);
6958 }
6959}
6960
6961bool MultiTouchInputMapper::hasStylus() const {
6962 return mMultiTouchMotionAccumulator.hasStylus()
6963 || mTouchButtonAccumulator.hasStylus();
6964}
6965
Michael Wright842500e2015-03-13 17:32:02 -07006966// --- ExternalStylusInputMapper
6967
6968ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6969 InputMapper(device) {
6970
6971}
6972
6973uint32_t ExternalStylusInputMapper::getSources() {
6974 return AINPUT_SOURCE_STYLUS;
6975}
6976
6977void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6978 InputMapper::populateDeviceInfo(info);
6979 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6980 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6981}
6982
6983void ExternalStylusInputMapper::dump(String8& dump) {
6984 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6985 dump.append(INDENT3 "Raw Stylus Axes:\n");
6986 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6987 dump.append(INDENT3 "Stylus State:\n");
6988 dumpStylusState(dump, mStylusState);
6989}
6990
6991void ExternalStylusInputMapper::configure(nsecs_t when,
6992 const InputReaderConfiguration* config, uint32_t changes) {
6993 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6994 mTouchButtonAccumulator.configure(getDevice());
6995}
6996
6997void ExternalStylusInputMapper::reset(nsecs_t when) {
6998 InputDevice* device = getDevice();
6999 mSingleTouchMotionAccumulator.reset(device);
7000 mTouchButtonAccumulator.reset(device);
7001 InputMapper::reset(when);
7002}
7003
7004void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7005 mSingleTouchMotionAccumulator.process(rawEvent);
7006 mTouchButtonAccumulator.process(rawEvent);
7007
7008 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7009 sync(rawEvent->when);
7010 }
7011}
7012
7013void ExternalStylusInputMapper::sync(nsecs_t when) {
7014 mStylusState.clear();
7015
7016 mStylusState.when = when;
7017
Michael Wright45ccacf2015-04-21 19:01:58 +01007018 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7019 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7020 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7021 }
7022
Michael Wright842500e2015-03-13 17:32:02 -07007023 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7024 if (mRawPressureAxis.valid) {
7025 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7026 } else if (mTouchButtonAccumulator.isToolActive()) {
7027 mStylusState.pressure = 1.0f;
7028 } else {
7029 mStylusState.pressure = 0.0f;
7030 }
7031
7032 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007033
7034 mContext->dispatchExternalStylusState(mStylusState);
7035}
7036
Michael Wrightd02c5b62014-02-10 15:10:22 -08007037
7038// --- JoystickInputMapper ---
7039
7040JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7041 InputMapper(device) {
7042}
7043
7044JoystickInputMapper::~JoystickInputMapper() {
7045}
7046
7047uint32_t JoystickInputMapper::getSources() {
7048 return AINPUT_SOURCE_JOYSTICK;
7049}
7050
7051void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7052 InputMapper::populateDeviceInfo(info);
7053
7054 for (size_t i = 0; i < mAxes.size(); i++) {
7055 const Axis& axis = mAxes.valueAt(i);
7056 addMotionRange(axis.axisInfo.axis, axis, info);
7057
7058 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7059 addMotionRange(axis.axisInfo.highAxis, axis, info);
7060
7061 }
7062 }
7063}
7064
7065void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7066 InputDeviceInfo* info) {
7067 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7068 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7069 /* In order to ease the transition for developers from using the old axes
7070 * to the newer, more semantically correct axes, we'll continue to register
7071 * the old axes as duplicates of their corresponding new ones. */
7072 int32_t compatAxis = getCompatAxis(axisId);
7073 if (compatAxis >= 0) {
7074 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7075 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7076 }
7077}
7078
7079/* A mapping from axes the joystick actually has to the axes that should be
7080 * artificially created for compatibility purposes.
7081 * Returns -1 if no compatibility axis is needed. */
7082int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7083 switch(axis) {
7084 case AMOTION_EVENT_AXIS_LTRIGGER:
7085 return AMOTION_EVENT_AXIS_BRAKE;
7086 case AMOTION_EVENT_AXIS_RTRIGGER:
7087 return AMOTION_EVENT_AXIS_GAS;
7088 }
7089 return -1;
7090}
7091
7092void JoystickInputMapper::dump(String8& dump) {
7093 dump.append(INDENT2 "Joystick Input Mapper:\n");
7094
7095 dump.append(INDENT3 "Axes:\n");
7096 size_t numAxes = mAxes.size();
7097 for (size_t i = 0; i < numAxes; i++) {
7098 const Axis& axis = mAxes.valueAt(i);
7099 const char* label = getAxisLabel(axis.axisInfo.axis);
7100 if (label) {
7101 dump.appendFormat(INDENT4 "%s", label);
7102 } else {
7103 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7104 }
7105 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7106 label = getAxisLabel(axis.axisInfo.highAxis);
7107 if (label) {
7108 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7109 } else {
7110 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7111 axis.axisInfo.splitValue);
7112 }
7113 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7114 dump.append(" (invert)");
7115 }
7116
7117 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7118 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7119 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7120 "highScale=%0.5f, highOffset=%0.5f\n",
7121 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7122 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7123 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7124 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7125 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7126 }
7127}
7128
7129void JoystickInputMapper::configure(nsecs_t when,
7130 const InputReaderConfiguration* config, uint32_t changes) {
7131 InputMapper::configure(when, config, changes);
7132
7133 if (!changes) { // first time only
7134 // Collect all axes.
7135 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7136 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7137 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7138 continue; // axis must be claimed by a different device
7139 }
7140
7141 RawAbsoluteAxisInfo rawAxisInfo;
7142 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7143 if (rawAxisInfo.valid) {
7144 // Map axis.
7145 AxisInfo axisInfo;
7146 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7147 if (!explicitlyMapped) {
7148 // Axis is not explicitly mapped, will choose a generic axis later.
7149 axisInfo.mode = AxisInfo::MODE_NORMAL;
7150 axisInfo.axis = -1;
7151 }
7152
7153 // Apply flat override.
7154 int32_t rawFlat = axisInfo.flatOverride < 0
7155 ? rawAxisInfo.flat : axisInfo.flatOverride;
7156
7157 // Calculate scaling factors and limits.
7158 Axis axis;
7159 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7160 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7161 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7162 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7163 scale, 0.0f, highScale, 0.0f,
7164 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7165 rawAxisInfo.resolution * scale);
7166 } else if (isCenteredAxis(axisInfo.axis)) {
7167 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7168 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7169 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7170 scale, offset, scale, offset,
7171 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7172 rawAxisInfo.resolution * scale);
7173 } else {
7174 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7175 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7176 scale, 0.0f, scale, 0.0f,
7177 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7178 rawAxisInfo.resolution * scale);
7179 }
7180
7181 // To eliminate noise while the joystick is at rest, filter out small variations
7182 // in axis values up front.
7183 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7184
7185 mAxes.add(abs, axis);
7186 }
7187 }
7188
7189 // If there are too many axes, start dropping them.
7190 // Prefer to keep explicitly mapped axes.
7191 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007192 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007193 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7194 pruneAxes(true);
7195 pruneAxes(false);
7196 }
7197
7198 // Assign generic axis ids to remaining axes.
7199 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7200 size_t numAxes = mAxes.size();
7201 for (size_t i = 0; i < numAxes; i++) {
7202 Axis& axis = mAxes.editValueAt(i);
7203 if (axis.axisInfo.axis < 0) {
7204 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7205 && haveAxis(nextGenericAxisId)) {
7206 nextGenericAxisId += 1;
7207 }
7208
7209 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7210 axis.axisInfo.axis = nextGenericAxisId;
7211 nextGenericAxisId += 1;
7212 } else {
7213 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7214 "have already been assigned to other axes.",
7215 getDeviceName().string(), mAxes.keyAt(i));
7216 mAxes.removeItemsAt(i--);
7217 numAxes -= 1;
7218 }
7219 }
7220 }
7221 }
7222}
7223
7224bool JoystickInputMapper::haveAxis(int32_t axisId) {
7225 size_t numAxes = mAxes.size();
7226 for (size_t i = 0; i < numAxes; i++) {
7227 const Axis& axis = mAxes.valueAt(i);
7228 if (axis.axisInfo.axis == axisId
7229 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7230 && axis.axisInfo.highAxis == axisId)) {
7231 return true;
7232 }
7233 }
7234 return false;
7235}
7236
7237void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7238 size_t i = mAxes.size();
7239 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7240 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7241 continue;
7242 }
7243 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7244 getDeviceName().string(), mAxes.keyAt(i));
7245 mAxes.removeItemsAt(i);
7246 }
7247}
7248
7249bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7250 switch (axis) {
7251 case AMOTION_EVENT_AXIS_X:
7252 case AMOTION_EVENT_AXIS_Y:
7253 case AMOTION_EVENT_AXIS_Z:
7254 case AMOTION_EVENT_AXIS_RX:
7255 case AMOTION_EVENT_AXIS_RY:
7256 case AMOTION_EVENT_AXIS_RZ:
7257 case AMOTION_EVENT_AXIS_HAT_X:
7258 case AMOTION_EVENT_AXIS_HAT_Y:
7259 case AMOTION_EVENT_AXIS_ORIENTATION:
7260 case AMOTION_EVENT_AXIS_RUDDER:
7261 case AMOTION_EVENT_AXIS_WHEEL:
7262 return true;
7263 default:
7264 return false;
7265 }
7266}
7267
7268void JoystickInputMapper::reset(nsecs_t when) {
7269 // Recenter all axes.
7270 size_t numAxes = mAxes.size();
7271 for (size_t i = 0; i < numAxes; i++) {
7272 Axis& axis = mAxes.editValueAt(i);
7273 axis.resetValue();
7274 }
7275
7276 InputMapper::reset(when);
7277}
7278
7279void JoystickInputMapper::process(const RawEvent* rawEvent) {
7280 switch (rawEvent->type) {
7281 case EV_ABS: {
7282 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7283 if (index >= 0) {
7284 Axis& axis = mAxes.editValueAt(index);
7285 float newValue, highNewValue;
7286 switch (axis.axisInfo.mode) {
7287 case AxisInfo::MODE_INVERT:
7288 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7289 * axis.scale + axis.offset;
7290 highNewValue = 0.0f;
7291 break;
7292 case AxisInfo::MODE_SPLIT:
7293 if (rawEvent->value < axis.axisInfo.splitValue) {
7294 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7295 * axis.scale + axis.offset;
7296 highNewValue = 0.0f;
7297 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7298 newValue = 0.0f;
7299 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7300 * axis.highScale + axis.highOffset;
7301 } else {
7302 newValue = 0.0f;
7303 highNewValue = 0.0f;
7304 }
7305 break;
7306 default:
7307 newValue = rawEvent->value * axis.scale + axis.offset;
7308 highNewValue = 0.0f;
7309 break;
7310 }
7311 axis.newValue = newValue;
7312 axis.highNewValue = highNewValue;
7313 }
7314 break;
7315 }
7316
7317 case EV_SYN:
7318 switch (rawEvent->code) {
7319 case SYN_REPORT:
7320 sync(rawEvent->when, false /*force*/);
7321 break;
7322 }
7323 break;
7324 }
7325}
7326
7327void JoystickInputMapper::sync(nsecs_t when, bool force) {
7328 if (!filterAxes(force)) {
7329 return;
7330 }
7331
7332 int32_t metaState = mContext->getGlobalMetaState();
7333 int32_t buttonState = 0;
7334
7335 PointerProperties pointerProperties;
7336 pointerProperties.clear();
7337 pointerProperties.id = 0;
7338 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7339
7340 PointerCoords pointerCoords;
7341 pointerCoords.clear();
7342
7343 size_t numAxes = mAxes.size();
7344 for (size_t i = 0; i < numAxes; i++) {
7345 const Axis& axis = mAxes.valueAt(i);
7346 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7347 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7348 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7349 axis.highCurrentValue);
7350 }
7351 }
7352
7353 // Moving a joystick axis should not wake the device because joysticks can
7354 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7355 // button will likely wake the device.
7356 // TODO: Use the input device configuration to control this behavior more finely.
7357 uint32_t policyFlags = 0;
7358
7359 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007360 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007361 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7362 getListener()->notifyMotion(&args);
7363}
7364
7365void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7366 int32_t axis, float value) {
7367 pointerCoords->setAxisValue(axis, value);
7368 /* In order to ease the transition for developers from using the old axes
7369 * to the newer, more semantically correct axes, we'll continue to produce
7370 * values for the old axes as mirrors of the value of their corresponding
7371 * new axes. */
7372 int32_t compatAxis = getCompatAxis(axis);
7373 if (compatAxis >= 0) {
7374 pointerCoords->setAxisValue(compatAxis, value);
7375 }
7376}
7377
7378bool JoystickInputMapper::filterAxes(bool force) {
7379 bool atLeastOneSignificantChange = force;
7380 size_t numAxes = mAxes.size();
7381 for (size_t i = 0; i < numAxes; i++) {
7382 Axis& axis = mAxes.editValueAt(i);
7383 if (force || hasValueChangedSignificantly(axis.filter,
7384 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7385 axis.currentValue = axis.newValue;
7386 atLeastOneSignificantChange = true;
7387 }
7388 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7389 if (force || hasValueChangedSignificantly(axis.filter,
7390 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7391 axis.highCurrentValue = axis.highNewValue;
7392 atLeastOneSignificantChange = true;
7393 }
7394 }
7395 }
7396 return atLeastOneSignificantChange;
7397}
7398
7399bool JoystickInputMapper::hasValueChangedSignificantly(
7400 float filter, float newValue, float currentValue, float min, float max) {
7401 if (newValue != currentValue) {
7402 // Filter out small changes in value unless the value is converging on the axis
7403 // bounds or center point. This is intended to reduce the amount of information
7404 // sent to applications by particularly noisy joysticks (such as PS3).
7405 if (fabs(newValue - currentValue) > filter
7406 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7407 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7408 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7409 return true;
7410 }
7411 }
7412 return false;
7413}
7414
7415bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7416 float filter, float newValue, float currentValue, float thresholdValue) {
7417 float newDistance = fabs(newValue - thresholdValue);
7418 if (newDistance < filter) {
7419 float oldDistance = fabs(currentValue - thresholdValue);
7420 if (newDistance < oldDistance) {
7421 return true;
7422 }
7423 }
7424 return false;
7425}
7426
7427} // namespace android