blob: 6dd12d6bdd1cac50cb4b7abab911a713e67954cb [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) {
Michael Spangf88ea9b2017-09-05 20:17:16 -0400260 for (const DisplayViewport& currentViewport : mVirtualDisplays) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700261 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
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700432 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433#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
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001179 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 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 "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001854 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 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 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002150 patternStr.appendFormat("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002152 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 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
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002201 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202#endif
2203 getEventHub()->vibrate(getDeviceId(), duration);
2204 } else {
2205#if DEBUG_VIBRATOR
2206 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2207#endif
2208 getEventHub()->cancelVibrate(getDeviceId());
2209 }
2210 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2211 mNextStepTime = now + duration;
2212 getContext()->requestTimeoutAtTime(mNextStepTime);
2213#if DEBUG_VIBRATOR
2214 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2215#endif
2216}
2217
2218void VibratorInputMapper::stopVibrating() {
2219 mVibrating = false;
2220#if DEBUG_VIBRATOR
2221 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2222#endif
2223 getEventHub()->cancelVibrate(getDeviceId());
2224}
2225
2226void VibratorInputMapper::dump(String8& dump) {
2227 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2228 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2229}
2230
2231
2232// --- KeyboardInputMapper ---
2233
2234KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2235 uint32_t source, int32_t keyboardType) :
2236 InputMapper(device), mSource(source),
2237 mKeyboardType(keyboardType) {
2238}
2239
2240KeyboardInputMapper::~KeyboardInputMapper() {
2241}
2242
2243uint32_t KeyboardInputMapper::getSources() {
2244 return mSource;
2245}
2246
2247void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2248 InputMapper::populateDeviceInfo(info);
2249
2250 info->setKeyboardType(mKeyboardType);
2251 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2252}
2253
2254void KeyboardInputMapper::dump(String8& dump) {
2255 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2256 dumpParameters(dump);
2257 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2258 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002259 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002261 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262}
2263
2264
2265void KeyboardInputMapper::configure(nsecs_t when,
2266 const InputReaderConfiguration* config, uint32_t changes) {
2267 InputMapper::configure(when, config, changes);
2268
2269 if (!changes) { // first time only
2270 // Configure basic parameters.
2271 configureParameters();
2272 }
2273
2274 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2275 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2276 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002277 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 mOrientation = v.orientation;
2279 } else {
2280 mOrientation = DISPLAY_ORIENTATION_0;
2281 }
2282 } else {
2283 mOrientation = DISPLAY_ORIENTATION_0;
2284 }
2285 }
2286}
2287
Ivan Podogovb9afef32017-02-13 15:34:32 +00002288static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2289 int32_t mapped = 0;
2290 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2291 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2292 if (stemKeyRotationMap[i][0] == keyCode) {
2293 stemKeyRotationMap[i][1] = mapped;
2294 return;
2295 }
2296 }
2297 }
2298}
2299
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300void KeyboardInputMapper::configureParameters() {
2301 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002302 const PropertyMap& config = getDevice()->getConfiguration();
2303 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 mParameters.orientationAware);
2305
2306 mParameters.hasAssociatedDisplay = false;
2307 if (mParameters.orientationAware) {
2308 mParameters.hasAssociatedDisplay = true;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002309
2310 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2311 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2312 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2313 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002315
2316 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002317 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002318 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319}
2320
2321void KeyboardInputMapper::dumpParameters(String8& dump) {
2322 dump.append(INDENT3 "Parameters:\n");
2323 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2324 toString(mParameters.hasAssociatedDisplay));
2325 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2326 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002327 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2328 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329}
2330
2331void KeyboardInputMapper::reset(nsecs_t when) {
2332 mMetaState = AMETA_NONE;
2333 mDownTime = 0;
2334 mKeyDowns.clear();
2335 mCurrentHidUsage = 0;
2336
2337 resetLedState();
2338
2339 InputMapper::reset(when);
2340}
2341
2342void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2343 switch (rawEvent->type) {
2344 case EV_KEY: {
2345 int32_t scanCode = rawEvent->code;
2346 int32_t usageCode = mCurrentHidUsage;
2347 mCurrentHidUsage = 0;
2348
2349 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002350 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 }
2352 break;
2353 }
2354 case EV_MSC: {
2355 if (rawEvent->code == MSC_SCAN) {
2356 mCurrentHidUsage = rawEvent->value;
2357 }
2358 break;
2359 }
2360 case EV_SYN: {
2361 if (rawEvent->code == SYN_REPORT) {
2362 mCurrentHidUsage = 0;
2363 }
2364 }
2365 }
2366}
2367
2368bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2369 return scanCode < BTN_MOUSE
2370 || scanCode >= KEY_OK
2371 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2372 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2373}
2374
Michael Wright58ba9882017-07-26 16:19:11 +01002375bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2376 switch (keyCode) {
2377 case AKEYCODE_MEDIA_PLAY:
2378 case AKEYCODE_MEDIA_PAUSE:
2379 case AKEYCODE_MEDIA_PLAY_PAUSE:
2380 case AKEYCODE_MUTE:
2381 case AKEYCODE_HEADSETHOOK:
2382 case AKEYCODE_MEDIA_STOP:
2383 case AKEYCODE_MEDIA_NEXT:
2384 case AKEYCODE_MEDIA_PREVIOUS:
2385 case AKEYCODE_MEDIA_REWIND:
2386 case AKEYCODE_MEDIA_RECORD:
2387 case AKEYCODE_MEDIA_FAST_FORWARD:
2388 case AKEYCODE_MEDIA_SKIP_FORWARD:
2389 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2390 case AKEYCODE_MEDIA_STEP_FORWARD:
2391 case AKEYCODE_MEDIA_STEP_BACKWARD:
2392 case AKEYCODE_MEDIA_AUDIO_TRACK:
2393 case AKEYCODE_VOLUME_UP:
2394 case AKEYCODE_VOLUME_DOWN:
2395 case AKEYCODE_VOLUME_MUTE:
2396 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2397 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2398 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2399 return true;
2400 }
2401 return false;
2402}
2403
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002404void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2405 int32_t usageCode) {
2406 int32_t keyCode;
2407 int32_t keyMetaState;
2408 uint32_t policyFlags;
2409
2410 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2411 &keyCode, &keyMetaState, &policyFlags)) {
2412 keyCode = AKEYCODE_UNKNOWN;
2413 keyMetaState = mMetaState;
2414 policyFlags = 0;
2415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416
2417 if (down) {
2418 // Rotate key codes according to orientation if needed.
2419 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2420 keyCode = rotateKeyCode(keyCode, mOrientation);
2421 }
2422
2423 // Add key down.
2424 ssize_t keyDownIndex = findKeyDown(scanCode);
2425 if (keyDownIndex >= 0) {
2426 // key repeat, be sure to use same keycode as before in case of rotation
2427 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2428 } else {
2429 // key down
2430 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2431 && mContext->shouldDropVirtualKey(when,
2432 getDevice(), keyCode, scanCode)) {
2433 return;
2434 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002435 if (policyFlags & POLICY_FLAG_GESTURE) {
2436 mDevice->cancelTouch(when);
2437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438
2439 mKeyDowns.push();
2440 KeyDown& keyDown = mKeyDowns.editTop();
2441 keyDown.keyCode = keyCode;
2442 keyDown.scanCode = scanCode;
2443 }
2444
2445 mDownTime = when;
2446 } else {
2447 // Remove key down.
2448 ssize_t keyDownIndex = findKeyDown(scanCode);
2449 if (keyDownIndex >= 0) {
2450 // key up, be sure to use same keycode as before in case of rotation
2451 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2452 mKeyDowns.removeAt(size_t(keyDownIndex));
2453 } else {
2454 // key was not actually down
2455 ALOGI("Dropping key up from device %s because the key was not down. "
2456 "keyCode=%d, scanCode=%d",
2457 getDeviceName().string(), keyCode, scanCode);
2458 return;
2459 }
2460 }
2461
Andrii Kulian763a3a42016-03-08 10:46:16 -08002462 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002463 // If global meta state changed send it along with the key.
2464 // If it has not changed then we'll use what keymap gave us,
2465 // since key replacement logic might temporarily reset a few
2466 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002467 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 }
2469
2470 nsecs_t downTime = mDownTime;
2471
2472 // Key down on external an keyboard should wake the device.
2473 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2474 // For internal keyboards, the key layout file should specify the policy flags for
2475 // each wake key individually.
2476 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002477 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002478 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002481 if (mParameters.handlesKeyRepeat) {
2482 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2483 }
2484
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2486 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002487 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 getListener()->notifyKey(&args);
2489}
2490
2491ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2492 size_t n = mKeyDowns.size();
2493 for (size_t i = 0; i < n; i++) {
2494 if (mKeyDowns[i].scanCode == scanCode) {
2495 return i;
2496 }
2497 }
2498 return -1;
2499}
2500
2501int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2502 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2503}
2504
2505int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2506 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2507}
2508
2509bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2510 const int32_t* keyCodes, uint8_t* outFlags) {
2511 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2512}
2513
2514int32_t KeyboardInputMapper::getMetaState() {
2515 return mMetaState;
2516}
2517
Andrii Kulian763a3a42016-03-08 10:46:16 -08002518void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2519 updateMetaStateIfNeeded(keyCode, false);
2520}
2521
2522bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2523 int32_t oldMetaState = mMetaState;
2524 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2525 bool metaStateChanged = oldMetaState != newMetaState;
2526 if (metaStateChanged) {
2527 mMetaState = newMetaState;
2528 updateLedState(false);
2529
2530 getContext()->updateGlobalMetaState();
2531 }
2532
2533 return metaStateChanged;
2534}
2535
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536void KeyboardInputMapper::resetLedState() {
2537 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2538 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2539 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2540
2541 updateLedState(true);
2542}
2543
2544void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2545 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2546 ledState.on = false;
2547}
2548
2549void KeyboardInputMapper::updateLedState(bool reset) {
2550 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2551 AMETA_CAPS_LOCK_ON, reset);
2552 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2553 AMETA_NUM_LOCK_ON, reset);
2554 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2555 AMETA_SCROLL_LOCK_ON, reset);
2556}
2557
2558void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2559 int32_t led, int32_t modifier, bool reset) {
2560 if (ledState.avail) {
2561 bool desiredState = (mMetaState & modifier) != 0;
2562 if (reset || ledState.on != desiredState) {
2563 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2564 ledState.on = desiredState;
2565 }
2566 }
2567}
2568
2569
2570// --- CursorInputMapper ---
2571
2572CursorInputMapper::CursorInputMapper(InputDevice* device) :
2573 InputMapper(device) {
2574}
2575
2576CursorInputMapper::~CursorInputMapper() {
2577}
2578
2579uint32_t CursorInputMapper::getSources() {
2580 return mSource;
2581}
2582
2583void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2584 InputMapper::populateDeviceInfo(info);
2585
2586 if (mParameters.mode == Parameters::MODE_POINTER) {
2587 float minX, minY, maxX, maxY;
2588 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2589 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2590 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2591 }
2592 } else {
2593 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2594 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2595 }
2596 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2597
2598 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2599 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2600 }
2601 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2602 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2603 }
2604}
2605
2606void CursorInputMapper::dump(String8& dump) {
2607 dump.append(INDENT2 "Cursor Input Mapper:\n");
2608 dumpParameters(dump);
2609 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2610 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2611 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2612 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2613 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2614 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2615 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2616 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2617 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2618 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2619 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2620 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2621 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002622 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623}
2624
2625void CursorInputMapper::configure(nsecs_t when,
2626 const InputReaderConfiguration* config, uint32_t changes) {
2627 InputMapper::configure(when, config, changes);
2628
2629 if (!changes) { // first time only
2630 mCursorScrollAccumulator.configure(getDevice());
2631
2632 // Configure basic parameters.
2633 configureParameters();
2634
2635 // Configure device mode.
2636 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002637 case Parameters::MODE_POINTER_RELATIVE:
2638 // Should not happen during first time configuration.
2639 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2640 mParameters.mode = Parameters::MODE_POINTER;
2641 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 case Parameters::MODE_POINTER:
2643 mSource = AINPUT_SOURCE_MOUSE;
2644 mXPrecision = 1.0f;
2645 mYPrecision = 1.0f;
2646 mXScale = 1.0f;
2647 mYScale = 1.0f;
2648 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2649 break;
2650 case Parameters::MODE_NAVIGATION:
2651 mSource = AINPUT_SOURCE_TRACKBALL;
2652 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2653 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2654 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2655 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2656 break;
2657 }
2658
2659 mVWheelScale = 1.0f;
2660 mHWheelScale = 1.0f;
2661 }
2662
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002663 if ((!changes && config->pointerCapture)
2664 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2665 if (config->pointerCapture) {
2666 if (mParameters.mode == Parameters::MODE_POINTER) {
2667 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2668 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2669 // Keep PointerController around in order to preserve the pointer position.
2670 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2671 } else {
2672 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2673 }
2674 } else {
2675 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2676 mParameters.mode = Parameters::MODE_POINTER;
2677 mSource = AINPUT_SOURCE_MOUSE;
2678 } else {
2679 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2680 }
2681 }
2682 bumpGeneration();
2683 if (changes) {
2684 getDevice()->notifyReset(when);
2685 }
2686 }
2687
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2689 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2690 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2691 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2692 }
2693
2694 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2695 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2696 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002697 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 mOrientation = v.orientation;
2699 } else {
2700 mOrientation = DISPLAY_ORIENTATION_0;
2701 }
2702 } else {
2703 mOrientation = DISPLAY_ORIENTATION_0;
2704 }
2705 bumpGeneration();
2706 }
2707}
2708
2709void CursorInputMapper::configureParameters() {
2710 mParameters.mode = Parameters::MODE_POINTER;
2711 String8 cursorModeString;
2712 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2713 if (cursorModeString == "navigation") {
2714 mParameters.mode = Parameters::MODE_NAVIGATION;
2715 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2716 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2717 }
2718 }
2719
2720 mParameters.orientationAware = false;
2721 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2722 mParameters.orientationAware);
2723
2724 mParameters.hasAssociatedDisplay = false;
2725 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2726 mParameters.hasAssociatedDisplay = true;
2727 }
2728}
2729
2730void CursorInputMapper::dumpParameters(String8& dump) {
2731 dump.append(INDENT3 "Parameters:\n");
2732 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2733 toString(mParameters.hasAssociatedDisplay));
2734
2735 switch (mParameters.mode) {
2736 case Parameters::MODE_POINTER:
2737 dump.append(INDENT4 "Mode: pointer\n");
2738 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002739 case Parameters::MODE_POINTER_RELATIVE:
2740 dump.append(INDENT4 "Mode: relative pointer\n");
2741 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 case Parameters::MODE_NAVIGATION:
2743 dump.append(INDENT4 "Mode: navigation\n");
2744 break;
2745 default:
2746 ALOG_ASSERT(false);
2747 }
2748
2749 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2750 toString(mParameters.orientationAware));
2751}
2752
2753void CursorInputMapper::reset(nsecs_t when) {
2754 mButtonState = 0;
2755 mDownTime = 0;
2756
2757 mPointerVelocityControl.reset();
2758 mWheelXVelocityControl.reset();
2759 mWheelYVelocityControl.reset();
2760
2761 mCursorButtonAccumulator.reset(getDevice());
2762 mCursorMotionAccumulator.reset(getDevice());
2763 mCursorScrollAccumulator.reset(getDevice());
2764
2765 InputMapper::reset(when);
2766}
2767
2768void CursorInputMapper::process(const RawEvent* rawEvent) {
2769 mCursorButtonAccumulator.process(rawEvent);
2770 mCursorMotionAccumulator.process(rawEvent);
2771 mCursorScrollAccumulator.process(rawEvent);
2772
2773 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2774 sync(rawEvent->when);
2775 }
2776}
2777
2778void CursorInputMapper::sync(nsecs_t when) {
2779 int32_t lastButtonState = mButtonState;
2780 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2781 mButtonState = currentButtonState;
2782
2783 bool wasDown = isPointerDown(lastButtonState);
2784 bool down = isPointerDown(currentButtonState);
2785 bool downChanged;
2786 if (!wasDown && down) {
2787 mDownTime = when;
2788 downChanged = true;
2789 } else if (wasDown && !down) {
2790 downChanged = true;
2791 } else {
2792 downChanged = false;
2793 }
2794 nsecs_t downTime = mDownTime;
2795 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002796 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2797 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798
2799 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2800 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2801 bool moved = deltaX != 0 || deltaY != 0;
2802
2803 // Rotate delta according to orientation if needed.
2804 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2805 && (deltaX != 0.0f || deltaY != 0.0f)) {
2806 rotateDelta(mOrientation, &deltaX, &deltaY);
2807 }
2808
2809 // Move the pointer.
2810 PointerProperties pointerProperties;
2811 pointerProperties.clear();
2812 pointerProperties.id = 0;
2813 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2814
2815 PointerCoords pointerCoords;
2816 pointerCoords.clear();
2817
2818 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2819 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2820 bool scrolled = vscroll != 0 || hscroll != 0;
2821
2822 mWheelYVelocityControl.move(when, NULL, &vscroll);
2823 mWheelXVelocityControl.move(when, &hscroll, NULL);
2824
2825 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2826
2827 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002828 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 if (moved || scrolled || buttonsChanged) {
2830 mPointerController->setPresentation(
2831 PointerControllerInterface::PRESENTATION_POINTER);
2832
2833 if (moved) {
2834 mPointerController->move(deltaX, deltaY);
2835 }
2836
2837 if (buttonsChanged) {
2838 mPointerController->setButtonState(currentButtonState);
2839 }
2840
2841 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2842 }
2843
2844 float x, y;
2845 mPointerController->getPosition(&x, &y);
2846 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2847 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002848 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2849 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 displayId = ADISPLAY_ID_DEFAULT;
2851 } else {
2852 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2853 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2854 displayId = ADISPLAY_ID_NONE;
2855 }
2856
2857 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2858
2859 // Moving an external trackball or mouse should wake the device.
2860 // We don't do this for internal cursor devices to prevent them from waking up
2861 // the device in your pocket.
2862 // TODO: Use the input device configuration to control this behavior more finely.
2863 uint32_t policyFlags = 0;
2864 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002865 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 }
2867
2868 // Synthesize key down from buttons if needed.
2869 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2870 policyFlags, lastButtonState, currentButtonState);
2871
2872 // Send motion event.
2873 if (downChanged || moved || scrolled || buttonsChanged) {
2874 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002875 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 int32_t motionEventAction;
2877 if (downChanged) {
2878 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002879 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2881 } else {
2882 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2883 }
2884
Michael Wright7b159c92015-05-14 14:48:03 +01002885 if (buttonsReleased) {
2886 BitSet32 released(buttonsReleased);
2887 while (!released.isEmpty()) {
2888 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2889 buttonState &= ~actionButton;
2890 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2891 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2892 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2893 displayId, 1, &pointerProperties, &pointerCoords,
2894 mXPrecision, mYPrecision, downTime);
2895 getListener()->notifyMotion(&releaseArgs);
2896 }
2897 }
2898
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002900 motionEventAction, 0, 0, metaState, currentButtonState,
2901 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 displayId, 1, &pointerProperties, &pointerCoords,
2903 mXPrecision, mYPrecision, downTime);
2904 getListener()->notifyMotion(&args);
2905
Michael Wright7b159c92015-05-14 14:48:03 +01002906 if (buttonsPressed) {
2907 BitSet32 pressed(buttonsPressed);
2908 while (!pressed.isEmpty()) {
2909 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2910 buttonState |= actionButton;
2911 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2912 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2913 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2914 displayId, 1, &pointerProperties, &pointerCoords,
2915 mXPrecision, mYPrecision, downTime);
2916 getListener()->notifyMotion(&pressArgs);
2917 }
2918 }
2919
2920 ALOG_ASSERT(buttonState == currentButtonState);
2921
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 // Send hover move after UP to tell the application that the mouse is hovering now.
2923 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002924 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002926 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2928 displayId, 1, &pointerProperties, &pointerCoords,
2929 mXPrecision, mYPrecision, downTime);
2930 getListener()->notifyMotion(&hoverArgs);
2931 }
2932
2933 // Send scroll events.
2934 if (scrolled) {
2935 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2936 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2937
2938 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002939 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 AMOTION_EVENT_EDGE_FLAG_NONE,
2941 displayId, 1, &pointerProperties, &pointerCoords,
2942 mXPrecision, mYPrecision, downTime);
2943 getListener()->notifyMotion(&scrollArgs);
2944 }
2945 }
2946
2947 // Synthesize key up from buttons if needed.
2948 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2949 policyFlags, lastButtonState, currentButtonState);
2950
2951 mCursorMotionAccumulator.finishSync();
2952 mCursorScrollAccumulator.finishSync();
2953}
2954
2955int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2956 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2957 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2958 } else {
2959 return AKEY_STATE_UNKNOWN;
2960 }
2961}
2962
2963void CursorInputMapper::fadePointer() {
2964 if (mPointerController != NULL) {
2965 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2966 }
2967}
2968
Prashant Malani1941ff52015-08-11 18:29:28 -07002969// --- RotaryEncoderInputMapper ---
2970
2971RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002972 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002973 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2974}
2975
2976RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2977}
2978
2979uint32_t RotaryEncoderInputMapper::getSources() {
2980 return mSource;
2981}
2982
2983void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2984 InputMapper::populateDeviceInfo(info);
2985
2986 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002987 float res = 0.0f;
2988 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2989 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2990 }
2991 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2992 mScalingFactor)) {
2993 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2994 "default to 1.0!\n");
2995 mScalingFactor = 1.0f;
2996 }
2997 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2998 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002999 }
3000}
3001
3002void RotaryEncoderInputMapper::dump(String8& dump) {
3003 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
3004 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
3005 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3006}
3007
3008void RotaryEncoderInputMapper::configure(nsecs_t when,
3009 const InputReaderConfiguration* config, uint32_t changes) {
3010 InputMapper::configure(when, config, changes);
3011 if (!changes) {
3012 mRotaryEncoderScrollAccumulator.configure(getDevice());
3013 }
Ivan Podogovad437252016-09-29 16:29:55 +01003014 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
3015 DisplayViewport v;
3016 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
3017 mOrientation = v.orientation;
3018 } else {
3019 mOrientation = DISPLAY_ORIENTATION_0;
3020 }
3021 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003022}
3023
3024void RotaryEncoderInputMapper::reset(nsecs_t when) {
3025 mRotaryEncoderScrollAccumulator.reset(getDevice());
3026
3027 InputMapper::reset(when);
3028}
3029
3030void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3031 mRotaryEncoderScrollAccumulator.process(rawEvent);
3032
3033 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3034 sync(rawEvent->when);
3035 }
3036}
3037
3038void RotaryEncoderInputMapper::sync(nsecs_t when) {
3039 PointerCoords pointerCoords;
3040 pointerCoords.clear();
3041
3042 PointerProperties pointerProperties;
3043 pointerProperties.clear();
3044 pointerProperties.id = 0;
3045 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3046
3047 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3048 bool scrolled = scroll != 0;
3049
3050 // This is not a pointer, so it's not associated with a display.
3051 int32_t displayId = ADISPLAY_ID_NONE;
3052
3053 // Moving the rotary encoder should wake the device (if specified).
3054 uint32_t policyFlags = 0;
3055 if (scrolled && getDevice()->isExternal()) {
3056 policyFlags |= POLICY_FLAG_WAKE;
3057 }
3058
Ivan Podogovad437252016-09-29 16:29:55 +01003059 if (mOrientation == DISPLAY_ORIENTATION_180) {
3060 scroll = -scroll;
3061 }
3062
Prashant Malani1941ff52015-08-11 18:29:28 -07003063 // Send motion event.
3064 if (scrolled) {
3065 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003066 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003067
3068 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3069 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3070 AMOTION_EVENT_EDGE_FLAG_NONE,
3071 displayId, 1, &pointerProperties, &pointerCoords,
3072 0, 0, 0);
3073 getListener()->notifyMotion(&scrollArgs);
3074 }
3075
3076 mRotaryEncoderScrollAccumulator.finishSync();
3077}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078
3079// --- TouchInputMapper ---
3080
3081TouchInputMapper::TouchInputMapper(InputDevice* device) :
3082 InputMapper(device),
3083 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3084 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3085 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3086}
3087
3088TouchInputMapper::~TouchInputMapper() {
3089}
3090
3091uint32_t TouchInputMapper::getSources() {
3092 return mSource;
3093}
3094
3095void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3096 InputMapper::populateDeviceInfo(info);
3097
3098 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3099 info->addMotionRange(mOrientedRanges.x);
3100 info->addMotionRange(mOrientedRanges.y);
3101 info->addMotionRange(mOrientedRanges.pressure);
3102
3103 if (mOrientedRanges.haveSize) {
3104 info->addMotionRange(mOrientedRanges.size);
3105 }
3106
3107 if (mOrientedRanges.haveTouchSize) {
3108 info->addMotionRange(mOrientedRanges.touchMajor);
3109 info->addMotionRange(mOrientedRanges.touchMinor);
3110 }
3111
3112 if (mOrientedRanges.haveToolSize) {
3113 info->addMotionRange(mOrientedRanges.toolMajor);
3114 info->addMotionRange(mOrientedRanges.toolMinor);
3115 }
3116
3117 if (mOrientedRanges.haveOrientation) {
3118 info->addMotionRange(mOrientedRanges.orientation);
3119 }
3120
3121 if (mOrientedRanges.haveDistance) {
3122 info->addMotionRange(mOrientedRanges.distance);
3123 }
3124
3125 if (mOrientedRanges.haveTilt) {
3126 info->addMotionRange(mOrientedRanges.tilt);
3127 }
3128
3129 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3130 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3131 0.0f);
3132 }
3133 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3134 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3135 0.0f);
3136 }
3137 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3138 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3139 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3140 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3141 x.fuzz, x.resolution);
3142 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3143 y.fuzz, y.resolution);
3144 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3145 x.fuzz, x.resolution);
3146 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3147 y.fuzz, y.resolution);
3148 }
3149 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3150 }
3151}
3152
3153void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003154 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 dumpParameters(dump);
3156 dumpVirtualKeys(dump);
3157 dumpRawPointerAxes(dump);
3158 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003159 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 dumpSurface(dump);
3161
3162 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3163 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3164 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3165 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3166 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3167 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3168 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3169 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3170 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3171 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3172 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3173 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3174 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3175 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3176 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3177 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3178 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3179
Michael Wright7b159c92015-05-14 14:48:03 +01003180 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003182 mLastRawState.rawPointerData.pointerCount);
3183 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3184 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3186 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3187 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3188 "toolType=%d, isHovering=%s\n", i,
3189 pointer.id, pointer.x, pointer.y, pointer.pressure,
3190 pointer.touchMajor, pointer.touchMinor,
3191 pointer.toolMajor, pointer.toolMinor,
3192 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3193 pointer.toolType, toString(pointer.isHovering));
3194 }
3195
Michael Wright7b159c92015-05-14 14:48:03 +01003196 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003198 mLastCookedState.cookedPointerData.pointerCount);
3199 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3200 const PointerProperties& pointerProperties =
3201 mLastCookedState.cookedPointerData.pointerProperties[i];
3202 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3204 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3205 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3206 "toolType=%d, isHovering=%s\n", i,
3207 pointerProperties.id,
3208 pointerCoords.getX(),
3209 pointerCoords.getY(),
3210 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3211 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3212 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3213 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3214 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3215 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3216 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3217 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3218 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003219 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 }
3221
Michael Wright842500e2015-03-13 17:32:02 -07003222 dump.append(INDENT3 "Stylus Fusion:\n");
3223 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3224 toString(mExternalStylusConnected));
3225 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3226 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003227 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003228 dump.append(INDENT3 "External Stylus State:\n");
3229 dumpStylusState(dump, mExternalStylusState);
3230
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 if (mDeviceMode == DEVICE_MODE_POINTER) {
3232 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3233 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3234 mPointerXMovementScale);
3235 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3236 mPointerYMovementScale);
3237 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3238 mPointerXZoomScale);
3239 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3240 mPointerYZoomScale);
3241 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3242 mPointerGestureMaxSwipeWidth);
3243 }
3244}
3245
Santos Cordonfa5cf462017-04-05 10:37:00 -07003246const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3247 switch (deviceMode) {
3248 case DEVICE_MODE_DISABLED:
3249 return "disabled";
3250 case DEVICE_MODE_DIRECT:
3251 return "direct";
3252 case DEVICE_MODE_UNSCALED:
3253 return "unscaled";
3254 case DEVICE_MODE_NAVIGATION:
3255 return "navigation";
3256 case DEVICE_MODE_POINTER:
3257 return "pointer";
3258 }
3259 return "unknown";
3260}
3261
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262void TouchInputMapper::configure(nsecs_t when,
3263 const InputReaderConfiguration* config, uint32_t changes) {
3264 InputMapper::configure(when, config, changes);
3265
3266 mConfig = *config;
3267
3268 if (!changes) { // first time only
3269 // Configure basic parameters.
3270 configureParameters();
3271
3272 // Configure common accumulators.
3273 mCursorScrollAccumulator.configure(getDevice());
3274 mTouchButtonAccumulator.configure(getDevice());
3275
3276 // Configure absolute axis information.
3277 configureRawPointerAxes();
3278
3279 // Prepare input device calibration.
3280 parseCalibration();
3281 resolveCalibration();
3282 }
3283
Michael Wright842500e2015-03-13 17:32:02 -07003284 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003285 // Update location calibration to reflect current settings
3286 updateAffineTransformation();
3287 }
3288
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3290 // Update pointer speed.
3291 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3292 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3293 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3294 }
3295
3296 bool resetNeeded = false;
3297 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3298 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003299 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3300 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 // Configure device sources, surface dimensions, orientation and
3302 // scaling factors.
3303 configureSurface(when, &resetNeeded);
3304 }
3305
3306 if (changes && resetNeeded) {
3307 // Send reset, unless this is the first time the device has been configured,
3308 // in which case the reader will call reset itself after all mappers are ready.
3309 getDevice()->notifyReset(when);
3310 }
3311}
3312
Michael Wright842500e2015-03-13 17:32:02 -07003313void TouchInputMapper::resolveExternalStylusPresence() {
3314 Vector<InputDeviceInfo> devices;
3315 mContext->getExternalStylusDevices(devices);
3316 mExternalStylusConnected = !devices.isEmpty();
3317
3318 if (!mExternalStylusConnected) {
3319 resetExternalStylus();
3320 }
3321}
3322
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323void TouchInputMapper::configureParameters() {
3324 // Use the pointer presentation mode for devices that do not support distinct
3325 // multitouch. The spot-based presentation relies on being able to accurately
3326 // locate two or more fingers on the touch pad.
3327 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003328 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329
3330 String8 gestureModeString;
3331 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3332 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003333 if (gestureModeString == "single-touch") {
3334 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3335 } else if (gestureModeString == "multi-touch") {
3336 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 } else if (gestureModeString != "default") {
3338 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3339 }
3340 }
3341
3342 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3343 // The device is a touch screen.
3344 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3345 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3346 // The device is a pointing device like a track pad.
3347 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3348 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3349 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3350 // The device is a cursor device with a touch pad attached.
3351 // By default don't use the touch pad to move the pointer.
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3353 } else {
3354 // The device is a touch pad of unknown purpose.
3355 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3356 }
3357
3358 mParameters.hasButtonUnderPad=
3359 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3360
3361 String8 deviceTypeString;
3362 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3363 deviceTypeString)) {
3364 if (deviceTypeString == "touchScreen") {
3365 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3366 } else if (deviceTypeString == "touchPad") {
3367 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3368 } else if (deviceTypeString == "touchNavigation") {
3369 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3370 } else if (deviceTypeString == "pointer") {
3371 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3372 } else if (deviceTypeString != "default") {
3373 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3374 }
3375 }
3376
3377 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3378 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3379 mParameters.orientationAware);
3380
3381 mParameters.hasAssociatedDisplay = false;
3382 mParameters.associatedDisplayIsExternal = false;
3383 if (mParameters.orientationAware
3384 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3385 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3386 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003387 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3388 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3389 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3390 mParameters.uniqueDisplayId);
3391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003393
3394 // Initial downs on external touch devices should wake the device.
3395 // Normally we don't do this for internal touch screens to prevent them from waking
3396 // up in your pocket but you can enable it using the input device configuration.
3397 mParameters.wake = getDevice()->isExternal();
3398 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3399 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400}
3401
3402void TouchInputMapper::dumpParameters(String8& dump) {
3403 dump.append(INDENT3 "Parameters:\n");
3404
3405 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003406 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3407 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003409 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3410 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 break;
3412 default:
3413 assert(false);
3414 }
3415
3416 switch (mParameters.deviceType) {
3417 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3418 dump.append(INDENT4 "DeviceType: touchScreen\n");
3419 break;
3420 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3421 dump.append(INDENT4 "DeviceType: touchPad\n");
3422 break;
3423 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3424 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3425 break;
3426 case Parameters::DEVICE_TYPE_POINTER:
3427 dump.append(INDENT4 "DeviceType: pointer\n");
3428 break;
3429 default:
3430 ALOG_ASSERT(false);
3431 }
3432
Santos Cordonfa5cf462017-04-05 10:37:00 -07003433 dump.appendFormat(
3434 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003436 toString(mParameters.associatedDisplayIsExternal),
3437 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3439 toString(mParameters.orientationAware));
3440}
3441
3442void TouchInputMapper::configureRawPointerAxes() {
3443 mRawPointerAxes.clear();
3444}
3445
3446void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3447 dump.append(INDENT3 "Raw Touch Axes:\n");
3448 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3451 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3455 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3461}
3462
Michael Wright842500e2015-03-13 17:32:02 -07003463bool TouchInputMapper::hasExternalStylus() const {
3464 return mExternalStylusConnected;
3465}
3466
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3468 int32_t oldDeviceMode = mDeviceMode;
3469
Michael Wright842500e2015-03-13 17:32:02 -07003470 resolveExternalStylusPresence();
3471
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 // Determine device mode.
3473 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3474 && mConfig.pointerGesturesEnabled) {
3475 mSource = AINPUT_SOURCE_MOUSE;
3476 mDeviceMode = DEVICE_MODE_POINTER;
3477 if (hasStylus()) {
3478 mSource |= AINPUT_SOURCE_STYLUS;
3479 }
3480 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3481 && mParameters.hasAssociatedDisplay) {
3482 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3483 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003484 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 mSource |= AINPUT_SOURCE_STYLUS;
3486 }
Michael Wright2f78b682015-06-12 15:25:08 +01003487 if (hasExternalStylus()) {
3488 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3491 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3492 mDeviceMode = DEVICE_MODE_NAVIGATION;
3493 } else {
3494 mSource = AINPUT_SOURCE_TOUCHPAD;
3495 mDeviceMode = DEVICE_MODE_UNSCALED;
3496 }
3497
3498 // Ensure we have valid X and Y axes.
3499 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3500 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3501 "The device will be inoperable.", getDeviceName().string());
3502 mDeviceMode = DEVICE_MODE_DISABLED;
3503 return;
3504 }
3505
3506 // Raw width and height in the natural orientation.
3507 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3508 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3509
3510 // Get associated display dimensions.
3511 DisplayViewport newViewport;
3512 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003513 const String8* uniqueDisplayId = NULL;
3514 ViewportType viewportTypeToUse;
3515
3516 if (mParameters.associatedDisplayIsExternal) {
3517 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3518 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3519 // If the IDC file specified a unique display Id, then it expects to be linked to a
3520 // virtual display with the same unique ID.
3521 uniqueDisplayId = &mParameters.uniqueDisplayId;
3522 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3523 } else {
3524 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3525 }
3526
3527 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3529 "display. The device will be inoperable until the display size "
3530 "becomes available.",
3531 getDeviceName().string());
3532 mDeviceMode = DEVICE_MODE_DISABLED;
3533 return;
3534 }
3535 } else {
3536 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3537 }
3538 bool viewportChanged = mViewport != newViewport;
3539 if (viewportChanged) {
3540 mViewport = newViewport;
3541
3542 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3543 // Convert rotated viewport to natural surface coordinates.
3544 int32_t naturalLogicalWidth, naturalLogicalHeight;
3545 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3546 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3547 int32_t naturalDeviceWidth, naturalDeviceHeight;
3548 switch (mViewport.orientation) {
3549 case DISPLAY_ORIENTATION_90:
3550 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3551 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3552 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3553 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3554 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3555 naturalPhysicalTop = mViewport.physicalLeft;
3556 naturalDeviceWidth = mViewport.deviceHeight;
3557 naturalDeviceHeight = mViewport.deviceWidth;
3558 break;
3559 case DISPLAY_ORIENTATION_180:
3560 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3561 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3562 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3563 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3564 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3565 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3566 naturalDeviceWidth = mViewport.deviceWidth;
3567 naturalDeviceHeight = mViewport.deviceHeight;
3568 break;
3569 case DISPLAY_ORIENTATION_270:
3570 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3571 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3572 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3573 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3574 naturalPhysicalLeft = mViewport.physicalTop;
3575 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3576 naturalDeviceWidth = mViewport.deviceHeight;
3577 naturalDeviceHeight = mViewport.deviceWidth;
3578 break;
3579 case DISPLAY_ORIENTATION_0:
3580 default:
3581 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3582 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3583 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3584 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3585 naturalPhysicalLeft = mViewport.physicalLeft;
3586 naturalPhysicalTop = mViewport.physicalTop;
3587 naturalDeviceWidth = mViewport.deviceWidth;
3588 naturalDeviceHeight = mViewport.deviceHeight;
3589 break;
3590 }
3591
3592 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3593 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3594 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3595 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3596
3597 mSurfaceOrientation = mParameters.orientationAware ?
3598 mViewport.orientation : DISPLAY_ORIENTATION_0;
3599 } else {
3600 mSurfaceWidth = rawWidth;
3601 mSurfaceHeight = rawHeight;
3602 mSurfaceLeft = 0;
3603 mSurfaceTop = 0;
3604 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3605 }
3606 }
3607
3608 // If moving between pointer modes, need to reset some state.
3609 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3610 if (deviceModeChanged) {
3611 mOrientedRanges.clear();
3612 }
3613
3614 // Create pointer controller if needed.
3615 if (mDeviceMode == DEVICE_MODE_POINTER ||
3616 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3617 if (mPointerController == NULL) {
3618 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3619 }
3620 } else {
3621 mPointerController.clear();
3622 }
3623
3624 if (viewportChanged || deviceModeChanged) {
3625 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3626 "display id %d",
3627 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3628 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3629
3630 // Configure X and Y factors.
3631 mXScale = float(mSurfaceWidth) / rawWidth;
3632 mYScale = float(mSurfaceHeight) / rawHeight;
3633 mXTranslate = -mSurfaceLeft;
3634 mYTranslate = -mSurfaceTop;
3635 mXPrecision = 1.0f / mXScale;
3636 mYPrecision = 1.0f / mYScale;
3637
3638 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3639 mOrientedRanges.x.source = mSource;
3640 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3641 mOrientedRanges.y.source = mSource;
3642
3643 configureVirtualKeys();
3644
3645 // Scale factor for terms that are not oriented in a particular axis.
3646 // If the pixels are square then xScale == yScale otherwise we fake it
3647 // by choosing an average.
3648 mGeometricScale = avg(mXScale, mYScale);
3649
3650 // Size of diagonal axis.
3651 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3652
3653 // Size factors.
3654 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3655 if (mRawPointerAxes.touchMajor.valid
3656 && mRawPointerAxes.touchMajor.maxValue != 0) {
3657 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3658 } else if (mRawPointerAxes.toolMajor.valid
3659 && mRawPointerAxes.toolMajor.maxValue != 0) {
3660 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3661 } else {
3662 mSizeScale = 0.0f;
3663 }
3664
3665 mOrientedRanges.haveTouchSize = true;
3666 mOrientedRanges.haveToolSize = true;
3667 mOrientedRanges.haveSize = true;
3668
3669 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3670 mOrientedRanges.touchMajor.source = mSource;
3671 mOrientedRanges.touchMajor.min = 0;
3672 mOrientedRanges.touchMajor.max = diagonalSize;
3673 mOrientedRanges.touchMajor.flat = 0;
3674 mOrientedRanges.touchMajor.fuzz = 0;
3675 mOrientedRanges.touchMajor.resolution = 0;
3676
3677 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3678 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3679
3680 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3681 mOrientedRanges.toolMajor.source = mSource;
3682 mOrientedRanges.toolMajor.min = 0;
3683 mOrientedRanges.toolMajor.max = diagonalSize;
3684 mOrientedRanges.toolMajor.flat = 0;
3685 mOrientedRanges.toolMajor.fuzz = 0;
3686 mOrientedRanges.toolMajor.resolution = 0;
3687
3688 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3689 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3690
3691 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3692 mOrientedRanges.size.source = mSource;
3693 mOrientedRanges.size.min = 0;
3694 mOrientedRanges.size.max = 1.0;
3695 mOrientedRanges.size.flat = 0;
3696 mOrientedRanges.size.fuzz = 0;
3697 mOrientedRanges.size.resolution = 0;
3698 } else {
3699 mSizeScale = 0.0f;
3700 }
3701
3702 // Pressure factors.
3703 mPressureScale = 0;
3704 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3705 || mCalibration.pressureCalibration
3706 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3707 if (mCalibration.havePressureScale) {
3708 mPressureScale = mCalibration.pressureScale;
3709 } else if (mRawPointerAxes.pressure.valid
3710 && mRawPointerAxes.pressure.maxValue != 0) {
3711 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3712 }
3713 }
3714
3715 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3716 mOrientedRanges.pressure.source = mSource;
3717 mOrientedRanges.pressure.min = 0;
3718 mOrientedRanges.pressure.max = 1.0;
3719 mOrientedRanges.pressure.flat = 0;
3720 mOrientedRanges.pressure.fuzz = 0;
3721 mOrientedRanges.pressure.resolution = 0;
3722
3723 // Tilt
3724 mTiltXCenter = 0;
3725 mTiltXScale = 0;
3726 mTiltYCenter = 0;
3727 mTiltYScale = 0;
3728 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3729 if (mHaveTilt) {
3730 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3731 mRawPointerAxes.tiltX.maxValue);
3732 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3733 mRawPointerAxes.tiltY.maxValue);
3734 mTiltXScale = M_PI / 180;
3735 mTiltYScale = M_PI / 180;
3736
3737 mOrientedRanges.haveTilt = true;
3738
3739 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3740 mOrientedRanges.tilt.source = mSource;
3741 mOrientedRanges.tilt.min = 0;
3742 mOrientedRanges.tilt.max = M_PI_2;
3743 mOrientedRanges.tilt.flat = 0;
3744 mOrientedRanges.tilt.fuzz = 0;
3745 mOrientedRanges.tilt.resolution = 0;
3746 }
3747
3748 // Orientation
3749 mOrientationScale = 0;
3750 if (mHaveTilt) {
3751 mOrientedRanges.haveOrientation = true;
3752
3753 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3754 mOrientedRanges.orientation.source = mSource;
3755 mOrientedRanges.orientation.min = -M_PI;
3756 mOrientedRanges.orientation.max = M_PI;
3757 mOrientedRanges.orientation.flat = 0;
3758 mOrientedRanges.orientation.fuzz = 0;
3759 mOrientedRanges.orientation.resolution = 0;
3760 } else if (mCalibration.orientationCalibration !=
3761 Calibration::ORIENTATION_CALIBRATION_NONE) {
3762 if (mCalibration.orientationCalibration
3763 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3764 if (mRawPointerAxes.orientation.valid) {
3765 if (mRawPointerAxes.orientation.maxValue > 0) {
3766 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3767 } else if (mRawPointerAxes.orientation.minValue < 0) {
3768 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3769 } else {
3770 mOrientationScale = 0;
3771 }
3772 }
3773 }
3774
3775 mOrientedRanges.haveOrientation = true;
3776
3777 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3778 mOrientedRanges.orientation.source = mSource;
3779 mOrientedRanges.orientation.min = -M_PI_2;
3780 mOrientedRanges.orientation.max = M_PI_2;
3781 mOrientedRanges.orientation.flat = 0;
3782 mOrientedRanges.orientation.fuzz = 0;
3783 mOrientedRanges.orientation.resolution = 0;
3784 }
3785
3786 // Distance
3787 mDistanceScale = 0;
3788 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3789 if (mCalibration.distanceCalibration
3790 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3791 if (mCalibration.haveDistanceScale) {
3792 mDistanceScale = mCalibration.distanceScale;
3793 } else {
3794 mDistanceScale = 1.0f;
3795 }
3796 }
3797
3798 mOrientedRanges.haveDistance = true;
3799
3800 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3801 mOrientedRanges.distance.source = mSource;
3802 mOrientedRanges.distance.min =
3803 mRawPointerAxes.distance.minValue * mDistanceScale;
3804 mOrientedRanges.distance.max =
3805 mRawPointerAxes.distance.maxValue * mDistanceScale;
3806 mOrientedRanges.distance.flat = 0;
3807 mOrientedRanges.distance.fuzz =
3808 mRawPointerAxes.distance.fuzz * mDistanceScale;
3809 mOrientedRanges.distance.resolution = 0;
3810 }
3811
3812 // Compute oriented precision, scales and ranges.
3813 // Note that the maximum value reported is an inclusive maximum value so it is one
3814 // unit less than the total width or height of surface.
3815 switch (mSurfaceOrientation) {
3816 case DISPLAY_ORIENTATION_90:
3817 case DISPLAY_ORIENTATION_270:
3818 mOrientedXPrecision = mYPrecision;
3819 mOrientedYPrecision = mXPrecision;
3820
3821 mOrientedRanges.x.min = mYTranslate;
3822 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3823 mOrientedRanges.x.flat = 0;
3824 mOrientedRanges.x.fuzz = 0;
3825 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3826
3827 mOrientedRanges.y.min = mXTranslate;
3828 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3829 mOrientedRanges.y.flat = 0;
3830 mOrientedRanges.y.fuzz = 0;
3831 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3832 break;
3833
3834 default:
3835 mOrientedXPrecision = mXPrecision;
3836 mOrientedYPrecision = mYPrecision;
3837
3838 mOrientedRanges.x.min = mXTranslate;
3839 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3840 mOrientedRanges.x.flat = 0;
3841 mOrientedRanges.x.fuzz = 0;
3842 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3843
3844 mOrientedRanges.y.min = mYTranslate;
3845 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3846 mOrientedRanges.y.flat = 0;
3847 mOrientedRanges.y.fuzz = 0;
3848 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3849 break;
3850 }
3851
Jason Gerecke71b16e82014-03-10 09:47:59 -07003852 // Location
3853 updateAffineTransformation();
3854
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 if (mDeviceMode == DEVICE_MODE_POINTER) {
3856 // Compute pointer gesture detection parameters.
3857 float rawDiagonal = hypotf(rawWidth, rawHeight);
3858 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3859
3860 // Scale movements such that one whole swipe of the touch pad covers a
3861 // given area relative to the diagonal size of the display when no acceleration
3862 // is applied.
3863 // Assume that the touch pad has a square aspect ratio such that movements in
3864 // X and Y of the same number of raw units cover the same physical distance.
3865 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3866 * displayDiagonal / rawDiagonal;
3867 mPointerYMovementScale = mPointerXMovementScale;
3868
3869 // Scale zooms to cover a smaller range of the display than movements do.
3870 // This value determines the area around the pointer that is affected by freeform
3871 // pointer gestures.
3872 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3873 * displayDiagonal / rawDiagonal;
3874 mPointerYZoomScale = mPointerXZoomScale;
3875
3876 // Max width between pointers to detect a swipe gesture is more than some fraction
3877 // of the diagonal axis of the touch pad. Touches that are wider than this are
3878 // translated into freeform gestures.
3879 mPointerGestureMaxSwipeWidth =
3880 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3881
3882 // Abort current pointer usages because the state has changed.
3883 abortPointerUsage(when, 0 /*policyFlags*/);
3884 }
3885
3886 // Inform the dispatcher about the changes.
3887 *outResetNeeded = true;
3888 bumpGeneration();
3889 }
3890}
3891
3892void TouchInputMapper::dumpSurface(String8& dump) {
3893 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3894 "logicalFrame=[%d, %d, %d, %d], "
3895 "physicalFrame=[%d, %d, %d, %d], "
3896 "deviceSize=[%d, %d]\n",
3897 mViewport.displayId, mViewport.orientation,
3898 mViewport.logicalLeft, mViewport.logicalTop,
3899 mViewport.logicalRight, mViewport.logicalBottom,
3900 mViewport.physicalLeft, mViewport.physicalTop,
3901 mViewport.physicalRight, mViewport.physicalBottom,
3902 mViewport.deviceWidth, mViewport.deviceHeight);
3903
3904 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3905 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3906 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3907 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3908 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3909}
3910
3911void TouchInputMapper::configureVirtualKeys() {
3912 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3913 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3914
3915 mVirtualKeys.clear();
3916
3917 if (virtualKeyDefinitions.size() == 0) {
3918 return;
3919 }
3920
3921 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3922
3923 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3924 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3925 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3926 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3927
3928 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3929 const VirtualKeyDefinition& virtualKeyDefinition =
3930 virtualKeyDefinitions[i];
3931
3932 mVirtualKeys.add();
3933 VirtualKey& virtualKey = mVirtualKeys.editTop();
3934
3935 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3936 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003937 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003939 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3940 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3942 virtualKey.scanCode);
3943 mVirtualKeys.pop(); // drop the key
3944 continue;
3945 }
3946
3947 virtualKey.keyCode = keyCode;
3948 virtualKey.flags = flags;
3949
3950 // convert the key definition's display coordinates into touch coordinates for a hit box
3951 int32_t halfWidth = virtualKeyDefinition.width / 2;
3952 int32_t halfHeight = virtualKeyDefinition.height / 2;
3953
3954 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3955 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3956 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3957 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3958 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3959 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3960 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3961 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3962 }
3963}
3964
3965void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3966 if (!mVirtualKeys.isEmpty()) {
3967 dump.append(INDENT3 "Virtual Keys:\n");
3968
3969 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3970 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003971 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3973 i, virtualKey.scanCode, virtualKey.keyCode,
3974 virtualKey.hitLeft, virtualKey.hitRight,
3975 virtualKey.hitTop, virtualKey.hitBottom);
3976 }
3977 }
3978}
3979
3980void TouchInputMapper::parseCalibration() {
3981 const PropertyMap& in = getDevice()->getConfiguration();
3982 Calibration& out = mCalibration;
3983
3984 // Size
3985 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3986 String8 sizeCalibrationString;
3987 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3988 if (sizeCalibrationString == "none") {
3989 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3990 } else if (sizeCalibrationString == "geometric") {
3991 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3992 } else if (sizeCalibrationString == "diameter") {
3993 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3994 } else if (sizeCalibrationString == "box") {
3995 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3996 } else if (sizeCalibrationString == "area") {
3997 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3998 } else if (sizeCalibrationString != "default") {
3999 ALOGW("Invalid value for touch.size.calibration: '%s'",
4000 sizeCalibrationString.string());
4001 }
4002 }
4003
4004 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4005 out.sizeScale);
4006 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4007 out.sizeBias);
4008 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4009 out.sizeIsSummed);
4010
4011 // Pressure
4012 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4013 String8 pressureCalibrationString;
4014 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4015 if (pressureCalibrationString == "none") {
4016 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4017 } else if (pressureCalibrationString == "physical") {
4018 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4019 } else if (pressureCalibrationString == "amplitude") {
4020 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4021 } else if (pressureCalibrationString != "default") {
4022 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4023 pressureCalibrationString.string());
4024 }
4025 }
4026
4027 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4028 out.pressureScale);
4029
4030 // Orientation
4031 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4032 String8 orientationCalibrationString;
4033 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4034 if (orientationCalibrationString == "none") {
4035 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4036 } else if (orientationCalibrationString == "interpolated") {
4037 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4038 } else if (orientationCalibrationString == "vector") {
4039 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4040 } else if (orientationCalibrationString != "default") {
4041 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4042 orientationCalibrationString.string());
4043 }
4044 }
4045
4046 // Distance
4047 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4048 String8 distanceCalibrationString;
4049 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4050 if (distanceCalibrationString == "none") {
4051 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4052 } else if (distanceCalibrationString == "scaled") {
4053 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4054 } else if (distanceCalibrationString != "default") {
4055 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4056 distanceCalibrationString.string());
4057 }
4058 }
4059
4060 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4061 out.distanceScale);
4062
4063 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4064 String8 coverageCalibrationString;
4065 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4066 if (coverageCalibrationString == "none") {
4067 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4068 } else if (coverageCalibrationString == "box") {
4069 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4070 } else if (coverageCalibrationString != "default") {
4071 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4072 coverageCalibrationString.string());
4073 }
4074 }
4075}
4076
4077void TouchInputMapper::resolveCalibration() {
4078 // Size
4079 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4080 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4081 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4082 }
4083 } else {
4084 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4085 }
4086
4087 // Pressure
4088 if (mRawPointerAxes.pressure.valid) {
4089 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4090 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4091 }
4092 } else {
4093 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4094 }
4095
4096 // Orientation
4097 if (mRawPointerAxes.orientation.valid) {
4098 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4099 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4100 }
4101 } else {
4102 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4103 }
4104
4105 // Distance
4106 if (mRawPointerAxes.distance.valid) {
4107 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4108 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4109 }
4110 } else {
4111 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4112 }
4113
4114 // Coverage
4115 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4116 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4117 }
4118}
4119
4120void TouchInputMapper::dumpCalibration(String8& dump) {
4121 dump.append(INDENT3 "Calibration:\n");
4122
4123 // Size
4124 switch (mCalibration.sizeCalibration) {
4125 case Calibration::SIZE_CALIBRATION_NONE:
4126 dump.append(INDENT4 "touch.size.calibration: none\n");
4127 break;
4128 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4129 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4130 break;
4131 case Calibration::SIZE_CALIBRATION_DIAMETER:
4132 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4133 break;
4134 case Calibration::SIZE_CALIBRATION_BOX:
4135 dump.append(INDENT4 "touch.size.calibration: box\n");
4136 break;
4137 case Calibration::SIZE_CALIBRATION_AREA:
4138 dump.append(INDENT4 "touch.size.calibration: area\n");
4139 break;
4140 default:
4141 ALOG_ASSERT(false);
4142 }
4143
4144 if (mCalibration.haveSizeScale) {
4145 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4146 mCalibration.sizeScale);
4147 }
4148
4149 if (mCalibration.haveSizeBias) {
4150 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4151 mCalibration.sizeBias);
4152 }
4153
4154 if (mCalibration.haveSizeIsSummed) {
4155 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4156 toString(mCalibration.sizeIsSummed));
4157 }
4158
4159 // Pressure
4160 switch (mCalibration.pressureCalibration) {
4161 case Calibration::PRESSURE_CALIBRATION_NONE:
4162 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4163 break;
4164 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4165 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4166 break;
4167 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4168 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4169 break;
4170 default:
4171 ALOG_ASSERT(false);
4172 }
4173
4174 if (mCalibration.havePressureScale) {
4175 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4176 mCalibration.pressureScale);
4177 }
4178
4179 // Orientation
4180 switch (mCalibration.orientationCalibration) {
4181 case Calibration::ORIENTATION_CALIBRATION_NONE:
4182 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4183 break;
4184 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4185 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4186 break;
4187 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4188 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4189 break;
4190 default:
4191 ALOG_ASSERT(false);
4192 }
4193
4194 // Distance
4195 switch (mCalibration.distanceCalibration) {
4196 case Calibration::DISTANCE_CALIBRATION_NONE:
4197 dump.append(INDENT4 "touch.distance.calibration: none\n");
4198 break;
4199 case Calibration::DISTANCE_CALIBRATION_SCALED:
4200 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4201 break;
4202 default:
4203 ALOG_ASSERT(false);
4204 }
4205
4206 if (mCalibration.haveDistanceScale) {
4207 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4208 mCalibration.distanceScale);
4209 }
4210
4211 switch (mCalibration.coverageCalibration) {
4212 case Calibration::COVERAGE_CALIBRATION_NONE:
4213 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4214 break;
4215 case Calibration::COVERAGE_CALIBRATION_BOX:
4216 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4217 break;
4218 default:
4219 ALOG_ASSERT(false);
4220 }
4221}
4222
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004223void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4224 dump.append(INDENT3 "Affine Transformation:\n");
4225
4226 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4227 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4228 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4229 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4230 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4231 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4232}
4233
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004234void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004235 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4236 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004237}
4238
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239void TouchInputMapper::reset(nsecs_t when) {
4240 mCursorButtonAccumulator.reset(getDevice());
4241 mCursorScrollAccumulator.reset(getDevice());
4242 mTouchButtonAccumulator.reset(getDevice());
4243
4244 mPointerVelocityControl.reset();
4245 mWheelXVelocityControl.reset();
4246 mWheelYVelocityControl.reset();
4247
Michael Wright842500e2015-03-13 17:32:02 -07004248 mRawStatesPending.clear();
4249 mCurrentRawState.clear();
4250 mCurrentCookedState.clear();
4251 mLastRawState.clear();
4252 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 mPointerUsage = POINTER_USAGE_NONE;
4254 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004255 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004256 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 mDownTime = 0;
4258
4259 mCurrentVirtualKey.down = false;
4260
4261 mPointerGesture.reset();
4262 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004263 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264
4265 if (mPointerController != NULL) {
4266 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4267 mPointerController->clearSpots();
4268 }
4269
4270 InputMapper::reset(when);
4271}
4272
Michael Wright842500e2015-03-13 17:32:02 -07004273void TouchInputMapper::resetExternalStylus() {
4274 mExternalStylusState.clear();
4275 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004276 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004277 mExternalStylusDataPending = false;
4278}
4279
Michael Wright43fd19f2015-04-21 19:02:58 +01004280void TouchInputMapper::clearStylusDataPendingFlags() {
4281 mExternalStylusDataPending = false;
4282 mExternalStylusFusionTimeout = LLONG_MAX;
4283}
4284
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285void TouchInputMapper::process(const RawEvent* rawEvent) {
4286 mCursorButtonAccumulator.process(rawEvent);
4287 mCursorScrollAccumulator.process(rawEvent);
4288 mTouchButtonAccumulator.process(rawEvent);
4289
4290 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4291 sync(rawEvent->when);
4292 }
4293}
4294
4295void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004296 const RawState* last = mRawStatesPending.isEmpty() ?
4297 &mCurrentRawState : &mRawStatesPending.top();
4298
4299 // Push a new state.
4300 mRawStatesPending.push();
4301 RawState* next = &mRawStatesPending.editTop();
4302 next->clear();
4303 next->when = when;
4304
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004306 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 | mCursorButtonAccumulator.getButtonState();
4308
Michael Wright842500e2015-03-13 17:32:02 -07004309 // Sync scroll
4310 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4311 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 mCursorScrollAccumulator.finishSync();
4313
Michael Wright842500e2015-03-13 17:32:02 -07004314 // Sync touch
4315 syncTouch(when, next);
4316
4317 // Assign pointer ids.
4318 if (!mHavePointerIds) {
4319 assignPointerIds(last, next);
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
4322#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004323 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4324 "hovering ids 0x%08x -> 0x%08x",
4325 last->rawPointerData.pointerCount,
4326 next->rawPointerData.pointerCount,
4327 last->rawPointerData.touchingIdBits.value,
4328 next->rawPointerData.touchingIdBits.value,
4329 last->rawPointerData.hoveringIdBits.value,
4330 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331#endif
4332
Michael Wright842500e2015-03-13 17:32:02 -07004333 processRawTouches(false /*timeout*/);
4334}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335
Michael Wright842500e2015-03-13 17:32:02 -07004336void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4338 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004339 mCurrentRawState.clear();
4340 mRawStatesPending.clear();
4341 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 }
4343
Michael Wright842500e2015-03-13 17:32:02 -07004344 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4345 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4346 // touching the current state will only observe the events that have been dispatched to the
4347 // rest of the pipeline.
4348 const size_t N = mRawStatesPending.size();
4349 size_t count;
4350 for(count = 0; count < N; count++) {
4351 const RawState& next = mRawStatesPending[count];
4352
4353 // A failure to assign the stylus id means that we're waiting on stylus data
4354 // and so should defer the rest of the pipeline.
4355 if (assignExternalStylusId(next, timeout)) {
4356 break;
4357 }
4358
4359 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004360 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004361 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004362 if (mCurrentRawState.when < mLastRawState.when) {
4363 mCurrentRawState.when = mLastRawState.when;
4364 }
Michael Wright842500e2015-03-13 17:32:02 -07004365 cookAndDispatch(mCurrentRawState.when);
4366 }
4367 if (count != 0) {
4368 mRawStatesPending.removeItemsAt(0, count);
4369 }
4370
Michael Wright842500e2015-03-13 17:32:02 -07004371 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004372 if (timeout) {
4373 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4374 clearStylusDataPendingFlags();
4375 mCurrentRawState.copyFrom(mLastRawState);
4376#if DEBUG_STYLUS_FUSION
4377 ALOGD("Timeout expired, synthesizing event with new stylus data");
4378#endif
4379 cookAndDispatch(when);
4380 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4381 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4382 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4383 }
Michael Wright842500e2015-03-13 17:32:02 -07004384 }
4385}
4386
4387void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4388 // Always start with a clean state.
4389 mCurrentCookedState.clear();
4390
4391 // Apply stylus buttons to current raw state.
4392 applyExternalStylusButtonState(when);
4393
4394 // Handle policy on initial down or hover events.
4395 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4396 && mCurrentRawState.rawPointerData.pointerCount != 0;
4397
4398 uint32_t policyFlags = 0;
4399 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4400 if (initialDown || buttonsPressed) {
4401 // If this is a touch screen, hide the pointer on an initial down.
4402 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4403 getContext()->fadePointer();
4404 }
4405
4406 if (mParameters.wake) {
4407 policyFlags |= POLICY_FLAG_WAKE;
4408 }
4409 }
4410
4411 // Consume raw off-screen touches before cooking pointer data.
4412 // If touches are consumed, subsequent code will not receive any pointer data.
4413 if (consumeRawTouches(when, policyFlags)) {
4414 mCurrentRawState.rawPointerData.clear();
4415 }
4416
4417 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4418 // with cooked pointer data that has the same ids and indices as the raw data.
4419 // The following code can use either the raw or cooked data, as needed.
4420 cookPointerData();
4421
4422 // Apply stylus pressure to current cooked state.
4423 applyExternalStylusTouchState(when);
4424
4425 // Synthesize key down from raw buttons if needed.
4426 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004427 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004428
4429 // Dispatch the touches either directly or by translation through a pointer on screen.
4430 if (mDeviceMode == DEVICE_MODE_POINTER) {
4431 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4432 !idBits.isEmpty(); ) {
4433 uint32_t id = idBits.clearFirstMarkedBit();
4434 const RawPointerData::Pointer& pointer =
4435 mCurrentRawState.rawPointerData.pointerForId(id);
4436 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4437 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4438 mCurrentCookedState.stylusIdBits.markBit(id);
4439 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4440 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4441 mCurrentCookedState.fingerIdBits.markBit(id);
4442 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4443 mCurrentCookedState.mouseIdBits.markBit(id);
4444 }
4445 }
4446 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4447 !idBits.isEmpty(); ) {
4448 uint32_t id = idBits.clearFirstMarkedBit();
4449 const RawPointerData::Pointer& pointer =
4450 mCurrentRawState.rawPointerData.pointerForId(id);
4451 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4452 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4453 mCurrentCookedState.stylusIdBits.markBit(id);
4454 }
4455 }
4456
4457 // Stylus takes precedence over all tools, then mouse, then finger.
4458 PointerUsage pointerUsage = mPointerUsage;
4459 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4460 mCurrentCookedState.mouseIdBits.clear();
4461 mCurrentCookedState.fingerIdBits.clear();
4462 pointerUsage = POINTER_USAGE_STYLUS;
4463 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4464 mCurrentCookedState.fingerIdBits.clear();
4465 pointerUsage = POINTER_USAGE_MOUSE;
4466 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4467 isPointerDown(mCurrentRawState.buttonState)) {
4468 pointerUsage = POINTER_USAGE_GESTURES;
4469 }
4470
4471 dispatchPointerUsage(when, policyFlags, pointerUsage);
4472 } else {
4473 if (mDeviceMode == DEVICE_MODE_DIRECT
4474 && mConfig.showTouches && mPointerController != NULL) {
4475 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4476 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4477
4478 mPointerController->setButtonState(mCurrentRawState.buttonState);
4479 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4480 mCurrentCookedState.cookedPointerData.idToIndex,
4481 mCurrentCookedState.cookedPointerData.touchingIdBits);
4482 }
4483
Michael Wright8e812822015-06-22 16:18:21 +01004484 if (!mCurrentMotionAborted) {
4485 dispatchButtonRelease(when, policyFlags);
4486 dispatchHoverExit(when, policyFlags);
4487 dispatchTouches(when, policyFlags);
4488 dispatchHoverEnterAndMove(when, policyFlags);
4489 dispatchButtonPress(when, policyFlags);
4490 }
4491
4492 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4493 mCurrentMotionAborted = false;
4494 }
Michael Wright842500e2015-03-13 17:32:02 -07004495 }
4496
4497 // Synthesize key up from raw buttons if needed.
4498 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004499 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500
4501 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004502 mCurrentRawState.rawVScroll = 0;
4503 mCurrentRawState.rawHScroll = 0;
4504
4505 // Copy current touch to last touch in preparation for the next cycle.
4506 mLastRawState.copyFrom(mCurrentRawState);
4507 mLastCookedState.copyFrom(mCurrentCookedState);
4508}
4509
4510void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004511 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004512 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4513 }
4514}
4515
4516void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004517 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4518 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004519
Michael Wright53dca3a2015-04-23 17:39:53 +01004520 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4521 float pressure = mExternalStylusState.pressure;
4522 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4523 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4524 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4525 }
4526 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4527 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4528
4529 PointerProperties& properties =
4530 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004531 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4532 properties.toolType = mExternalStylusState.toolType;
4533 }
4534 }
4535}
4536
4537bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4538 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4539 return false;
4540 }
4541
4542 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4543 && state.rawPointerData.pointerCount != 0;
4544 if (initialDown) {
4545 if (mExternalStylusState.pressure != 0.0f) {
4546#if DEBUG_STYLUS_FUSION
4547 ALOGD("Have both stylus and touch data, beginning fusion");
4548#endif
4549 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4550 } else if (timeout) {
4551#if DEBUG_STYLUS_FUSION
4552 ALOGD("Timeout expired, assuming touch is not a stylus.");
4553#endif
4554 resetExternalStylus();
4555 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004556 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4557 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004558 }
4559#if DEBUG_STYLUS_FUSION
4560 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004561 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004562#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004563 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004564 return true;
4565 }
4566 }
4567
4568 // Check if the stylus pointer has gone up.
4569 if (mExternalStylusId != -1 &&
4570 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4571#if DEBUG_STYLUS_FUSION
4572 ALOGD("Stylus pointer is going up");
4573#endif
4574 mExternalStylusId = -1;
4575 }
4576
4577 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578}
4579
4580void TouchInputMapper::timeoutExpired(nsecs_t when) {
4581 if (mDeviceMode == DEVICE_MODE_POINTER) {
4582 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4583 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4584 }
Michael Wright842500e2015-03-13 17:32:02 -07004585 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004586 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004587 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004588 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4589 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004590 }
4591 }
4592}
4593
4594void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004595 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004596 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004597 // We're either in the middle of a fused stream of data or we're waiting on data before
4598 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4599 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004600 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004601 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 }
4603}
4604
4605bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4606 // Check for release of a virtual key.
4607 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004608 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 // Pointer went up while virtual key was down.
4610 mCurrentVirtualKey.down = false;
4611 if (!mCurrentVirtualKey.ignored) {
4612#if DEBUG_VIRTUAL_KEYS
4613 ALOGD("VirtualKeys: Generating key up: 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 }
4620 return true;
4621 }
4622
Michael Wright842500e2015-03-13 17:32:02 -07004623 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4624 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4625 const RawPointerData::Pointer& pointer =
4626 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4628 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4629 // Pointer is still within the space of the virtual key.
4630 return true;
4631 }
4632 }
4633
4634 // Pointer left virtual key area or another pointer also went down.
4635 // Send key cancellation but do not consume the touch yet.
4636 // This is useful when the user swipes through from the virtual key area
4637 // into the main display surface.
4638 mCurrentVirtualKey.down = false;
4639 if (!mCurrentVirtualKey.ignored) {
4640#if DEBUG_VIRTUAL_KEYS
4641 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4642 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4643#endif
4644 dispatchVirtualKey(when, policyFlags,
4645 AKEY_EVENT_ACTION_UP,
4646 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4647 | AKEY_EVENT_FLAG_CANCELED);
4648 }
4649 }
4650
Michael Wright842500e2015-03-13 17:32:02 -07004651 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4652 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004654 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4655 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4657 // If exactly one pointer went down, check for virtual key hit.
4658 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004659 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4661 if (virtualKey) {
4662 mCurrentVirtualKey.down = true;
4663 mCurrentVirtualKey.downTime = when;
4664 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4665 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4666 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4667 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4668
4669 if (!mCurrentVirtualKey.ignored) {
4670#if DEBUG_VIRTUAL_KEYS
4671 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4672 mCurrentVirtualKey.keyCode,
4673 mCurrentVirtualKey.scanCode);
4674#endif
4675 dispatchVirtualKey(when, policyFlags,
4676 AKEY_EVENT_ACTION_DOWN,
4677 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4678 }
4679 }
4680 }
4681 return true;
4682 }
4683 }
4684
4685 // Disable all virtual key touches that happen within a short time interval of the
4686 // most recent touch within the screen area. The idea is to filter out stray
4687 // virtual key presses when interacting with the touch screen.
4688 //
4689 // Problems we're trying to solve:
4690 //
4691 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4692 // virtual key area that is implemented by a separate touch panel and accidentally
4693 // triggers a virtual key.
4694 //
4695 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4696 // area and accidentally triggers a virtual key. This often happens when virtual keys
4697 // are layed out below the screen near to where the on screen keyboard's space bar
4698 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004699 if (mConfig.virtualKeyQuietTime > 0 &&
4700 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4702 }
4703 return false;
4704}
4705
4706void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4707 int32_t keyEventAction, int32_t keyEventFlags) {
4708 int32_t keyCode = mCurrentVirtualKey.keyCode;
4709 int32_t scanCode = mCurrentVirtualKey.scanCode;
4710 nsecs_t downTime = mCurrentVirtualKey.downTime;
4711 int32_t metaState = mContext->getGlobalMetaState();
4712 policyFlags |= POLICY_FLAG_VIRTUAL;
4713
4714 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4715 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4716 getListener()->notifyKey(&args);
4717}
4718
Michael Wright8e812822015-06-22 16:18:21 +01004719void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4720 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4721 if (!currentIdBits.isEmpty()) {
4722 int32_t metaState = getContext()->getGlobalMetaState();
4723 int32_t buttonState = mCurrentCookedState.buttonState;
4724 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4725 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4726 mCurrentCookedState.cookedPointerData.pointerProperties,
4727 mCurrentCookedState.cookedPointerData.pointerCoords,
4728 mCurrentCookedState.cookedPointerData.idToIndex,
4729 currentIdBits, -1,
4730 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4731 mCurrentMotionAborted = true;
4732 }
4733}
4734
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004736 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4737 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004739 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740
4741 if (currentIdBits == lastIdBits) {
4742 if (!currentIdBits.isEmpty()) {
4743 // No pointer id changes so this is a move event.
4744 // The listener takes care of batching moves so we don't have to deal with that here.
4745 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004746 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004748 mCurrentCookedState.cookedPointerData.pointerProperties,
4749 mCurrentCookedState.cookedPointerData.pointerCoords,
4750 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 currentIdBits, -1,
4752 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4753 }
4754 } else {
4755 // There may be pointers going up and pointers going down and pointers moving
4756 // all at the same time.
4757 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4758 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4759 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4760 BitSet32 dispatchedIdBits(lastIdBits.value);
4761
4762 // Update last coordinates of pointers that have moved so that we observe the new
4763 // pointer positions at the same time as other pointers that have just gone up.
4764 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004765 mCurrentCookedState.cookedPointerData.pointerProperties,
4766 mCurrentCookedState.cookedPointerData.pointerCoords,
4767 mCurrentCookedState.cookedPointerData.idToIndex,
4768 mLastCookedState.cookedPointerData.pointerProperties,
4769 mLastCookedState.cookedPointerData.pointerCoords,
4770 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004772 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 moveNeeded = true;
4774 }
4775
4776 // Dispatch pointer up events.
4777 while (!upIdBits.isEmpty()) {
4778 uint32_t upId = upIdBits.clearFirstMarkedBit();
4779
4780 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004781 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004782 mLastCookedState.cookedPointerData.pointerProperties,
4783 mLastCookedState.cookedPointerData.pointerCoords,
4784 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004785 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 dispatchedIdBits.clearBit(upId);
4787 }
4788
4789 // Dispatch move events if any of the remaining pointers moved from their old locations.
4790 // Although applications receive new locations as part of individual pointer up
4791 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004792 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4794 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004795 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004796 mCurrentCookedState.cookedPointerData.pointerProperties,
4797 mCurrentCookedState.cookedPointerData.pointerCoords,
4798 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004799 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 }
4801
4802 // Dispatch pointer down events using the new pointer locations.
4803 while (!downIdBits.isEmpty()) {
4804 uint32_t downId = downIdBits.clearFirstMarkedBit();
4805 dispatchedIdBits.markBit(downId);
4806
4807 if (dispatchedIdBits.count() == 1) {
4808 // First pointer is going down. Set down time.
4809 mDownTime = when;
4810 }
4811
4812 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004813 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004814 mCurrentCookedState.cookedPointerData.pointerProperties,
4815 mCurrentCookedState.cookedPointerData.pointerCoords,
4816 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004817 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 }
4819 }
4820}
4821
4822void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4823 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004824 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4825 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 int32_t metaState = getContext()->getGlobalMetaState();
4827 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004828 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004829 mLastCookedState.cookedPointerData.pointerProperties,
4830 mLastCookedState.cookedPointerData.pointerCoords,
4831 mLastCookedState.cookedPointerData.idToIndex,
4832 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4834 mSentHoverEnter = false;
4835 }
4836}
4837
4838void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004839 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4840 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 int32_t metaState = getContext()->getGlobalMetaState();
4842 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004843 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004844 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004845 mCurrentCookedState.cookedPointerData.pointerProperties,
4846 mCurrentCookedState.cookedPointerData.pointerCoords,
4847 mCurrentCookedState.cookedPointerData.idToIndex,
4848 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4850 mSentHoverEnter = true;
4851 }
4852
4853 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004854 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004855 mCurrentRawState.buttonState, 0,
4856 mCurrentCookedState.cookedPointerData.pointerProperties,
4857 mCurrentCookedState.cookedPointerData.pointerCoords,
4858 mCurrentCookedState.cookedPointerData.idToIndex,
4859 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4861 }
4862}
4863
Michael Wright7b159c92015-05-14 14:48:03 +01004864void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4865 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4866 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4867 const int32_t metaState = getContext()->getGlobalMetaState();
4868 int32_t buttonState = mLastCookedState.buttonState;
4869 while (!releasedButtons.isEmpty()) {
4870 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4871 buttonState &= ~actionButton;
4872 dispatchMotion(when, policyFlags, mSource,
4873 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4874 0, metaState, buttonState, 0,
4875 mCurrentCookedState.cookedPointerData.pointerProperties,
4876 mCurrentCookedState.cookedPointerData.pointerCoords,
4877 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4878 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4879 }
4880}
4881
4882void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4883 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4884 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4885 const int32_t metaState = getContext()->getGlobalMetaState();
4886 int32_t buttonState = mLastCookedState.buttonState;
4887 while (!pressedButtons.isEmpty()) {
4888 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4889 buttonState |= actionButton;
4890 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4891 0, metaState, buttonState, 0,
4892 mCurrentCookedState.cookedPointerData.pointerProperties,
4893 mCurrentCookedState.cookedPointerData.pointerCoords,
4894 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4895 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4896 }
4897}
4898
4899const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4900 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4901 return cookedPointerData.touchingIdBits;
4902 }
4903 return cookedPointerData.hoveringIdBits;
4904}
4905
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004907 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
Michael Wright842500e2015-03-13 17:32:02 -07004909 mCurrentCookedState.cookedPointerData.clear();
4910 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4911 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4912 mCurrentRawState.rawPointerData.hoveringIdBits;
4913 mCurrentCookedState.cookedPointerData.touchingIdBits =
4914 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
Michael Wright7b159c92015-05-14 14:48:03 +01004916 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4917 mCurrentCookedState.buttonState = 0;
4918 } else {
4919 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4920 }
4921
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 // Walk through the the active pointers and map device coordinates onto
4923 // surface coordinates and adjust for display orientation.
4924 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004925 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926
4927 // Size
4928 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4929 switch (mCalibration.sizeCalibration) {
4930 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4931 case Calibration::SIZE_CALIBRATION_DIAMETER:
4932 case Calibration::SIZE_CALIBRATION_BOX:
4933 case Calibration::SIZE_CALIBRATION_AREA:
4934 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4935 touchMajor = in.touchMajor;
4936 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4937 toolMajor = in.toolMajor;
4938 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4939 size = mRawPointerAxes.touchMinor.valid
4940 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4941 } else if (mRawPointerAxes.touchMajor.valid) {
4942 toolMajor = touchMajor = in.touchMajor;
4943 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4944 ? in.touchMinor : in.touchMajor;
4945 size = mRawPointerAxes.touchMinor.valid
4946 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4947 } else if (mRawPointerAxes.toolMajor.valid) {
4948 touchMajor = toolMajor = in.toolMajor;
4949 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4950 ? in.toolMinor : in.toolMajor;
4951 size = mRawPointerAxes.toolMinor.valid
4952 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4953 } else {
4954 ALOG_ASSERT(false, "No touch or tool axes. "
4955 "Size calibration should have been resolved to NONE.");
4956 touchMajor = 0;
4957 touchMinor = 0;
4958 toolMajor = 0;
4959 toolMinor = 0;
4960 size = 0;
4961 }
4962
4963 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004964 uint32_t touchingCount =
4965 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 if (touchingCount > 1) {
4967 touchMajor /= touchingCount;
4968 touchMinor /= touchingCount;
4969 toolMajor /= touchingCount;
4970 toolMinor /= touchingCount;
4971 size /= touchingCount;
4972 }
4973 }
4974
4975 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4976 touchMajor *= mGeometricScale;
4977 touchMinor *= mGeometricScale;
4978 toolMajor *= mGeometricScale;
4979 toolMinor *= mGeometricScale;
4980 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4981 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4982 touchMinor = touchMajor;
4983 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4984 toolMinor = toolMajor;
4985 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4986 touchMinor = touchMajor;
4987 toolMinor = toolMajor;
4988 }
4989
4990 mCalibration.applySizeScaleAndBias(&touchMajor);
4991 mCalibration.applySizeScaleAndBias(&touchMinor);
4992 mCalibration.applySizeScaleAndBias(&toolMajor);
4993 mCalibration.applySizeScaleAndBias(&toolMinor);
4994 size *= mSizeScale;
4995 break;
4996 default:
4997 touchMajor = 0;
4998 touchMinor = 0;
4999 toolMajor = 0;
5000 toolMinor = 0;
5001 size = 0;
5002 break;
5003 }
5004
5005 // Pressure
5006 float pressure;
5007 switch (mCalibration.pressureCalibration) {
5008 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5009 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5010 pressure = in.pressure * mPressureScale;
5011 break;
5012 default:
5013 pressure = in.isHovering ? 0 : 1;
5014 break;
5015 }
5016
5017 // Tilt and Orientation
5018 float tilt;
5019 float orientation;
5020 if (mHaveTilt) {
5021 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5022 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5023 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5024 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5025 } else {
5026 tilt = 0;
5027
5028 switch (mCalibration.orientationCalibration) {
5029 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5030 orientation = in.orientation * mOrientationScale;
5031 break;
5032 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5033 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5034 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5035 if (c1 != 0 || c2 != 0) {
5036 orientation = atan2f(c1, c2) * 0.5f;
5037 float confidence = hypotf(c1, c2);
5038 float scale = 1.0f + confidence / 16.0f;
5039 touchMajor *= scale;
5040 touchMinor /= scale;
5041 toolMajor *= scale;
5042 toolMinor /= scale;
5043 } else {
5044 orientation = 0;
5045 }
5046 break;
5047 }
5048 default:
5049 orientation = 0;
5050 }
5051 }
5052
5053 // Distance
5054 float distance;
5055 switch (mCalibration.distanceCalibration) {
5056 case Calibration::DISTANCE_CALIBRATION_SCALED:
5057 distance = in.distance * mDistanceScale;
5058 break;
5059 default:
5060 distance = 0;
5061 }
5062
5063 // Coverage
5064 int32_t rawLeft, rawTop, rawRight, rawBottom;
5065 switch (mCalibration.coverageCalibration) {
5066 case Calibration::COVERAGE_CALIBRATION_BOX:
5067 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5068 rawRight = in.toolMinor & 0x0000ffff;
5069 rawBottom = in.toolMajor & 0x0000ffff;
5070 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5071 break;
5072 default:
5073 rawLeft = rawTop = rawRight = rawBottom = 0;
5074 break;
5075 }
5076
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005077 // Adjust X,Y coords for device calibration
5078 // TODO: Adjust coverage coords?
5079 float xTransformed = in.x, yTransformed = in.y;
5080 mAffineTransform.applyTo(xTransformed, yTransformed);
5081
5082 // Adjust X, Y, and coverage coords for surface orientation.
5083 float x, y;
5084 float left, top, right, bottom;
5085
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 switch (mSurfaceOrientation) {
5087 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005088 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5089 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5091 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5092 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5093 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5094 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005095 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5097 }
5098 break;
5099 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005100 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5101 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5103 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5104 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5105 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5106 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005107 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5109 }
5110 break;
5111 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005112 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5113 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5115 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5116 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5117 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5118 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005119 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5121 }
5122 break;
5123 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005124 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5125 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5127 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5128 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5129 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5130 break;
5131 }
5132
5133 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005134 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 out.clear();
5136 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5137 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5138 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5139 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5140 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5141 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5142 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5143 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5144 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5145 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5146 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5147 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5148 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5150 } else {
5151 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5152 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5153 }
5154
5155 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005156 PointerProperties& properties =
5157 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 uint32_t id = in.id;
5159 properties.clear();
5160 properties.id = id;
5161 properties.toolType = in.toolType;
5162
5163 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005164 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 }
5166}
5167
5168void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5169 PointerUsage pointerUsage) {
5170 if (pointerUsage != mPointerUsage) {
5171 abortPointerUsage(when, policyFlags);
5172 mPointerUsage = pointerUsage;
5173 }
5174
5175 switch (mPointerUsage) {
5176 case POINTER_USAGE_GESTURES:
5177 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5178 break;
5179 case POINTER_USAGE_STYLUS:
5180 dispatchPointerStylus(when, policyFlags);
5181 break;
5182 case POINTER_USAGE_MOUSE:
5183 dispatchPointerMouse(when, policyFlags);
5184 break;
5185 default:
5186 break;
5187 }
5188}
5189
5190void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5191 switch (mPointerUsage) {
5192 case POINTER_USAGE_GESTURES:
5193 abortPointerGestures(when, policyFlags);
5194 break;
5195 case POINTER_USAGE_STYLUS:
5196 abortPointerStylus(when, policyFlags);
5197 break;
5198 case POINTER_USAGE_MOUSE:
5199 abortPointerMouse(when, policyFlags);
5200 break;
5201 default:
5202 break;
5203 }
5204
5205 mPointerUsage = POINTER_USAGE_NONE;
5206}
5207
5208void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5209 bool isTimeout) {
5210 // Update current gesture coordinates.
5211 bool cancelPreviousGesture, finishPreviousGesture;
5212 bool sendEvents = preparePointerGestures(when,
5213 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5214 if (!sendEvents) {
5215 return;
5216 }
5217 if (finishPreviousGesture) {
5218 cancelPreviousGesture = false;
5219 }
5220
5221 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005222 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5223 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224 if (finishPreviousGesture || cancelPreviousGesture) {
5225 mPointerController->clearSpots();
5226 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005227
5228 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5229 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5230 mPointerGesture.currentGestureIdToIndex,
5231 mPointerGesture.currentGestureIdBits);
5232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 } else {
5234 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5235 }
5236
5237 // Show or hide the pointer if needed.
5238 switch (mPointerGesture.currentGestureMode) {
5239 case PointerGesture::NEUTRAL:
5240 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005241 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5242 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 // Remind the user of where the pointer is after finishing a gesture with spots.
5244 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5245 }
5246 break;
5247 case PointerGesture::TAP:
5248 case PointerGesture::TAP_DRAG:
5249 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5250 case PointerGesture::HOVER:
5251 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005252 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253 // Unfade the pointer when the current gesture manipulates the
5254 // area directly under the pointer.
5255 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5256 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 case PointerGesture::FREEFORM:
5258 // Fade the pointer when the current gesture manipulates a different
5259 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005260 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5262 } else {
5263 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5264 }
5265 break;
5266 }
5267
5268 // Send events!
5269 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005270 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271
5272 // Update last coordinates of pointers that have moved so that we observe the new
5273 // pointer positions at the same time as other pointers that have just gone up.
5274 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5275 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5276 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5277 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5278 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5279 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5280 bool moveNeeded = false;
5281 if (down && !cancelPreviousGesture && !finishPreviousGesture
5282 && !mPointerGesture.lastGestureIdBits.isEmpty()
5283 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5284 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5285 & mPointerGesture.lastGestureIdBits.value);
5286 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5287 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5288 mPointerGesture.lastGestureProperties,
5289 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5290 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005291 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292 moveNeeded = true;
5293 }
5294 }
5295
5296 // Send motion events for all pointers that went up or were canceled.
5297 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5298 if (!dispatchedGestureIdBits.isEmpty()) {
5299 if (cancelPreviousGesture) {
5300 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005301 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 AMOTION_EVENT_EDGE_FLAG_NONE,
5303 mPointerGesture.lastGestureProperties,
5304 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005305 dispatchedGestureIdBits, -1, 0,
5306 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307
5308 dispatchedGestureIdBits.clear();
5309 } else {
5310 BitSet32 upGestureIdBits;
5311 if (finishPreviousGesture) {
5312 upGestureIdBits = dispatchedGestureIdBits;
5313 } else {
5314 upGestureIdBits.value = dispatchedGestureIdBits.value
5315 & ~mPointerGesture.currentGestureIdBits.value;
5316 }
5317 while (!upGestureIdBits.isEmpty()) {
5318 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5319
5320 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005321 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5323 mPointerGesture.lastGestureProperties,
5324 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5325 dispatchedGestureIdBits, id,
5326 0, 0, mPointerGesture.downTime);
5327
5328 dispatchedGestureIdBits.clearBit(id);
5329 }
5330 }
5331 }
5332
5333 // Send motion events for all pointers that moved.
5334 if (moveNeeded) {
5335 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005336 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5337 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 mPointerGesture.currentGestureProperties,
5339 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5340 dispatchedGestureIdBits, -1,
5341 0, 0, mPointerGesture.downTime);
5342 }
5343
5344 // Send motion events for all pointers that went down.
5345 if (down) {
5346 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5347 & ~dispatchedGestureIdBits.value);
5348 while (!downGestureIdBits.isEmpty()) {
5349 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5350 dispatchedGestureIdBits.markBit(id);
5351
5352 if (dispatchedGestureIdBits.count() == 1) {
5353 mPointerGesture.downTime = when;
5354 }
5355
5356 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005357 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 mPointerGesture.currentGestureProperties,
5359 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5360 dispatchedGestureIdBits, id,
5361 0, 0, mPointerGesture.downTime);
5362 }
5363 }
5364
5365 // Send motion events for hover.
5366 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5367 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005368 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5370 mPointerGesture.currentGestureProperties,
5371 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5372 mPointerGesture.currentGestureIdBits, -1,
5373 0, 0, mPointerGesture.downTime);
5374 } else if (dispatchedGestureIdBits.isEmpty()
5375 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5376 // Synthesize a hover move event after all pointers go up to indicate that
5377 // the pointer is hovering again even if the user is not currently touching
5378 // the touch pad. This ensures that a view will receive a fresh hover enter
5379 // event after a tap.
5380 float x, y;
5381 mPointerController->getPosition(&x, &y);
5382
5383 PointerProperties pointerProperties;
5384 pointerProperties.clear();
5385 pointerProperties.id = 0;
5386 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5387
5388 PointerCoords pointerCoords;
5389 pointerCoords.clear();
5390 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5391 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5392
5393 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005394 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5396 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5397 0, 0, mPointerGesture.downTime);
5398 getListener()->notifyMotion(&args);
5399 }
5400
5401 // Update state.
5402 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5403 if (!down) {
5404 mPointerGesture.lastGestureIdBits.clear();
5405 } else {
5406 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5407 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5408 uint32_t id = idBits.clearFirstMarkedBit();
5409 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5410 mPointerGesture.lastGestureProperties[index].copyFrom(
5411 mPointerGesture.currentGestureProperties[index]);
5412 mPointerGesture.lastGestureCoords[index].copyFrom(
5413 mPointerGesture.currentGestureCoords[index]);
5414 mPointerGesture.lastGestureIdToIndex[id] = index;
5415 }
5416 }
5417}
5418
5419void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5420 // Cancel previously dispatches pointers.
5421 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5422 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005423 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005425 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 AMOTION_EVENT_EDGE_FLAG_NONE,
5427 mPointerGesture.lastGestureProperties,
5428 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5429 mPointerGesture.lastGestureIdBits, -1,
5430 0, 0, mPointerGesture.downTime);
5431 }
5432
5433 // Reset the current pointer gesture.
5434 mPointerGesture.reset();
5435 mPointerVelocityControl.reset();
5436
5437 // Remove any current spots.
5438 if (mPointerController != NULL) {
5439 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5440 mPointerController->clearSpots();
5441 }
5442}
5443
5444bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5445 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5446 *outCancelPreviousGesture = false;
5447 *outFinishPreviousGesture = false;
5448
5449 // Handle TAP timeout.
5450 if (isTimeout) {
5451#if DEBUG_GESTURES
5452 ALOGD("Gestures: Processing timeout");
5453#endif
5454
5455 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5456 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5457 // The tap/drag timeout has not yet expired.
5458 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5459 + mConfig.pointerGestureTapDragInterval);
5460 } else {
5461 // The tap is finished.
5462#if DEBUG_GESTURES
5463 ALOGD("Gestures: TAP finished");
5464#endif
5465 *outFinishPreviousGesture = true;
5466
5467 mPointerGesture.activeGestureId = -1;
5468 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5469 mPointerGesture.currentGestureIdBits.clear();
5470
5471 mPointerVelocityControl.reset();
5472 return true;
5473 }
5474 }
5475
5476 // We did not handle this timeout.
5477 return false;
5478 }
5479
Michael Wright842500e2015-03-13 17:32:02 -07005480 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5481 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482
5483 // Update the velocity tracker.
5484 {
5485 VelocityTracker::Position positions[MAX_POINTERS];
5486 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005487 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005489 const RawPointerData::Pointer& pointer =
5490 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 positions[count].x = pointer.x * mPointerXMovementScale;
5492 positions[count].y = pointer.y * mPointerYMovementScale;
5493 }
5494 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005495 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 }
5497
5498 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5499 // to NEUTRAL, then we should not generate tap event.
5500 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5501 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5502 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5503 mPointerGesture.resetTap();
5504 }
5505
5506 // Pick a new active touch id if needed.
5507 // Choose an arbitrary pointer that just went down, if there is one.
5508 // Otherwise choose an arbitrary remaining pointer.
5509 // This guarantees we always have an active touch id when there is at least one pointer.
5510 // We keep the same active touch id for as long as possible.
5511 bool activeTouchChanged = false;
5512 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5513 int32_t activeTouchId = lastActiveTouchId;
5514 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005515 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 activeTouchChanged = true;
5517 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005518 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 mPointerGesture.firstTouchTime = when;
5520 }
Michael Wright842500e2015-03-13 17:32:02 -07005521 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005523 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005525 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 } else {
5527 activeTouchId = mPointerGesture.activeTouchId = -1;
5528 }
5529 }
5530
5531 // Determine whether we are in quiet time.
5532 bool isQuietTime = false;
5533 if (activeTouchId < 0) {
5534 mPointerGesture.resetQuietTime();
5535 } else {
5536 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5537 if (!isQuietTime) {
5538 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5539 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5540 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5541 && currentFingerCount < 2) {
5542 // Enter quiet time when exiting swipe or freeform state.
5543 // This is to prevent accidentally entering the hover state and flinging the
5544 // pointer when finishing a swipe and there is still one pointer left onscreen.
5545 isQuietTime = true;
5546 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5547 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005548 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549 // Enter quiet time when releasing the button and there are still two or more
5550 // fingers down. This may indicate that one finger was used to press the button
5551 // but it has not gone up yet.
5552 isQuietTime = true;
5553 }
5554 if (isQuietTime) {
5555 mPointerGesture.quietTime = when;
5556 }
5557 }
5558 }
5559
5560 // Switch states based on button and pointer state.
5561 if (isQuietTime) {
5562 // Case 1: Quiet time. (QUIET)
5563#if DEBUG_GESTURES
5564 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5565 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5566#endif
5567 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5568 *outFinishPreviousGesture = true;
5569 }
5570
5571 mPointerGesture.activeGestureId = -1;
5572 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5573 mPointerGesture.currentGestureIdBits.clear();
5574
5575 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005576 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5578 // The pointer follows the active touch point.
5579 // Emit DOWN, MOVE, UP events at the pointer location.
5580 //
5581 // Only the active touch matters; other fingers are ignored. This policy helps
5582 // to handle the case where the user places a second finger on the touch pad
5583 // to apply the necessary force to depress an integrated button below the surface.
5584 // We don't want the second finger to be delivered to applications.
5585 //
5586 // For this to work well, we need to make sure to track the pointer that is really
5587 // active. If the user first puts one finger down to click then adds another
5588 // finger to drag then the active pointer should switch to the finger that is
5589 // being dragged.
5590#if DEBUG_GESTURES
5591 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5592 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5593#endif
5594 // Reset state when just starting.
5595 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5596 *outFinishPreviousGesture = true;
5597 mPointerGesture.activeGestureId = 0;
5598 }
5599
5600 // Switch pointers if needed.
5601 // Find the fastest pointer and follow it.
5602 if (activeTouchId >= 0 && currentFingerCount > 1) {
5603 int32_t bestId = -1;
5604 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005605 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 uint32_t id = idBits.clearFirstMarkedBit();
5607 float vx, vy;
5608 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5609 float speed = hypotf(vx, vy);
5610 if (speed > bestSpeed) {
5611 bestId = id;
5612 bestSpeed = speed;
5613 }
5614 }
5615 }
5616 if (bestId >= 0 && bestId != activeTouchId) {
5617 mPointerGesture.activeTouchId = activeTouchId = bestId;
5618 activeTouchChanged = true;
5619#if DEBUG_GESTURES
5620 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5621 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5622#endif
5623 }
5624 }
5625
Jun Mukaifa1706a2015-12-03 01:14:46 -08005626 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005627 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005629 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005631 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005632 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5633 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634
5635 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5636 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5637
5638 // Move the pointer using a relative motion.
5639 // When using spots, the click will occur at the position of the anchor
5640 // spot and all other spots will move there.
5641 mPointerController->move(deltaX, deltaY);
5642 } else {
5643 mPointerVelocityControl.reset();
5644 }
5645
5646 float x, y;
5647 mPointerController->getPosition(&x, &y);
5648
5649 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5650 mPointerGesture.currentGestureIdBits.clear();
5651 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5652 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5653 mPointerGesture.currentGestureProperties[0].clear();
5654 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5655 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5656 mPointerGesture.currentGestureCoords[0].clear();
5657 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5658 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5659 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5660 } else if (currentFingerCount == 0) {
5661 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5662 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5663 *outFinishPreviousGesture = true;
5664 }
5665
5666 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5667 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5668 bool tapped = false;
5669 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5670 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5671 && lastFingerCount == 1) {
5672 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5673 float x, y;
5674 mPointerController->getPosition(&x, &y);
5675 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5676 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5677#if DEBUG_GESTURES
5678 ALOGD("Gestures: TAP");
5679#endif
5680
5681 mPointerGesture.tapUpTime = when;
5682 getContext()->requestTimeoutAtTime(when
5683 + mConfig.pointerGestureTapDragInterval);
5684
5685 mPointerGesture.activeGestureId = 0;
5686 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5687 mPointerGesture.currentGestureIdBits.clear();
5688 mPointerGesture.currentGestureIdBits.markBit(
5689 mPointerGesture.activeGestureId);
5690 mPointerGesture.currentGestureIdToIndex[
5691 mPointerGesture.activeGestureId] = 0;
5692 mPointerGesture.currentGestureProperties[0].clear();
5693 mPointerGesture.currentGestureProperties[0].id =
5694 mPointerGesture.activeGestureId;
5695 mPointerGesture.currentGestureProperties[0].toolType =
5696 AMOTION_EVENT_TOOL_TYPE_FINGER;
5697 mPointerGesture.currentGestureCoords[0].clear();
5698 mPointerGesture.currentGestureCoords[0].setAxisValue(
5699 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5700 mPointerGesture.currentGestureCoords[0].setAxisValue(
5701 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5702 mPointerGesture.currentGestureCoords[0].setAxisValue(
5703 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5704
5705 tapped = true;
5706 } else {
5707#if DEBUG_GESTURES
5708 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5709 x - mPointerGesture.tapX,
5710 y - mPointerGesture.tapY);
5711#endif
5712 }
5713 } else {
5714#if DEBUG_GESTURES
5715 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5716 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5717 (when - mPointerGesture.tapDownTime) * 0.000001f);
5718 } else {
5719 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5720 }
5721#endif
5722 }
5723 }
5724
5725 mPointerVelocityControl.reset();
5726
5727 if (!tapped) {
5728#if DEBUG_GESTURES
5729 ALOGD("Gestures: NEUTRAL");
5730#endif
5731 mPointerGesture.activeGestureId = -1;
5732 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5733 mPointerGesture.currentGestureIdBits.clear();
5734 }
5735 } else if (currentFingerCount == 1) {
5736 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5737 // The pointer follows the active touch point.
5738 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5739 // When in TAP_DRAG, emit MOVE events at the pointer location.
5740 ALOG_ASSERT(activeTouchId >= 0);
5741
5742 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5743 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5744 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5745 float x, y;
5746 mPointerController->getPosition(&x, &y);
5747 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5748 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5749 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5750 } else {
5751#if DEBUG_GESTURES
5752 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5753 x - mPointerGesture.tapX,
5754 y - mPointerGesture.tapY);
5755#endif
5756 }
5757 } else {
5758#if DEBUG_GESTURES
5759 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5760 (when - mPointerGesture.tapUpTime) * 0.000001f);
5761#endif
5762 }
5763 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5764 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5765 }
5766
Jun Mukaifa1706a2015-12-03 01:14:46 -08005767 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005768 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005770 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005772 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005773 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5774 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775
5776 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5777 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5778
5779 // Move the pointer using a relative motion.
5780 // When using spots, the hover or drag will occur at the position of the anchor spot.
5781 mPointerController->move(deltaX, deltaY);
5782 } else {
5783 mPointerVelocityControl.reset();
5784 }
5785
5786 bool down;
5787 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5788#if DEBUG_GESTURES
5789 ALOGD("Gestures: TAP_DRAG");
5790#endif
5791 down = true;
5792 } else {
5793#if DEBUG_GESTURES
5794 ALOGD("Gestures: HOVER");
5795#endif
5796 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5797 *outFinishPreviousGesture = true;
5798 }
5799 mPointerGesture.activeGestureId = 0;
5800 down = false;
5801 }
5802
5803 float x, y;
5804 mPointerController->getPosition(&x, &y);
5805
5806 mPointerGesture.currentGestureIdBits.clear();
5807 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5808 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5809 mPointerGesture.currentGestureProperties[0].clear();
5810 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5811 mPointerGesture.currentGestureProperties[0].toolType =
5812 AMOTION_EVENT_TOOL_TYPE_FINGER;
5813 mPointerGesture.currentGestureCoords[0].clear();
5814 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5815 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5816 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5817 down ? 1.0f : 0.0f);
5818
5819 if (lastFingerCount == 0 && currentFingerCount != 0) {
5820 mPointerGesture.resetTap();
5821 mPointerGesture.tapDownTime = when;
5822 mPointerGesture.tapX = x;
5823 mPointerGesture.tapY = y;
5824 }
5825 } else {
5826 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5827 // We need to provide feedback for each finger that goes down so we cannot wait
5828 // for the fingers to move before deciding what to do.
5829 //
5830 // The ambiguous case is deciding what to do when there are two fingers down but they
5831 // have not moved enough to determine whether they are part of a drag or part of a
5832 // freeform gesture, or just a press or long-press at the pointer location.
5833 //
5834 // When there are two fingers we start with the PRESS hypothesis and we generate a
5835 // down at the pointer location.
5836 //
5837 // When the two fingers move enough or when additional fingers are added, we make
5838 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5839 ALOG_ASSERT(activeTouchId >= 0);
5840
5841 bool settled = when >= mPointerGesture.firstTouchTime
5842 + mConfig.pointerGestureMultitouchSettleInterval;
5843 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5844 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5845 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5846 *outFinishPreviousGesture = true;
5847 } else if (!settled && currentFingerCount > lastFingerCount) {
5848 // Additional pointers have gone down but not yet settled.
5849 // Reset the gesture.
5850#if DEBUG_GESTURES
5851 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5852 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5853 + mConfig.pointerGestureMultitouchSettleInterval - when)
5854 * 0.000001f);
5855#endif
5856 *outCancelPreviousGesture = true;
5857 } else {
5858 // Continue previous gesture.
5859 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5860 }
5861
5862 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5863 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5864 mPointerGesture.activeGestureId = 0;
5865 mPointerGesture.referenceIdBits.clear();
5866 mPointerVelocityControl.reset();
5867
5868 // Use the centroid and pointer location as the reference points for the gesture.
5869#if DEBUG_GESTURES
5870 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5871 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5872 + mConfig.pointerGestureMultitouchSettleInterval - when)
5873 * 0.000001f);
5874#endif
Michael Wright842500e2015-03-13 17:32:02 -07005875 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005876 &mPointerGesture.referenceTouchX,
5877 &mPointerGesture.referenceTouchY);
5878 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5879 &mPointerGesture.referenceGestureY);
5880 }
5881
5882 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005883 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5885 uint32_t id = idBits.clearFirstMarkedBit();
5886 mPointerGesture.referenceDeltas[id].dx = 0;
5887 mPointerGesture.referenceDeltas[id].dy = 0;
5888 }
Michael Wright842500e2015-03-13 17:32:02 -07005889 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890
5891 // Add delta for all fingers and calculate a common movement delta.
5892 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005893 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5894 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5896 bool first = (idBits == commonIdBits);
5897 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005898 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5899 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5901 delta.dx += cpd.x - lpd.x;
5902 delta.dy += cpd.y - lpd.y;
5903
5904 if (first) {
5905 commonDeltaX = delta.dx;
5906 commonDeltaY = delta.dy;
5907 } else {
5908 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5909 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5910 }
5911 }
5912
5913 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5914 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5915 float dist[MAX_POINTER_ID + 1];
5916 int32_t distOverThreshold = 0;
5917 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5918 uint32_t id = idBits.clearFirstMarkedBit();
5919 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5920 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5921 delta.dy * mPointerYZoomScale);
5922 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5923 distOverThreshold += 1;
5924 }
5925 }
5926
5927 // Only transition when at least two pointers have moved further than
5928 // the minimum distance threshold.
5929 if (distOverThreshold >= 2) {
5930 if (currentFingerCount > 2) {
5931 // There are more than two pointers, switch to FREEFORM.
5932#if DEBUG_GESTURES
5933 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5934 currentFingerCount);
5935#endif
5936 *outCancelPreviousGesture = true;
5937 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5938 } else {
5939 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005940 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 uint32_t id1 = idBits.clearFirstMarkedBit();
5942 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005943 const RawPointerData::Pointer& p1 =
5944 mCurrentRawState.rawPointerData.pointerForId(id1);
5945 const RawPointerData::Pointer& p2 =
5946 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5948 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5949 // There are two pointers but they are too far apart for a SWIPE,
5950 // switch to FREEFORM.
5951#if DEBUG_GESTURES
5952 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5953 mutualDistance, mPointerGestureMaxSwipeWidth);
5954#endif
5955 *outCancelPreviousGesture = true;
5956 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5957 } else {
5958 // There are two pointers. Wait for both pointers to start moving
5959 // before deciding whether this is a SWIPE or FREEFORM gesture.
5960 float dist1 = dist[id1];
5961 float dist2 = dist[id2];
5962 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5963 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5964 // Calculate the dot product of the displacement vectors.
5965 // When the vectors are oriented in approximately the same direction,
5966 // the angle betweeen them is near zero and the cosine of the angle
5967 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5968 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5969 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5970 float dx1 = delta1.dx * mPointerXZoomScale;
5971 float dy1 = delta1.dy * mPointerYZoomScale;
5972 float dx2 = delta2.dx * mPointerXZoomScale;
5973 float dy2 = delta2.dy * mPointerYZoomScale;
5974 float dot = dx1 * dx2 + dy1 * dy2;
5975 float cosine = dot / (dist1 * dist2); // denominator always > 0
5976 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5977 // Pointers are moving in the same direction. Switch to SWIPE.
5978#if DEBUG_GESTURES
5979 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5980 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5981 "cosine %0.3f >= %0.3f",
5982 dist1, mConfig.pointerGestureMultitouchMinDistance,
5983 dist2, mConfig.pointerGestureMultitouchMinDistance,
5984 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5985#endif
5986 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5987 } else {
5988 // Pointers are moving in different directions. Switch to FREEFORM.
5989#if DEBUG_GESTURES
5990 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5991 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5992 "cosine %0.3f < %0.3f",
5993 dist1, mConfig.pointerGestureMultitouchMinDistance,
5994 dist2, mConfig.pointerGestureMultitouchMinDistance,
5995 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5996#endif
5997 *outCancelPreviousGesture = true;
5998 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5999 }
6000 }
6001 }
6002 }
6003 }
6004 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6005 // Switch from SWIPE to FREEFORM if additional pointers go down.
6006 // Cancel previous gesture.
6007 if (currentFingerCount > 2) {
6008#if DEBUG_GESTURES
6009 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6010 currentFingerCount);
6011#endif
6012 *outCancelPreviousGesture = true;
6013 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6014 }
6015 }
6016
6017 // Move the reference points based on the overall group motion of the fingers
6018 // except in PRESS mode while waiting for a transition to occur.
6019 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6020 && (commonDeltaX || commonDeltaY)) {
6021 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6022 uint32_t id = idBits.clearFirstMarkedBit();
6023 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6024 delta.dx = 0;
6025 delta.dy = 0;
6026 }
6027
6028 mPointerGesture.referenceTouchX += commonDeltaX;
6029 mPointerGesture.referenceTouchY += commonDeltaY;
6030
6031 commonDeltaX *= mPointerXMovementScale;
6032 commonDeltaY *= mPointerYMovementScale;
6033
6034 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6035 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6036
6037 mPointerGesture.referenceGestureX += commonDeltaX;
6038 mPointerGesture.referenceGestureY += commonDeltaY;
6039 }
6040
6041 // Report gestures.
6042 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6043 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6044 // PRESS or SWIPE mode.
6045#if DEBUG_GESTURES
6046 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6047 "activeGestureId=%d, currentTouchPointerCount=%d",
6048 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6049#endif
6050 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6051
6052 mPointerGesture.currentGestureIdBits.clear();
6053 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6054 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6055 mPointerGesture.currentGestureProperties[0].clear();
6056 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6057 mPointerGesture.currentGestureProperties[0].toolType =
6058 AMOTION_EVENT_TOOL_TYPE_FINGER;
6059 mPointerGesture.currentGestureCoords[0].clear();
6060 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6061 mPointerGesture.referenceGestureX);
6062 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6063 mPointerGesture.referenceGestureY);
6064 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6065 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6066 // FREEFORM mode.
6067#if DEBUG_GESTURES
6068 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6069 "activeGestureId=%d, currentTouchPointerCount=%d",
6070 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6071#endif
6072 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6073
6074 mPointerGesture.currentGestureIdBits.clear();
6075
6076 BitSet32 mappedTouchIdBits;
6077 BitSet32 usedGestureIdBits;
6078 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6079 // Initially, assign the active gesture id to the active touch point
6080 // if there is one. No other touch id bits are mapped yet.
6081 if (!*outCancelPreviousGesture) {
6082 mappedTouchIdBits.markBit(activeTouchId);
6083 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6084 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6085 mPointerGesture.activeGestureId;
6086 } else {
6087 mPointerGesture.activeGestureId = -1;
6088 }
6089 } else {
6090 // Otherwise, assume we mapped all touches from the previous frame.
6091 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006092 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6093 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6095
6096 // Check whether we need to choose a new active gesture id because the
6097 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006098 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6099 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100 !upTouchIdBits.isEmpty(); ) {
6101 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6102 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6103 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6104 mPointerGesture.activeGestureId = -1;
6105 break;
6106 }
6107 }
6108 }
6109
6110#if DEBUG_GESTURES
6111 ALOGD("Gestures: FREEFORM follow up "
6112 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6113 "activeGestureId=%d",
6114 mappedTouchIdBits.value, usedGestureIdBits.value,
6115 mPointerGesture.activeGestureId);
6116#endif
6117
Michael Wright842500e2015-03-13 17:32:02 -07006118 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 for (uint32_t i = 0; i < currentFingerCount; i++) {
6120 uint32_t touchId = idBits.clearFirstMarkedBit();
6121 uint32_t gestureId;
6122 if (!mappedTouchIdBits.hasBit(touchId)) {
6123 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6124 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6125#if DEBUG_GESTURES
6126 ALOGD("Gestures: FREEFORM "
6127 "new mapping for touch id %d -> gesture id %d",
6128 touchId, gestureId);
6129#endif
6130 } else {
6131 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6132#if DEBUG_GESTURES
6133 ALOGD("Gestures: FREEFORM "
6134 "existing mapping for touch id %d -> gesture id %d",
6135 touchId, gestureId);
6136#endif
6137 }
6138 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6139 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6140
6141 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006142 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006143 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6144 * mPointerXZoomScale;
6145 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6146 * mPointerYZoomScale;
6147 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6148
6149 mPointerGesture.currentGestureProperties[i].clear();
6150 mPointerGesture.currentGestureProperties[i].id = gestureId;
6151 mPointerGesture.currentGestureProperties[i].toolType =
6152 AMOTION_EVENT_TOOL_TYPE_FINGER;
6153 mPointerGesture.currentGestureCoords[i].clear();
6154 mPointerGesture.currentGestureCoords[i].setAxisValue(
6155 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6156 mPointerGesture.currentGestureCoords[i].setAxisValue(
6157 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6158 mPointerGesture.currentGestureCoords[i].setAxisValue(
6159 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6160 }
6161
6162 if (mPointerGesture.activeGestureId < 0) {
6163 mPointerGesture.activeGestureId =
6164 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6165#if DEBUG_GESTURES
6166 ALOGD("Gestures: FREEFORM new "
6167 "activeGestureId=%d", mPointerGesture.activeGestureId);
6168#endif
6169 }
6170 }
6171 }
6172
Michael Wright842500e2015-03-13 17:32:02 -07006173 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006174
6175#if DEBUG_GESTURES
6176 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6177 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6178 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6179 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6180 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6181 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6182 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6183 uint32_t id = idBits.clearFirstMarkedBit();
6184 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6185 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6186 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6187 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6188 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6189 id, index, properties.toolType,
6190 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6191 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6192 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6193 }
6194 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6195 uint32_t id = idBits.clearFirstMarkedBit();
6196 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6197 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6198 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6199 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6200 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6201 id, index, properties.toolType,
6202 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6203 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6204 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6205 }
6206#endif
6207 return true;
6208}
6209
6210void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6211 mPointerSimple.currentCoords.clear();
6212 mPointerSimple.currentProperties.clear();
6213
6214 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006215 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6216 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6217 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6218 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6219 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 mPointerController->setPosition(x, y);
6221
Michael Wright842500e2015-03-13 17:32:02 -07006222 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223 down = !hovering;
6224
6225 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006226 mPointerSimple.currentCoords.copyFrom(
6227 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6229 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6230 mPointerSimple.currentProperties.id = 0;
6231 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006232 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 } else {
6234 down = false;
6235 hovering = false;
6236 }
6237
6238 dispatchPointerSimple(when, policyFlags, down, hovering);
6239}
6240
6241void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6242 abortPointerSimple(when, policyFlags);
6243}
6244
6245void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6246 mPointerSimple.currentCoords.clear();
6247 mPointerSimple.currentProperties.clear();
6248
6249 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006250 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6251 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6252 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006253 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006254 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6255 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006256 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006257 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006259 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006260 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261 * mPointerYMovementScale;
6262
6263 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6264 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6265
6266 mPointerController->move(deltaX, deltaY);
6267 } else {
6268 mPointerVelocityControl.reset();
6269 }
6270
Michael Wright842500e2015-03-13 17:32:02 -07006271 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272 hovering = !down;
6273
6274 float x, y;
6275 mPointerController->getPosition(&x, &y);
6276 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006277 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6279 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6280 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6281 hovering ? 0.0f : 1.0f);
6282 mPointerSimple.currentProperties.id = 0;
6283 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006284 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 } else {
6286 mPointerVelocityControl.reset();
6287
6288 down = false;
6289 hovering = false;
6290 }
6291
6292 dispatchPointerSimple(when, policyFlags, down, hovering);
6293}
6294
6295void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6296 abortPointerSimple(when, policyFlags);
6297
6298 mPointerVelocityControl.reset();
6299}
6300
6301void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6302 bool down, bool hovering) {
6303 int32_t metaState = getContext()->getGlobalMetaState();
6304
6305 if (mPointerController != NULL) {
6306 if (down || hovering) {
6307 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6308 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006309 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006310 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6311 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6312 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6313 }
6314 }
6315
6316 if (mPointerSimple.down && !down) {
6317 mPointerSimple.down = false;
6318
6319 // Send up.
6320 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006321 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322 mViewport.displayId,
6323 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6324 mOrientedXPrecision, mOrientedYPrecision,
6325 mPointerSimple.downTime);
6326 getListener()->notifyMotion(&args);
6327 }
6328
6329 if (mPointerSimple.hovering && !hovering) {
6330 mPointerSimple.hovering = false;
6331
6332 // Send hover exit.
6333 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006334 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335 mViewport.displayId,
6336 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6337 mOrientedXPrecision, mOrientedYPrecision,
6338 mPointerSimple.downTime);
6339 getListener()->notifyMotion(&args);
6340 }
6341
6342 if (down) {
6343 if (!mPointerSimple.down) {
6344 mPointerSimple.down = true;
6345 mPointerSimple.downTime = when;
6346
6347 // Send down.
6348 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006349 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006350 mViewport.displayId,
6351 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6352 mOrientedXPrecision, mOrientedYPrecision,
6353 mPointerSimple.downTime);
6354 getListener()->notifyMotion(&args);
6355 }
6356
6357 // Send move.
6358 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006359 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 mViewport.displayId,
6361 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6362 mOrientedXPrecision, mOrientedYPrecision,
6363 mPointerSimple.downTime);
6364 getListener()->notifyMotion(&args);
6365 }
6366
6367 if (hovering) {
6368 if (!mPointerSimple.hovering) {
6369 mPointerSimple.hovering = true;
6370
6371 // Send hover enter.
6372 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006373 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006374 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006375 mViewport.displayId,
6376 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6377 mOrientedXPrecision, mOrientedYPrecision,
6378 mPointerSimple.downTime);
6379 getListener()->notifyMotion(&args);
6380 }
6381
6382 // Send hover move.
6383 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006384 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006385 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 mViewport.displayId,
6387 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6388 mOrientedXPrecision, mOrientedYPrecision,
6389 mPointerSimple.downTime);
6390 getListener()->notifyMotion(&args);
6391 }
6392
Michael Wright842500e2015-03-13 17:32:02 -07006393 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6394 float vscroll = mCurrentRawState.rawVScroll;
6395 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396 mWheelYVelocityControl.move(when, NULL, &vscroll);
6397 mWheelXVelocityControl.move(when, &hscroll, NULL);
6398
6399 // Send scroll.
6400 PointerCoords pointerCoords;
6401 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6402 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6403 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6404
6405 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006406 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407 mViewport.displayId,
6408 1, &mPointerSimple.currentProperties, &pointerCoords,
6409 mOrientedXPrecision, mOrientedYPrecision,
6410 mPointerSimple.downTime);
6411 getListener()->notifyMotion(&args);
6412 }
6413
6414 // Save state.
6415 if (down || hovering) {
6416 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6417 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6418 } else {
6419 mPointerSimple.reset();
6420 }
6421}
6422
6423void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6424 mPointerSimple.currentCoords.clear();
6425 mPointerSimple.currentProperties.clear();
6426
6427 dispatchPointerSimple(when, policyFlags, false, false);
6428}
6429
6430void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006431 int32_t action, int32_t actionButton, int32_t flags,
6432 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006434 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6435 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006436 PointerCoords pointerCoords[MAX_POINTERS];
6437 PointerProperties pointerProperties[MAX_POINTERS];
6438 uint32_t pointerCount = 0;
6439 while (!idBits.isEmpty()) {
6440 uint32_t id = idBits.clearFirstMarkedBit();
6441 uint32_t index = idToIndex[id];
6442 pointerProperties[pointerCount].copyFrom(properties[index]);
6443 pointerCoords[pointerCount].copyFrom(coords[index]);
6444
6445 if (changedId >= 0 && id == uint32_t(changedId)) {
6446 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6447 }
6448
6449 pointerCount += 1;
6450 }
6451
6452 ALOG_ASSERT(pointerCount != 0);
6453
6454 if (changedId >= 0 && pointerCount == 1) {
6455 // Replace initial down and final up action.
6456 // We can compare the action without masking off the changed pointer index
6457 // because we know the index is 0.
6458 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6459 action = AMOTION_EVENT_ACTION_DOWN;
6460 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6461 action = AMOTION_EVENT_ACTION_UP;
6462 } else {
6463 // Can't happen.
6464 ALOG_ASSERT(false);
6465 }
6466 }
6467
6468 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006469 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006470 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6471 xPrecision, yPrecision, downTime);
6472 getListener()->notifyMotion(&args);
6473}
6474
6475bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6476 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6477 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6478 BitSet32 idBits) const {
6479 bool changed = false;
6480 while (!idBits.isEmpty()) {
6481 uint32_t id = idBits.clearFirstMarkedBit();
6482 uint32_t inIndex = inIdToIndex[id];
6483 uint32_t outIndex = outIdToIndex[id];
6484
6485 const PointerProperties& curInProperties = inProperties[inIndex];
6486 const PointerCoords& curInCoords = inCoords[inIndex];
6487 PointerProperties& curOutProperties = outProperties[outIndex];
6488 PointerCoords& curOutCoords = outCoords[outIndex];
6489
6490 if (curInProperties != curOutProperties) {
6491 curOutProperties.copyFrom(curInProperties);
6492 changed = true;
6493 }
6494
6495 if (curInCoords != curOutCoords) {
6496 curOutCoords.copyFrom(curInCoords);
6497 changed = true;
6498 }
6499 }
6500 return changed;
6501}
6502
6503void TouchInputMapper::fadePointer() {
6504 if (mPointerController != NULL) {
6505 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6506 }
6507}
6508
Jeff Brownc9aa6282015-02-11 19:03:28 -08006509void TouchInputMapper::cancelTouch(nsecs_t when) {
6510 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006511 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006512}
6513
Michael Wrightd02c5b62014-02-10 15:10:22 -08006514bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6515 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6516 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6517}
6518
6519const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6520 int32_t x, int32_t y) {
6521 size_t numVirtualKeys = mVirtualKeys.size();
6522 for (size_t i = 0; i < numVirtualKeys; i++) {
6523 const VirtualKey& virtualKey = mVirtualKeys[i];
6524
6525#if DEBUG_VIRTUAL_KEYS
6526 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6527 "left=%d, top=%d, right=%d, bottom=%d",
6528 x, y,
6529 virtualKey.keyCode, virtualKey.scanCode,
6530 virtualKey.hitLeft, virtualKey.hitTop,
6531 virtualKey.hitRight, virtualKey.hitBottom);
6532#endif
6533
6534 if (virtualKey.isHit(x, y)) {
6535 return & virtualKey;
6536 }
6537 }
6538
6539 return NULL;
6540}
6541
Michael Wright842500e2015-03-13 17:32:02 -07006542void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6543 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6544 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545
Michael Wright842500e2015-03-13 17:32:02 -07006546 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547
6548 if (currentPointerCount == 0) {
6549 // No pointers to assign.
6550 return;
6551 }
6552
6553 if (lastPointerCount == 0) {
6554 // All pointers are new.
6555 for (uint32_t i = 0; i < currentPointerCount; i++) {
6556 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006557 current->rawPointerData.pointers[i].id = id;
6558 current->rawPointerData.idToIndex[id] = i;
6559 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006560 }
6561 return;
6562 }
6563
6564 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006565 && current->rawPointerData.pointers[0].toolType
6566 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006568 uint32_t id = last->rawPointerData.pointers[0].id;
6569 current->rawPointerData.pointers[0].id = id;
6570 current->rawPointerData.idToIndex[id] = 0;
6571 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572 return;
6573 }
6574
6575 // General case.
6576 // We build a heap of squared euclidean distances between current and last pointers
6577 // associated with the current and last pointer indices. Then, we find the best
6578 // match (by distance) for each current pointer.
6579 // The pointers must have the same tool type but it is possible for them to
6580 // transition from hovering to touching or vice-versa while retaining the same id.
6581 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6582
6583 uint32_t heapSize = 0;
6584 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6585 currentPointerIndex++) {
6586 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6587 lastPointerIndex++) {
6588 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006589 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006591 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 if (currentPointer.toolType == lastPointer.toolType) {
6593 int64_t deltaX = currentPointer.x - lastPointer.x;
6594 int64_t deltaY = currentPointer.y - lastPointer.y;
6595
6596 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6597
6598 // Insert new element into the heap (sift up).
6599 heap[heapSize].currentPointerIndex = currentPointerIndex;
6600 heap[heapSize].lastPointerIndex = lastPointerIndex;
6601 heap[heapSize].distance = distance;
6602 heapSize += 1;
6603 }
6604 }
6605 }
6606
6607 // Heapify
6608 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6609 startIndex -= 1;
6610 for (uint32_t parentIndex = startIndex; ;) {
6611 uint32_t childIndex = parentIndex * 2 + 1;
6612 if (childIndex >= heapSize) {
6613 break;
6614 }
6615
6616 if (childIndex + 1 < heapSize
6617 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6618 childIndex += 1;
6619 }
6620
6621 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6622 break;
6623 }
6624
6625 swap(heap[parentIndex], heap[childIndex]);
6626 parentIndex = childIndex;
6627 }
6628 }
6629
6630#if DEBUG_POINTER_ASSIGNMENT
6631 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6632 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006633 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006634 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6635 heap[i].distance);
6636 }
6637#endif
6638
6639 // Pull matches out by increasing order of distance.
6640 // To avoid reassigning pointers that have already been matched, the loop keeps track
6641 // of which last and current pointers have been matched using the matchedXXXBits variables.
6642 // It also tracks the used pointer id bits.
6643 BitSet32 matchedLastBits(0);
6644 BitSet32 matchedCurrentBits(0);
6645 BitSet32 usedIdBits(0);
6646 bool first = true;
6647 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6648 while (heapSize > 0) {
6649 if (first) {
6650 // The first time through the loop, we just consume the root element of
6651 // the heap (the one with smallest distance).
6652 first = false;
6653 } else {
6654 // Previous iterations consumed the root element of the heap.
6655 // Pop root element off of the heap (sift down).
6656 heap[0] = heap[heapSize];
6657 for (uint32_t parentIndex = 0; ;) {
6658 uint32_t childIndex = parentIndex * 2 + 1;
6659 if (childIndex >= heapSize) {
6660 break;
6661 }
6662
6663 if (childIndex + 1 < heapSize
6664 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6665 childIndex += 1;
6666 }
6667
6668 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6669 break;
6670 }
6671
6672 swap(heap[parentIndex], heap[childIndex]);
6673 parentIndex = childIndex;
6674 }
6675
6676#if DEBUG_POINTER_ASSIGNMENT
6677 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6678 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006679 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006680 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6681 heap[i].distance);
6682 }
6683#endif
6684 }
6685
6686 heapSize -= 1;
6687
6688 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6689 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6690
6691 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6692 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6693
6694 matchedCurrentBits.markBit(currentPointerIndex);
6695 matchedLastBits.markBit(lastPointerIndex);
6696
Michael Wright842500e2015-03-13 17:32:02 -07006697 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6698 current->rawPointerData.pointers[currentPointerIndex].id = id;
6699 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6700 current->rawPointerData.markIdBit(id,
6701 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006702 usedIdBits.markBit(id);
6703
6704#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006705 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6706 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006707 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6708#endif
6709 break;
6710 }
6711 }
6712
6713 // Assign fresh ids to pointers that were not matched in the process.
6714 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6715 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6716 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6717
Michael Wright842500e2015-03-13 17:32:02 -07006718 current->rawPointerData.pointers[currentPointerIndex].id = id;
6719 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6720 current->rawPointerData.markIdBit(id,
6721 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006722
6723#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006724 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006725#endif
6726 }
6727}
6728
6729int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6730 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6731 return AKEY_STATE_VIRTUAL;
6732 }
6733
6734 size_t numVirtualKeys = mVirtualKeys.size();
6735 for (size_t i = 0; i < numVirtualKeys; i++) {
6736 const VirtualKey& virtualKey = mVirtualKeys[i];
6737 if (virtualKey.keyCode == keyCode) {
6738 return AKEY_STATE_UP;
6739 }
6740 }
6741
6742 return AKEY_STATE_UNKNOWN;
6743}
6744
6745int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6746 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6747 return AKEY_STATE_VIRTUAL;
6748 }
6749
6750 size_t numVirtualKeys = mVirtualKeys.size();
6751 for (size_t i = 0; i < numVirtualKeys; i++) {
6752 const VirtualKey& virtualKey = mVirtualKeys[i];
6753 if (virtualKey.scanCode == scanCode) {
6754 return AKEY_STATE_UP;
6755 }
6756 }
6757
6758 return AKEY_STATE_UNKNOWN;
6759}
6760
6761bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6762 const int32_t* keyCodes, uint8_t* outFlags) {
6763 size_t numVirtualKeys = mVirtualKeys.size();
6764 for (size_t i = 0; i < numVirtualKeys; i++) {
6765 const VirtualKey& virtualKey = mVirtualKeys[i];
6766
6767 for (size_t i = 0; i < numCodes; i++) {
6768 if (virtualKey.keyCode == keyCodes[i]) {
6769 outFlags[i] = 1;
6770 }
6771 }
6772 }
6773
6774 return true;
6775}
6776
6777
6778// --- SingleTouchInputMapper ---
6779
6780SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6781 TouchInputMapper(device) {
6782}
6783
6784SingleTouchInputMapper::~SingleTouchInputMapper() {
6785}
6786
6787void SingleTouchInputMapper::reset(nsecs_t when) {
6788 mSingleTouchMotionAccumulator.reset(getDevice());
6789
6790 TouchInputMapper::reset(when);
6791}
6792
6793void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6794 TouchInputMapper::process(rawEvent);
6795
6796 mSingleTouchMotionAccumulator.process(rawEvent);
6797}
6798
Michael Wright842500e2015-03-13 17:32:02 -07006799void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006800 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006801 outState->rawPointerData.pointerCount = 1;
6802 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006803
6804 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6805 && (mTouchButtonAccumulator.isHovering()
6806 || (mRawPointerAxes.pressure.valid
6807 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006808 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006809
Michael Wright842500e2015-03-13 17:32:02 -07006810 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006811 outPointer.id = 0;
6812 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6813 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6814 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6815 outPointer.touchMajor = 0;
6816 outPointer.touchMinor = 0;
6817 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6818 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6819 outPointer.orientation = 0;
6820 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6821 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6822 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6823 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6824 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6825 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6826 }
6827 outPointer.isHovering = isHovering;
6828 }
6829}
6830
6831void SingleTouchInputMapper::configureRawPointerAxes() {
6832 TouchInputMapper::configureRawPointerAxes();
6833
6834 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6835 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6836 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6837 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6838 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6839 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6840 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6841}
6842
6843bool SingleTouchInputMapper::hasStylus() const {
6844 return mTouchButtonAccumulator.hasStylus();
6845}
6846
6847
6848// --- MultiTouchInputMapper ---
6849
6850MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6851 TouchInputMapper(device) {
6852}
6853
6854MultiTouchInputMapper::~MultiTouchInputMapper() {
6855}
6856
6857void MultiTouchInputMapper::reset(nsecs_t when) {
6858 mMultiTouchMotionAccumulator.reset(getDevice());
6859
6860 mPointerIdBits.clear();
6861
6862 TouchInputMapper::reset(when);
6863}
6864
6865void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6866 TouchInputMapper::process(rawEvent);
6867
6868 mMultiTouchMotionAccumulator.process(rawEvent);
6869}
6870
Michael Wright842500e2015-03-13 17:32:02 -07006871void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006872 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6873 size_t outCount = 0;
6874 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006875 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006876
6877 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6878 const MultiTouchMotionAccumulator::Slot* inSlot =
6879 mMultiTouchMotionAccumulator.getSlot(inIndex);
6880 if (!inSlot->isInUse()) {
6881 continue;
6882 }
6883
6884 if (outCount >= MAX_POINTERS) {
6885#if DEBUG_POINTERS
6886 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6887 "ignoring the rest.",
6888 getDeviceName().string(), MAX_POINTERS);
6889#endif
6890 break; // too many fingers!
6891 }
6892
Michael Wright842500e2015-03-13 17:32:02 -07006893 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006894 outPointer.x = inSlot->getX();
6895 outPointer.y = inSlot->getY();
6896 outPointer.pressure = inSlot->getPressure();
6897 outPointer.touchMajor = inSlot->getTouchMajor();
6898 outPointer.touchMinor = inSlot->getTouchMinor();
6899 outPointer.toolMajor = inSlot->getToolMajor();
6900 outPointer.toolMinor = inSlot->getToolMinor();
6901 outPointer.orientation = inSlot->getOrientation();
6902 outPointer.distance = inSlot->getDistance();
6903 outPointer.tiltX = 0;
6904 outPointer.tiltY = 0;
6905
6906 outPointer.toolType = inSlot->getToolType();
6907 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6908 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6909 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6910 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6911 }
6912 }
6913
6914 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6915 && (mTouchButtonAccumulator.isHovering()
6916 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6917 outPointer.isHovering = isHovering;
6918
6919 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006920 if (mHavePointerIds) {
6921 int32_t trackingId = inSlot->getTrackingId();
6922 int32_t id = -1;
6923 if (trackingId >= 0) {
6924 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6925 uint32_t n = idBits.clearFirstMarkedBit();
6926 if (mPointerTrackingIdMap[n] == trackingId) {
6927 id = n;
6928 }
6929 }
6930
6931 if (id < 0 && !mPointerIdBits.isFull()) {
6932 id = mPointerIdBits.markFirstUnmarkedBit();
6933 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006934 }
Michael Wright842500e2015-03-13 17:32:02 -07006935 }
gaoshang1a632de2016-08-24 10:23:50 +08006936 if (id < 0) {
6937 mHavePointerIds = false;
6938 outState->rawPointerData.clearIdBits();
6939 newPointerIdBits.clear();
6940 } else {
6941 outPointer.id = id;
6942 outState->rawPointerData.idToIndex[id] = outCount;
6943 outState->rawPointerData.markIdBit(id, isHovering);
6944 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006945 }
Michael Wright842500e2015-03-13 17:32:02 -07006946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006947 outCount += 1;
6948 }
6949
Michael Wright842500e2015-03-13 17:32:02 -07006950 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006951 mPointerIdBits = newPointerIdBits;
6952
6953 mMultiTouchMotionAccumulator.finishSync();
6954}
6955
6956void MultiTouchInputMapper::configureRawPointerAxes() {
6957 TouchInputMapper::configureRawPointerAxes();
6958
6959 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6960 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6961 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6962 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6963 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6964 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6965 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6966 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6967 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6968 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6969 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6970
6971 if (mRawPointerAxes.trackingId.valid
6972 && mRawPointerAxes.slot.valid
6973 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6974 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6975 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006976 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6977 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006978 getDeviceName().string(), slotCount, MAX_SLOTS);
6979 slotCount = MAX_SLOTS;
6980 }
6981 mMultiTouchMotionAccumulator.configure(getDevice(),
6982 slotCount, true /*usingSlotsProtocol*/);
6983 } else {
6984 mMultiTouchMotionAccumulator.configure(getDevice(),
6985 MAX_POINTERS, false /*usingSlotsProtocol*/);
6986 }
6987}
6988
6989bool MultiTouchInputMapper::hasStylus() const {
6990 return mMultiTouchMotionAccumulator.hasStylus()
6991 || mTouchButtonAccumulator.hasStylus();
6992}
6993
Michael Wright842500e2015-03-13 17:32:02 -07006994// --- ExternalStylusInputMapper
6995
6996ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6997 InputMapper(device) {
6998
6999}
7000
7001uint32_t ExternalStylusInputMapper::getSources() {
7002 return AINPUT_SOURCE_STYLUS;
7003}
7004
7005void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7006 InputMapper::populateDeviceInfo(info);
7007 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7008 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7009}
7010
7011void ExternalStylusInputMapper::dump(String8& dump) {
7012 dump.append(INDENT2 "External Stylus Input Mapper:\n");
7013 dump.append(INDENT3 "Raw Stylus Axes:\n");
7014 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
7015 dump.append(INDENT3 "Stylus State:\n");
7016 dumpStylusState(dump, mStylusState);
7017}
7018
7019void ExternalStylusInputMapper::configure(nsecs_t when,
7020 const InputReaderConfiguration* config, uint32_t changes) {
7021 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7022 mTouchButtonAccumulator.configure(getDevice());
7023}
7024
7025void ExternalStylusInputMapper::reset(nsecs_t when) {
7026 InputDevice* device = getDevice();
7027 mSingleTouchMotionAccumulator.reset(device);
7028 mTouchButtonAccumulator.reset(device);
7029 InputMapper::reset(when);
7030}
7031
7032void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7033 mSingleTouchMotionAccumulator.process(rawEvent);
7034 mTouchButtonAccumulator.process(rawEvent);
7035
7036 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7037 sync(rawEvent->when);
7038 }
7039}
7040
7041void ExternalStylusInputMapper::sync(nsecs_t when) {
7042 mStylusState.clear();
7043
7044 mStylusState.when = when;
7045
Michael Wright45ccacf2015-04-21 19:01:58 +01007046 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7047 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7048 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7049 }
7050
Michael Wright842500e2015-03-13 17:32:02 -07007051 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7052 if (mRawPressureAxis.valid) {
7053 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7054 } else if (mTouchButtonAccumulator.isToolActive()) {
7055 mStylusState.pressure = 1.0f;
7056 } else {
7057 mStylusState.pressure = 0.0f;
7058 }
7059
7060 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007061
7062 mContext->dispatchExternalStylusState(mStylusState);
7063}
7064
Michael Wrightd02c5b62014-02-10 15:10:22 -08007065
7066// --- JoystickInputMapper ---
7067
7068JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7069 InputMapper(device) {
7070}
7071
7072JoystickInputMapper::~JoystickInputMapper() {
7073}
7074
7075uint32_t JoystickInputMapper::getSources() {
7076 return AINPUT_SOURCE_JOYSTICK;
7077}
7078
7079void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7080 InputMapper::populateDeviceInfo(info);
7081
7082 for (size_t i = 0; i < mAxes.size(); i++) {
7083 const Axis& axis = mAxes.valueAt(i);
7084 addMotionRange(axis.axisInfo.axis, axis, info);
7085
7086 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7087 addMotionRange(axis.axisInfo.highAxis, axis, info);
7088
7089 }
7090 }
7091}
7092
7093void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7094 InputDeviceInfo* info) {
7095 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7096 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7097 /* In order to ease the transition for developers from using the old axes
7098 * to the newer, more semantically correct axes, we'll continue to register
7099 * the old axes as duplicates of their corresponding new ones. */
7100 int32_t compatAxis = getCompatAxis(axisId);
7101 if (compatAxis >= 0) {
7102 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7103 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7104 }
7105}
7106
7107/* A mapping from axes the joystick actually has to the axes that should be
7108 * artificially created for compatibility purposes.
7109 * Returns -1 if no compatibility axis is needed. */
7110int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7111 switch(axis) {
7112 case AMOTION_EVENT_AXIS_LTRIGGER:
7113 return AMOTION_EVENT_AXIS_BRAKE;
7114 case AMOTION_EVENT_AXIS_RTRIGGER:
7115 return AMOTION_EVENT_AXIS_GAS;
7116 }
7117 return -1;
7118}
7119
7120void JoystickInputMapper::dump(String8& dump) {
7121 dump.append(INDENT2 "Joystick Input Mapper:\n");
7122
7123 dump.append(INDENT3 "Axes:\n");
7124 size_t numAxes = mAxes.size();
7125 for (size_t i = 0; i < numAxes; i++) {
7126 const Axis& axis = mAxes.valueAt(i);
7127 const char* label = getAxisLabel(axis.axisInfo.axis);
7128 if (label) {
7129 dump.appendFormat(INDENT4 "%s", label);
7130 } else {
7131 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7132 }
7133 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7134 label = getAxisLabel(axis.axisInfo.highAxis);
7135 if (label) {
7136 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7137 } else {
7138 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7139 axis.axisInfo.splitValue);
7140 }
7141 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7142 dump.append(" (invert)");
7143 }
7144
7145 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7146 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7147 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7148 "highScale=%0.5f, highOffset=%0.5f\n",
7149 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7150 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7151 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7152 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7153 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7154 }
7155}
7156
7157void JoystickInputMapper::configure(nsecs_t when,
7158 const InputReaderConfiguration* config, uint32_t changes) {
7159 InputMapper::configure(when, config, changes);
7160
7161 if (!changes) { // first time only
7162 // Collect all axes.
7163 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7164 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7165 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7166 continue; // axis must be claimed by a different device
7167 }
7168
7169 RawAbsoluteAxisInfo rawAxisInfo;
7170 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7171 if (rawAxisInfo.valid) {
7172 // Map axis.
7173 AxisInfo axisInfo;
7174 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7175 if (!explicitlyMapped) {
7176 // Axis is not explicitly mapped, will choose a generic axis later.
7177 axisInfo.mode = AxisInfo::MODE_NORMAL;
7178 axisInfo.axis = -1;
7179 }
7180
7181 // Apply flat override.
7182 int32_t rawFlat = axisInfo.flatOverride < 0
7183 ? rawAxisInfo.flat : axisInfo.flatOverride;
7184
7185 // Calculate scaling factors and limits.
7186 Axis axis;
7187 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7188 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7189 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7190 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7191 scale, 0.0f, highScale, 0.0f,
7192 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7193 rawAxisInfo.resolution * scale);
7194 } else if (isCenteredAxis(axisInfo.axis)) {
7195 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7196 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7197 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7198 scale, offset, scale, offset,
7199 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7200 rawAxisInfo.resolution * scale);
7201 } else {
7202 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7203 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7204 scale, 0.0f, scale, 0.0f,
7205 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7206 rawAxisInfo.resolution * scale);
7207 }
7208
7209 // To eliminate noise while the joystick is at rest, filter out small variations
7210 // in axis values up front.
7211 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7212
7213 mAxes.add(abs, axis);
7214 }
7215 }
7216
7217 // If there are too many axes, start dropping them.
7218 // Prefer to keep explicitly mapped axes.
7219 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007220 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007221 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7222 pruneAxes(true);
7223 pruneAxes(false);
7224 }
7225
7226 // Assign generic axis ids to remaining axes.
7227 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7228 size_t numAxes = mAxes.size();
7229 for (size_t i = 0; i < numAxes; i++) {
7230 Axis& axis = mAxes.editValueAt(i);
7231 if (axis.axisInfo.axis < 0) {
7232 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7233 && haveAxis(nextGenericAxisId)) {
7234 nextGenericAxisId += 1;
7235 }
7236
7237 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7238 axis.axisInfo.axis = nextGenericAxisId;
7239 nextGenericAxisId += 1;
7240 } else {
7241 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7242 "have already been assigned to other axes.",
7243 getDeviceName().string(), mAxes.keyAt(i));
7244 mAxes.removeItemsAt(i--);
7245 numAxes -= 1;
7246 }
7247 }
7248 }
7249 }
7250}
7251
7252bool JoystickInputMapper::haveAxis(int32_t axisId) {
7253 size_t numAxes = mAxes.size();
7254 for (size_t i = 0; i < numAxes; i++) {
7255 const Axis& axis = mAxes.valueAt(i);
7256 if (axis.axisInfo.axis == axisId
7257 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7258 && axis.axisInfo.highAxis == axisId)) {
7259 return true;
7260 }
7261 }
7262 return false;
7263}
7264
7265void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7266 size_t i = mAxes.size();
7267 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7268 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7269 continue;
7270 }
7271 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7272 getDeviceName().string(), mAxes.keyAt(i));
7273 mAxes.removeItemsAt(i);
7274 }
7275}
7276
7277bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7278 switch (axis) {
7279 case AMOTION_EVENT_AXIS_X:
7280 case AMOTION_EVENT_AXIS_Y:
7281 case AMOTION_EVENT_AXIS_Z:
7282 case AMOTION_EVENT_AXIS_RX:
7283 case AMOTION_EVENT_AXIS_RY:
7284 case AMOTION_EVENT_AXIS_RZ:
7285 case AMOTION_EVENT_AXIS_HAT_X:
7286 case AMOTION_EVENT_AXIS_HAT_Y:
7287 case AMOTION_EVENT_AXIS_ORIENTATION:
7288 case AMOTION_EVENT_AXIS_RUDDER:
7289 case AMOTION_EVENT_AXIS_WHEEL:
7290 return true;
7291 default:
7292 return false;
7293 }
7294}
7295
7296void JoystickInputMapper::reset(nsecs_t when) {
7297 // Recenter all axes.
7298 size_t numAxes = mAxes.size();
7299 for (size_t i = 0; i < numAxes; i++) {
7300 Axis& axis = mAxes.editValueAt(i);
7301 axis.resetValue();
7302 }
7303
7304 InputMapper::reset(when);
7305}
7306
7307void JoystickInputMapper::process(const RawEvent* rawEvent) {
7308 switch (rawEvent->type) {
7309 case EV_ABS: {
7310 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7311 if (index >= 0) {
7312 Axis& axis = mAxes.editValueAt(index);
7313 float newValue, highNewValue;
7314 switch (axis.axisInfo.mode) {
7315 case AxisInfo::MODE_INVERT:
7316 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7317 * axis.scale + axis.offset;
7318 highNewValue = 0.0f;
7319 break;
7320 case AxisInfo::MODE_SPLIT:
7321 if (rawEvent->value < axis.axisInfo.splitValue) {
7322 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7323 * axis.scale + axis.offset;
7324 highNewValue = 0.0f;
7325 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7326 newValue = 0.0f;
7327 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7328 * axis.highScale + axis.highOffset;
7329 } else {
7330 newValue = 0.0f;
7331 highNewValue = 0.0f;
7332 }
7333 break;
7334 default:
7335 newValue = rawEvent->value * axis.scale + axis.offset;
7336 highNewValue = 0.0f;
7337 break;
7338 }
7339 axis.newValue = newValue;
7340 axis.highNewValue = highNewValue;
7341 }
7342 break;
7343 }
7344
7345 case EV_SYN:
7346 switch (rawEvent->code) {
7347 case SYN_REPORT:
7348 sync(rawEvent->when, false /*force*/);
7349 break;
7350 }
7351 break;
7352 }
7353}
7354
7355void JoystickInputMapper::sync(nsecs_t when, bool force) {
7356 if (!filterAxes(force)) {
7357 return;
7358 }
7359
7360 int32_t metaState = mContext->getGlobalMetaState();
7361 int32_t buttonState = 0;
7362
7363 PointerProperties pointerProperties;
7364 pointerProperties.clear();
7365 pointerProperties.id = 0;
7366 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7367
7368 PointerCoords pointerCoords;
7369 pointerCoords.clear();
7370
7371 size_t numAxes = mAxes.size();
7372 for (size_t i = 0; i < numAxes; i++) {
7373 const Axis& axis = mAxes.valueAt(i);
7374 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7375 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7376 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7377 axis.highCurrentValue);
7378 }
7379 }
7380
7381 // Moving a joystick axis should not wake the device because joysticks can
7382 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7383 // button will likely wake the device.
7384 // TODO: Use the input device configuration to control this behavior more finely.
7385 uint32_t policyFlags = 0;
7386
7387 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007388 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007389 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7390 getListener()->notifyMotion(&args);
7391}
7392
7393void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7394 int32_t axis, float value) {
7395 pointerCoords->setAxisValue(axis, value);
7396 /* In order to ease the transition for developers from using the old axes
7397 * to the newer, more semantically correct axes, we'll continue to produce
7398 * values for the old axes as mirrors of the value of their corresponding
7399 * new axes. */
7400 int32_t compatAxis = getCompatAxis(axis);
7401 if (compatAxis >= 0) {
7402 pointerCoords->setAxisValue(compatAxis, value);
7403 }
7404}
7405
7406bool JoystickInputMapper::filterAxes(bool force) {
7407 bool atLeastOneSignificantChange = force;
7408 size_t numAxes = mAxes.size();
7409 for (size_t i = 0; i < numAxes; i++) {
7410 Axis& axis = mAxes.editValueAt(i);
7411 if (force || hasValueChangedSignificantly(axis.filter,
7412 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7413 axis.currentValue = axis.newValue;
7414 atLeastOneSignificantChange = true;
7415 }
7416 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7417 if (force || hasValueChangedSignificantly(axis.filter,
7418 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7419 axis.highCurrentValue = axis.highNewValue;
7420 atLeastOneSignificantChange = true;
7421 }
7422 }
7423 }
7424 return atLeastOneSignificantChange;
7425}
7426
7427bool JoystickInputMapper::hasValueChangedSignificantly(
7428 float filter, float newValue, float currentValue, float min, float max) {
7429 if (newValue != currentValue) {
7430 // Filter out small changes in value unless the value is converging on the axis
7431 // bounds or center point. This is intended to reduce the amount of information
7432 // sent to applications by particularly noisy joysticks (such as PS3).
7433 if (fabs(newValue - currentValue) > filter
7434 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7435 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7436 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7437 return true;
7438 }
7439 }
7440 return false;
7441}
7442
7443bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7444 float filter, float newValue, float currentValue, float thresholdValue) {
7445 float newDistance = fabs(newValue - thresholdValue);
7446 if (newDistance < filter) {
7447 float oldDistance = fabs(currentValue - thresholdValue);
7448 if (newDistance < oldDistance) {
7449 return true;
7450 }
7451 }
7452 return false;
7453}
7454
7455} // namespace android