blob: 591f8d7e6163441653e36d418dec4b28b19b3e83 [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();
Ivan Lozano96f12992017-11-09 14:45:38 -08001177 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178#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 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001205 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207}
1208
1209void InputDevice::timeoutExpired(nsecs_t when) {
1210 size_t numMappers = mMappers.size();
1211 for (size_t i = 0; i < numMappers; i++) {
1212 InputMapper* mapper = mMappers[i];
1213 mapper->timeoutExpired(when);
1214 }
1215}
1216
Michael Wright842500e2015-03-13 17:32:02 -07001217void InputDevice::updateExternalStylusState(const StylusState& state) {
1218 size_t numMappers = mMappers.size();
1219 for (size_t i = 0; i < numMappers; i++) {
1220 InputMapper* mapper = mMappers[i];
1221 mapper->updateExternalStylusState(state);
1222 }
1223}
1224
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1226 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001227 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 size_t numMappers = mMappers.size();
1229 for (size_t i = 0; i < numMappers; i++) {
1230 InputMapper* mapper = mMappers[i];
1231 mapper->populateDeviceInfo(outDeviceInfo);
1232 }
1233}
1234
1235int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1236 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1237}
1238
1239int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1240 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1241}
1242
1243int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1244 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1245}
1246
1247int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1248 int32_t result = AKEY_STATE_UNKNOWN;
1249 size_t numMappers = mMappers.size();
1250 for (size_t i = 0; i < numMappers; i++) {
1251 InputMapper* mapper = mMappers[i];
1252 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1253 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1254 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1255 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1256 if (currentResult >= AKEY_STATE_DOWN) {
1257 return currentResult;
1258 } else if (currentResult == AKEY_STATE_UP) {
1259 result = currentResult;
1260 }
1261 }
1262 }
1263 return result;
1264}
1265
1266bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1267 const int32_t* keyCodes, uint8_t* outFlags) {
1268 bool result = false;
1269 size_t numMappers = mMappers.size();
1270 for (size_t i = 0; i < numMappers; i++) {
1271 InputMapper* mapper = mMappers[i];
1272 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1273 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1274 }
1275 }
1276 return result;
1277}
1278
1279void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1280 int32_t token) {
1281 size_t numMappers = mMappers.size();
1282 for (size_t i = 0; i < numMappers; i++) {
1283 InputMapper* mapper = mMappers[i];
1284 mapper->vibrate(pattern, patternSize, repeat, token);
1285 }
1286}
1287
1288void InputDevice::cancelVibrate(int32_t token) {
1289 size_t numMappers = mMappers.size();
1290 for (size_t i = 0; i < numMappers; i++) {
1291 InputMapper* mapper = mMappers[i];
1292 mapper->cancelVibrate(token);
1293 }
1294}
1295
Jeff Brownc9aa6282015-02-11 19:03:28 -08001296void InputDevice::cancelTouch(nsecs_t when) {
1297 size_t numMappers = mMappers.size();
1298 for (size_t i = 0; i < numMappers; i++) {
1299 InputMapper* mapper = mMappers[i];
1300 mapper->cancelTouch(when);
1301 }
1302}
1303
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304int32_t InputDevice::getMetaState() {
1305 int32_t result = 0;
1306 size_t numMappers = mMappers.size();
1307 for (size_t i = 0; i < numMappers; i++) {
1308 InputMapper* mapper = mMappers[i];
1309 result |= mapper->getMetaState();
1310 }
1311 return result;
1312}
1313
Andrii Kulian763a3a42016-03-08 10:46:16 -08001314void InputDevice::updateMetaState(int32_t keyCode) {
1315 size_t numMappers = mMappers.size();
1316 for (size_t i = 0; i < numMappers; i++) {
1317 mMappers[i]->updateMetaState(keyCode);
1318 }
1319}
1320
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321void InputDevice::fadePointer() {
1322 size_t numMappers = mMappers.size();
1323 for (size_t i = 0; i < numMappers; i++) {
1324 InputMapper* mapper = mMappers[i];
1325 mapper->fadePointer();
1326 }
1327}
1328
1329void InputDevice::bumpGeneration() {
1330 mGeneration = mContext->bumpGeneration();
1331}
1332
1333void InputDevice::notifyReset(nsecs_t when) {
1334 NotifyDeviceResetArgs args(when, mId);
1335 mContext->getListener()->notifyDeviceReset(&args);
1336}
1337
1338
1339// --- CursorButtonAccumulator ---
1340
1341CursorButtonAccumulator::CursorButtonAccumulator() {
1342 clearButtons();
1343}
1344
1345void CursorButtonAccumulator::reset(InputDevice* device) {
1346 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1347 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1348 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1349 mBtnBack = device->isKeyPressed(BTN_BACK);
1350 mBtnSide = device->isKeyPressed(BTN_SIDE);
1351 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1352 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1353 mBtnTask = device->isKeyPressed(BTN_TASK);
1354}
1355
1356void CursorButtonAccumulator::clearButtons() {
1357 mBtnLeft = 0;
1358 mBtnRight = 0;
1359 mBtnMiddle = 0;
1360 mBtnBack = 0;
1361 mBtnSide = 0;
1362 mBtnForward = 0;
1363 mBtnExtra = 0;
1364 mBtnTask = 0;
1365}
1366
1367void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1368 if (rawEvent->type == EV_KEY) {
1369 switch (rawEvent->code) {
1370 case BTN_LEFT:
1371 mBtnLeft = rawEvent->value;
1372 break;
1373 case BTN_RIGHT:
1374 mBtnRight = rawEvent->value;
1375 break;
1376 case BTN_MIDDLE:
1377 mBtnMiddle = rawEvent->value;
1378 break;
1379 case BTN_BACK:
1380 mBtnBack = rawEvent->value;
1381 break;
1382 case BTN_SIDE:
1383 mBtnSide = rawEvent->value;
1384 break;
1385 case BTN_FORWARD:
1386 mBtnForward = rawEvent->value;
1387 break;
1388 case BTN_EXTRA:
1389 mBtnExtra = rawEvent->value;
1390 break;
1391 case BTN_TASK:
1392 mBtnTask = rawEvent->value;
1393 break;
1394 }
1395 }
1396}
1397
1398uint32_t CursorButtonAccumulator::getButtonState() const {
1399 uint32_t result = 0;
1400 if (mBtnLeft) {
1401 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1402 }
1403 if (mBtnRight) {
1404 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1405 }
1406 if (mBtnMiddle) {
1407 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1408 }
1409 if (mBtnBack || mBtnSide) {
1410 result |= AMOTION_EVENT_BUTTON_BACK;
1411 }
1412 if (mBtnForward || mBtnExtra) {
1413 result |= AMOTION_EVENT_BUTTON_FORWARD;
1414 }
1415 return result;
1416}
1417
1418
1419// --- CursorMotionAccumulator ---
1420
1421CursorMotionAccumulator::CursorMotionAccumulator() {
1422 clearRelativeAxes();
1423}
1424
1425void CursorMotionAccumulator::reset(InputDevice* device) {
1426 clearRelativeAxes();
1427}
1428
1429void CursorMotionAccumulator::clearRelativeAxes() {
1430 mRelX = 0;
1431 mRelY = 0;
1432}
1433
1434void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1435 if (rawEvent->type == EV_REL) {
1436 switch (rawEvent->code) {
1437 case REL_X:
1438 mRelX = rawEvent->value;
1439 break;
1440 case REL_Y:
1441 mRelY = rawEvent->value;
1442 break;
1443 }
1444 }
1445}
1446
1447void CursorMotionAccumulator::finishSync() {
1448 clearRelativeAxes();
1449}
1450
1451
1452// --- CursorScrollAccumulator ---
1453
1454CursorScrollAccumulator::CursorScrollAccumulator() :
1455 mHaveRelWheel(false), mHaveRelHWheel(false) {
1456 clearRelativeAxes();
1457}
1458
1459void CursorScrollAccumulator::configure(InputDevice* device) {
1460 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1461 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1462}
1463
1464void CursorScrollAccumulator::reset(InputDevice* device) {
1465 clearRelativeAxes();
1466}
1467
1468void CursorScrollAccumulator::clearRelativeAxes() {
1469 mRelWheel = 0;
1470 mRelHWheel = 0;
1471}
1472
1473void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1474 if (rawEvent->type == EV_REL) {
1475 switch (rawEvent->code) {
1476 case REL_WHEEL:
1477 mRelWheel = rawEvent->value;
1478 break;
1479 case REL_HWHEEL:
1480 mRelHWheel = rawEvent->value;
1481 break;
1482 }
1483 }
1484}
1485
1486void CursorScrollAccumulator::finishSync() {
1487 clearRelativeAxes();
1488}
1489
1490
1491// --- TouchButtonAccumulator ---
1492
1493TouchButtonAccumulator::TouchButtonAccumulator() :
1494 mHaveBtnTouch(false), mHaveStylus(false) {
1495 clearButtons();
1496}
1497
1498void TouchButtonAccumulator::configure(InputDevice* device) {
1499 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1500 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1501 || device->hasKey(BTN_TOOL_RUBBER)
1502 || device->hasKey(BTN_TOOL_BRUSH)
1503 || device->hasKey(BTN_TOOL_PENCIL)
1504 || device->hasKey(BTN_TOOL_AIRBRUSH);
1505}
1506
1507void TouchButtonAccumulator::reset(InputDevice* device) {
1508 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1509 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001510 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1511 mBtnStylus2 =
1512 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1514 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1515 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1516 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1517 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1518 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1519 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1520 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1521 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1522 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1523 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1524}
1525
1526void TouchButtonAccumulator::clearButtons() {
1527 mBtnTouch = 0;
1528 mBtnStylus = 0;
1529 mBtnStylus2 = 0;
1530 mBtnToolFinger = 0;
1531 mBtnToolPen = 0;
1532 mBtnToolRubber = 0;
1533 mBtnToolBrush = 0;
1534 mBtnToolPencil = 0;
1535 mBtnToolAirbrush = 0;
1536 mBtnToolMouse = 0;
1537 mBtnToolLens = 0;
1538 mBtnToolDoubleTap = 0;
1539 mBtnToolTripleTap = 0;
1540 mBtnToolQuadTap = 0;
1541}
1542
1543void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1544 if (rawEvent->type == EV_KEY) {
1545 switch (rawEvent->code) {
1546 case BTN_TOUCH:
1547 mBtnTouch = rawEvent->value;
1548 break;
1549 case BTN_STYLUS:
1550 mBtnStylus = rawEvent->value;
1551 break;
1552 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001553 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 mBtnStylus2 = rawEvent->value;
1555 break;
1556 case BTN_TOOL_FINGER:
1557 mBtnToolFinger = rawEvent->value;
1558 break;
1559 case BTN_TOOL_PEN:
1560 mBtnToolPen = rawEvent->value;
1561 break;
1562 case BTN_TOOL_RUBBER:
1563 mBtnToolRubber = rawEvent->value;
1564 break;
1565 case BTN_TOOL_BRUSH:
1566 mBtnToolBrush = rawEvent->value;
1567 break;
1568 case BTN_TOOL_PENCIL:
1569 mBtnToolPencil = rawEvent->value;
1570 break;
1571 case BTN_TOOL_AIRBRUSH:
1572 mBtnToolAirbrush = rawEvent->value;
1573 break;
1574 case BTN_TOOL_MOUSE:
1575 mBtnToolMouse = rawEvent->value;
1576 break;
1577 case BTN_TOOL_LENS:
1578 mBtnToolLens = rawEvent->value;
1579 break;
1580 case BTN_TOOL_DOUBLETAP:
1581 mBtnToolDoubleTap = rawEvent->value;
1582 break;
1583 case BTN_TOOL_TRIPLETAP:
1584 mBtnToolTripleTap = rawEvent->value;
1585 break;
1586 case BTN_TOOL_QUADTAP:
1587 mBtnToolQuadTap = rawEvent->value;
1588 break;
1589 }
1590 }
1591}
1592
1593uint32_t TouchButtonAccumulator::getButtonState() const {
1594 uint32_t result = 0;
1595 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001596 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 }
1598 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001599 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 }
1601 return result;
1602}
1603
1604int32_t TouchButtonAccumulator::getToolType() const {
1605 if (mBtnToolMouse || mBtnToolLens) {
1606 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1607 }
1608 if (mBtnToolRubber) {
1609 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1610 }
1611 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1612 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1613 }
1614 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1615 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1616 }
1617 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1618}
1619
1620bool TouchButtonAccumulator::isToolActive() const {
1621 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1622 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1623 || mBtnToolMouse || mBtnToolLens
1624 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1625}
1626
1627bool TouchButtonAccumulator::isHovering() const {
1628 return mHaveBtnTouch && !mBtnTouch;
1629}
1630
1631bool TouchButtonAccumulator::hasStylus() const {
1632 return mHaveStylus;
1633}
1634
1635
1636// --- RawPointerAxes ---
1637
1638RawPointerAxes::RawPointerAxes() {
1639 clear();
1640}
1641
1642void RawPointerAxes::clear() {
1643 x.clear();
1644 y.clear();
1645 pressure.clear();
1646 touchMajor.clear();
1647 touchMinor.clear();
1648 toolMajor.clear();
1649 toolMinor.clear();
1650 orientation.clear();
1651 distance.clear();
1652 tiltX.clear();
1653 tiltY.clear();
1654 trackingId.clear();
1655 slot.clear();
1656}
1657
1658
1659// --- RawPointerData ---
1660
1661RawPointerData::RawPointerData() {
1662 clear();
1663}
1664
1665void RawPointerData::clear() {
1666 pointerCount = 0;
1667 clearIdBits();
1668}
1669
1670void RawPointerData::copyFrom(const RawPointerData& other) {
1671 pointerCount = other.pointerCount;
1672 hoveringIdBits = other.hoveringIdBits;
1673 touchingIdBits = other.touchingIdBits;
1674
1675 for (uint32_t i = 0; i < pointerCount; i++) {
1676 pointers[i] = other.pointers[i];
1677
1678 int id = pointers[i].id;
1679 idToIndex[id] = other.idToIndex[id];
1680 }
1681}
1682
1683void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1684 float x = 0, y = 0;
1685 uint32_t count = touchingIdBits.count();
1686 if (count) {
1687 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1688 uint32_t id = idBits.clearFirstMarkedBit();
1689 const Pointer& pointer = pointerForId(id);
1690 x += pointer.x;
1691 y += pointer.y;
1692 }
1693 x /= count;
1694 y /= count;
1695 }
1696 *outX = x;
1697 *outY = y;
1698}
1699
1700
1701// --- CookedPointerData ---
1702
1703CookedPointerData::CookedPointerData() {
1704 clear();
1705}
1706
1707void CookedPointerData::clear() {
1708 pointerCount = 0;
1709 hoveringIdBits.clear();
1710 touchingIdBits.clear();
1711}
1712
1713void CookedPointerData::copyFrom(const CookedPointerData& other) {
1714 pointerCount = other.pointerCount;
1715 hoveringIdBits = other.hoveringIdBits;
1716 touchingIdBits = other.touchingIdBits;
1717
1718 for (uint32_t i = 0; i < pointerCount; i++) {
1719 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1720 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1721
1722 int id = pointerProperties[i].id;
1723 idToIndex[id] = other.idToIndex[id];
1724 }
1725}
1726
1727
1728// --- SingleTouchMotionAccumulator ---
1729
1730SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1731 clearAbsoluteAxes();
1732}
1733
1734void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1735 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1736 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1737 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1738 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1739 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1740 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1741 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1742}
1743
1744void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1745 mAbsX = 0;
1746 mAbsY = 0;
1747 mAbsPressure = 0;
1748 mAbsToolWidth = 0;
1749 mAbsDistance = 0;
1750 mAbsTiltX = 0;
1751 mAbsTiltY = 0;
1752}
1753
1754void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1755 if (rawEvent->type == EV_ABS) {
1756 switch (rawEvent->code) {
1757 case ABS_X:
1758 mAbsX = rawEvent->value;
1759 break;
1760 case ABS_Y:
1761 mAbsY = rawEvent->value;
1762 break;
1763 case ABS_PRESSURE:
1764 mAbsPressure = rawEvent->value;
1765 break;
1766 case ABS_TOOL_WIDTH:
1767 mAbsToolWidth = rawEvent->value;
1768 break;
1769 case ABS_DISTANCE:
1770 mAbsDistance = rawEvent->value;
1771 break;
1772 case ABS_TILT_X:
1773 mAbsTiltX = rawEvent->value;
1774 break;
1775 case ABS_TILT_Y:
1776 mAbsTiltY = rawEvent->value;
1777 break;
1778 }
1779 }
1780}
1781
1782
1783// --- MultiTouchMotionAccumulator ---
1784
1785MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1786 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1787 mHaveStylus(false) {
1788}
1789
1790MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1791 delete[] mSlots;
1792}
1793
1794void MultiTouchMotionAccumulator::configure(InputDevice* device,
1795 size_t slotCount, bool usingSlotsProtocol) {
1796 mSlotCount = slotCount;
1797 mUsingSlotsProtocol = usingSlotsProtocol;
1798 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1799
1800 delete[] mSlots;
1801 mSlots = new Slot[slotCount];
1802}
1803
1804void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1805 // Unfortunately there is no way to read the initial contents of the slots.
1806 // So when we reset the accumulator, we must assume they are all zeroes.
1807 if (mUsingSlotsProtocol) {
1808 // Query the driver for the current slot index and use it as the initial slot
1809 // before we start reading events from the device. It is possible that the
1810 // current slot index will not be the same as it was when the first event was
1811 // written into the evdev buffer, which means the input mapper could start
1812 // out of sync with the initial state of the events in the evdev buffer.
1813 // In the extremely unlikely case that this happens, the data from
1814 // two slots will be confused until the next ABS_MT_SLOT event is received.
1815 // This can cause the touch point to "jump", but at least there will be
1816 // no stuck touches.
1817 int32_t initialSlot;
1818 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1819 ABS_MT_SLOT, &initialSlot);
1820 if (status) {
1821 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1822 initialSlot = -1;
1823 }
1824 clearSlots(initialSlot);
1825 } else {
1826 clearSlots(-1);
1827 }
1828}
1829
1830void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1831 if (mSlots) {
1832 for (size_t i = 0; i < mSlotCount; i++) {
1833 mSlots[i].clear();
1834 }
1835 }
1836 mCurrentSlot = initialSlot;
1837}
1838
1839void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1840 if (rawEvent->type == EV_ABS) {
1841 bool newSlot = false;
1842 if (mUsingSlotsProtocol) {
1843 if (rawEvent->code == ABS_MT_SLOT) {
1844 mCurrentSlot = rawEvent->value;
1845 newSlot = true;
1846 }
1847 } else if (mCurrentSlot < 0) {
1848 mCurrentSlot = 0;
1849 }
1850
1851 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1852#if DEBUG_POINTERS
1853 if (newSlot) {
1854 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001855 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 mCurrentSlot, mSlotCount - 1);
1857 }
1858#endif
1859 } else {
1860 Slot* slot = &mSlots[mCurrentSlot];
1861
1862 switch (rawEvent->code) {
1863 case ABS_MT_POSITION_X:
1864 slot->mInUse = true;
1865 slot->mAbsMTPositionX = rawEvent->value;
1866 break;
1867 case ABS_MT_POSITION_Y:
1868 slot->mInUse = true;
1869 slot->mAbsMTPositionY = rawEvent->value;
1870 break;
1871 case ABS_MT_TOUCH_MAJOR:
1872 slot->mInUse = true;
1873 slot->mAbsMTTouchMajor = rawEvent->value;
1874 break;
1875 case ABS_MT_TOUCH_MINOR:
1876 slot->mInUse = true;
1877 slot->mAbsMTTouchMinor = rawEvent->value;
1878 slot->mHaveAbsMTTouchMinor = true;
1879 break;
1880 case ABS_MT_WIDTH_MAJOR:
1881 slot->mInUse = true;
1882 slot->mAbsMTWidthMajor = rawEvent->value;
1883 break;
1884 case ABS_MT_WIDTH_MINOR:
1885 slot->mInUse = true;
1886 slot->mAbsMTWidthMinor = rawEvent->value;
1887 slot->mHaveAbsMTWidthMinor = true;
1888 break;
1889 case ABS_MT_ORIENTATION:
1890 slot->mInUse = true;
1891 slot->mAbsMTOrientation = rawEvent->value;
1892 break;
1893 case ABS_MT_TRACKING_ID:
1894 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1895 // The slot is no longer in use but it retains its previous contents,
1896 // which may be reused for subsequent touches.
1897 slot->mInUse = false;
1898 } else {
1899 slot->mInUse = true;
1900 slot->mAbsMTTrackingId = rawEvent->value;
1901 }
1902 break;
1903 case ABS_MT_PRESSURE:
1904 slot->mInUse = true;
1905 slot->mAbsMTPressure = rawEvent->value;
1906 break;
1907 case ABS_MT_DISTANCE:
1908 slot->mInUse = true;
1909 slot->mAbsMTDistance = rawEvent->value;
1910 break;
1911 case ABS_MT_TOOL_TYPE:
1912 slot->mInUse = true;
1913 slot->mAbsMTToolType = rawEvent->value;
1914 slot->mHaveAbsMTToolType = true;
1915 break;
1916 }
1917 }
1918 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1919 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1920 mCurrentSlot += 1;
1921 }
1922}
1923
1924void MultiTouchMotionAccumulator::finishSync() {
1925 if (!mUsingSlotsProtocol) {
1926 clearSlots(-1);
1927 }
1928}
1929
1930bool MultiTouchMotionAccumulator::hasStylus() const {
1931 return mHaveStylus;
1932}
1933
1934
1935// --- MultiTouchMotionAccumulator::Slot ---
1936
1937MultiTouchMotionAccumulator::Slot::Slot() {
1938 clear();
1939}
1940
1941void MultiTouchMotionAccumulator::Slot::clear() {
1942 mInUse = false;
1943 mHaveAbsMTTouchMinor = false;
1944 mHaveAbsMTWidthMinor = false;
1945 mHaveAbsMTToolType = false;
1946 mAbsMTPositionX = 0;
1947 mAbsMTPositionY = 0;
1948 mAbsMTTouchMajor = 0;
1949 mAbsMTTouchMinor = 0;
1950 mAbsMTWidthMajor = 0;
1951 mAbsMTWidthMinor = 0;
1952 mAbsMTOrientation = 0;
1953 mAbsMTTrackingId = -1;
1954 mAbsMTPressure = 0;
1955 mAbsMTDistance = 0;
1956 mAbsMTToolType = 0;
1957}
1958
1959int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1960 if (mHaveAbsMTToolType) {
1961 switch (mAbsMTToolType) {
1962 case MT_TOOL_FINGER:
1963 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1964 case MT_TOOL_PEN:
1965 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1966 }
1967 }
1968 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1969}
1970
1971
1972// --- InputMapper ---
1973
1974InputMapper::InputMapper(InputDevice* device) :
1975 mDevice(device), mContext(device->getContext()) {
1976}
1977
1978InputMapper::~InputMapper() {
1979}
1980
1981void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1982 info->addSource(getSources());
1983}
1984
1985void InputMapper::dump(String8& dump) {
1986}
1987
1988void InputMapper::configure(nsecs_t when,
1989 const InputReaderConfiguration* config, uint32_t changes) {
1990}
1991
1992void InputMapper::reset(nsecs_t when) {
1993}
1994
1995void InputMapper::timeoutExpired(nsecs_t when) {
1996}
1997
1998int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1999 return AKEY_STATE_UNKNOWN;
2000}
2001
2002int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2003 return AKEY_STATE_UNKNOWN;
2004}
2005
2006int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2007 return AKEY_STATE_UNKNOWN;
2008}
2009
2010bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2011 const int32_t* keyCodes, uint8_t* outFlags) {
2012 return false;
2013}
2014
2015void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2016 int32_t token) {
2017}
2018
2019void InputMapper::cancelVibrate(int32_t token) {
2020}
2021
Jeff Brownc9aa6282015-02-11 19:03:28 -08002022void InputMapper::cancelTouch(nsecs_t when) {
2023}
2024
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025int32_t InputMapper::getMetaState() {
2026 return 0;
2027}
2028
Andrii Kulian763a3a42016-03-08 10:46:16 -08002029void InputMapper::updateMetaState(int32_t keyCode) {
2030}
2031
Michael Wright842500e2015-03-13 17:32:02 -07002032void InputMapper::updateExternalStylusState(const StylusState& state) {
2033
2034}
2035
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036void InputMapper::fadePointer() {
2037}
2038
2039status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2040 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2041}
2042
2043void InputMapper::bumpGeneration() {
2044 mDevice->bumpGeneration();
2045}
2046
2047void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
2048 const RawAbsoluteAxisInfo& axis, const char* name) {
2049 if (axis.valid) {
2050 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
2051 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2052 } else {
2053 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
2054 }
2055}
2056
Michael Wright842500e2015-03-13 17:32:02 -07002057void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
2058 dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
2059 dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
2060 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
2061 dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
2062}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
2064// --- SwitchInputMapper ---
2065
2066SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002067 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068}
2069
2070SwitchInputMapper::~SwitchInputMapper() {
2071}
2072
2073uint32_t SwitchInputMapper::getSources() {
2074 return AINPUT_SOURCE_SWITCH;
2075}
2076
2077void SwitchInputMapper::process(const RawEvent* rawEvent) {
2078 switch (rawEvent->type) {
2079 case EV_SW:
2080 processSwitch(rawEvent->code, rawEvent->value);
2081 break;
2082
2083 case EV_SYN:
2084 if (rawEvent->code == SYN_REPORT) {
2085 sync(rawEvent->when);
2086 }
2087 }
2088}
2089
2090void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2091 if (switchCode >= 0 && switchCode < 32) {
2092 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002093 mSwitchValues |= 1 << switchCode;
2094 } else {
2095 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
2097 mUpdatedSwitchMask |= 1 << switchCode;
2098 }
2099}
2100
2101void SwitchInputMapper::sync(nsecs_t when) {
2102 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002103 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002104 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 getListener()->notifySwitch(&args);
2106
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 mUpdatedSwitchMask = 0;
2108 }
2109}
2110
2111int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2112 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2113}
2114
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002115void SwitchInputMapper::dump(String8& dump) {
2116 dump.append(INDENT2 "Switch Input Mapper:\n");
2117 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
2118}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119
2120// --- VibratorInputMapper ---
2121
2122VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2123 InputMapper(device), mVibrating(false) {
2124}
2125
2126VibratorInputMapper::~VibratorInputMapper() {
2127}
2128
2129uint32_t VibratorInputMapper::getSources() {
2130 return 0;
2131}
2132
2133void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2134 InputMapper::populateDeviceInfo(info);
2135
2136 info->setVibrator(true);
2137}
2138
2139void VibratorInputMapper::process(const RawEvent* rawEvent) {
2140 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2141}
2142
2143void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2144 int32_t token) {
2145#if DEBUG_VIBRATOR
2146 String8 patternStr;
2147 for (size_t i = 0; i < patternSize; i++) {
2148 if (i != 0) {
2149 patternStr.append(", ");
2150 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002151 patternStr.appendFormat("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002153 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 getDeviceId(), patternStr.string(), repeat, token);
2155#endif
2156
2157 mVibrating = true;
2158 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2159 mPatternSize = patternSize;
2160 mRepeat = repeat;
2161 mToken = token;
2162 mIndex = -1;
2163
2164 nextStep();
2165}
2166
2167void VibratorInputMapper::cancelVibrate(int32_t token) {
2168#if DEBUG_VIBRATOR
2169 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2170#endif
2171
2172 if (mVibrating && mToken == token) {
2173 stopVibrating();
2174 }
2175}
2176
2177void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2178 if (mVibrating) {
2179 if (when >= mNextStepTime) {
2180 nextStep();
2181 } else {
2182 getContext()->requestTimeoutAtTime(mNextStepTime);
2183 }
2184 }
2185}
2186
2187void VibratorInputMapper::nextStep() {
2188 mIndex += 1;
2189 if (size_t(mIndex) >= mPatternSize) {
2190 if (mRepeat < 0) {
2191 // We are done.
2192 stopVibrating();
2193 return;
2194 }
2195 mIndex = mRepeat;
2196 }
2197
2198 bool vibratorOn = mIndex & 1;
2199 nsecs_t duration = mPattern[mIndex];
2200 if (vibratorOn) {
2201#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002202 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203#endif
2204 getEventHub()->vibrate(getDeviceId(), duration);
2205 } else {
2206#if DEBUG_VIBRATOR
2207 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2208#endif
2209 getEventHub()->cancelVibrate(getDeviceId());
2210 }
2211 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2212 mNextStepTime = now + duration;
2213 getContext()->requestTimeoutAtTime(mNextStepTime);
2214#if DEBUG_VIBRATOR
2215 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2216#endif
2217}
2218
2219void VibratorInputMapper::stopVibrating() {
2220 mVibrating = false;
2221#if DEBUG_VIBRATOR
2222 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2223#endif
2224 getEventHub()->cancelVibrate(getDeviceId());
2225}
2226
2227void VibratorInputMapper::dump(String8& dump) {
2228 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2229 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2230}
2231
2232
2233// --- KeyboardInputMapper ---
2234
2235KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2236 uint32_t source, int32_t keyboardType) :
2237 InputMapper(device), mSource(source),
2238 mKeyboardType(keyboardType) {
2239}
2240
2241KeyboardInputMapper::~KeyboardInputMapper() {
2242}
2243
2244uint32_t KeyboardInputMapper::getSources() {
2245 return mSource;
2246}
2247
2248void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2249 InputMapper::populateDeviceInfo(info);
2250
2251 info->setKeyboardType(mKeyboardType);
2252 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2253}
2254
2255void KeyboardInputMapper::dump(String8& dump) {
2256 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2257 dumpParameters(dump);
2258 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2259 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002260 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002262 dump.appendFormat(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263}
2264
2265
2266void KeyboardInputMapper::configure(nsecs_t when,
2267 const InputReaderConfiguration* config, uint32_t changes) {
2268 InputMapper::configure(when, config, changes);
2269
2270 if (!changes) { // first time only
2271 // Configure basic parameters.
2272 configureParameters();
2273 }
2274
2275 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2276 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2277 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002278 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 mOrientation = v.orientation;
2280 } else {
2281 mOrientation = DISPLAY_ORIENTATION_0;
2282 }
2283 } else {
2284 mOrientation = DISPLAY_ORIENTATION_0;
2285 }
2286 }
2287}
2288
Ivan Podogovb9afef32017-02-13 15:34:32 +00002289static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2290 int32_t mapped = 0;
2291 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2292 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2293 if (stemKeyRotationMap[i][0] == keyCode) {
2294 stemKeyRotationMap[i][1] = mapped;
2295 return;
2296 }
2297 }
2298 }
2299}
2300
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301void KeyboardInputMapper::configureParameters() {
2302 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002303 const PropertyMap& config = getDevice()->getConfiguration();
2304 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 mParameters.orientationAware);
2306
2307 mParameters.hasAssociatedDisplay = false;
2308 if (mParameters.orientationAware) {
2309 mParameters.hasAssociatedDisplay = true;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002310
2311 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2312 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2313 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2314 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002316
2317 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002318 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002319 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320}
2321
2322void KeyboardInputMapper::dumpParameters(String8& dump) {
2323 dump.append(INDENT3 "Parameters:\n");
2324 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2325 toString(mParameters.hasAssociatedDisplay));
2326 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2327 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002328 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2329 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330}
2331
2332void KeyboardInputMapper::reset(nsecs_t when) {
2333 mMetaState = AMETA_NONE;
2334 mDownTime = 0;
2335 mKeyDowns.clear();
2336 mCurrentHidUsage = 0;
2337
2338 resetLedState();
2339
2340 InputMapper::reset(when);
2341}
2342
2343void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2344 switch (rawEvent->type) {
2345 case EV_KEY: {
2346 int32_t scanCode = rawEvent->code;
2347 int32_t usageCode = mCurrentHidUsage;
2348 mCurrentHidUsage = 0;
2349
2350 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002351 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353 break;
2354 }
2355 case EV_MSC: {
2356 if (rawEvent->code == MSC_SCAN) {
2357 mCurrentHidUsage = rawEvent->value;
2358 }
2359 break;
2360 }
2361 case EV_SYN: {
2362 if (rawEvent->code == SYN_REPORT) {
2363 mCurrentHidUsage = 0;
2364 }
2365 }
2366 }
2367}
2368
2369bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2370 return scanCode < BTN_MOUSE
2371 || scanCode >= KEY_OK
2372 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2373 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2374}
2375
Michael Wright58ba9882017-07-26 16:19:11 +01002376bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2377 switch (keyCode) {
2378 case AKEYCODE_MEDIA_PLAY:
2379 case AKEYCODE_MEDIA_PAUSE:
2380 case AKEYCODE_MEDIA_PLAY_PAUSE:
2381 case AKEYCODE_MUTE:
2382 case AKEYCODE_HEADSETHOOK:
2383 case AKEYCODE_MEDIA_STOP:
2384 case AKEYCODE_MEDIA_NEXT:
2385 case AKEYCODE_MEDIA_PREVIOUS:
2386 case AKEYCODE_MEDIA_REWIND:
2387 case AKEYCODE_MEDIA_RECORD:
2388 case AKEYCODE_MEDIA_FAST_FORWARD:
2389 case AKEYCODE_MEDIA_SKIP_FORWARD:
2390 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2391 case AKEYCODE_MEDIA_STEP_FORWARD:
2392 case AKEYCODE_MEDIA_STEP_BACKWARD:
2393 case AKEYCODE_MEDIA_AUDIO_TRACK:
2394 case AKEYCODE_VOLUME_UP:
2395 case AKEYCODE_VOLUME_DOWN:
2396 case AKEYCODE_VOLUME_MUTE:
2397 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2398 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2399 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2400 return true;
2401 }
2402 return false;
2403}
2404
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002405void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2406 int32_t usageCode) {
2407 int32_t keyCode;
2408 int32_t keyMetaState;
2409 uint32_t policyFlags;
2410
2411 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2412 &keyCode, &keyMetaState, &policyFlags)) {
2413 keyCode = AKEYCODE_UNKNOWN;
2414 keyMetaState = mMetaState;
2415 policyFlags = 0;
2416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417
2418 if (down) {
2419 // Rotate key codes according to orientation if needed.
2420 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2421 keyCode = rotateKeyCode(keyCode, mOrientation);
2422 }
2423
2424 // Add key down.
2425 ssize_t keyDownIndex = findKeyDown(scanCode);
2426 if (keyDownIndex >= 0) {
2427 // key repeat, be sure to use same keycode as before in case of rotation
2428 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2429 } else {
2430 // key down
2431 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2432 && mContext->shouldDropVirtualKey(when,
2433 getDevice(), keyCode, scanCode)) {
2434 return;
2435 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002436 if (policyFlags & POLICY_FLAG_GESTURE) {
2437 mDevice->cancelTouch(when);
2438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439
2440 mKeyDowns.push();
2441 KeyDown& keyDown = mKeyDowns.editTop();
2442 keyDown.keyCode = keyCode;
2443 keyDown.scanCode = scanCode;
2444 }
2445
2446 mDownTime = when;
2447 } else {
2448 // Remove key down.
2449 ssize_t keyDownIndex = findKeyDown(scanCode);
2450 if (keyDownIndex >= 0) {
2451 // key up, be sure to use same keycode as before in case of rotation
2452 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2453 mKeyDowns.removeAt(size_t(keyDownIndex));
2454 } else {
2455 // key was not actually down
2456 ALOGI("Dropping key up from device %s because the key was not down. "
2457 "keyCode=%d, scanCode=%d",
2458 getDeviceName().string(), keyCode, scanCode);
2459 return;
2460 }
2461 }
2462
Andrii Kulian763a3a42016-03-08 10:46:16 -08002463 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002464 // If global meta state changed send it along with the key.
2465 // If it has not changed then we'll use what keymap gave us,
2466 // since key replacement logic might temporarily reset a few
2467 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002468 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470
2471 nsecs_t downTime = mDownTime;
2472
2473 // Key down on external an keyboard should wake the device.
2474 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2475 // For internal keyboards, the key layout file should specify the policy flags for
2476 // each wake key individually.
2477 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002478 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002479 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 }
2481
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002482 if (mParameters.handlesKeyRepeat) {
2483 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2484 }
2485
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2487 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002488 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 getListener()->notifyKey(&args);
2490}
2491
2492ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2493 size_t n = mKeyDowns.size();
2494 for (size_t i = 0; i < n; i++) {
2495 if (mKeyDowns[i].scanCode == scanCode) {
2496 return i;
2497 }
2498 }
2499 return -1;
2500}
2501
2502int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2503 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2504}
2505
2506int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2507 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2508}
2509
2510bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2511 const int32_t* keyCodes, uint8_t* outFlags) {
2512 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2513}
2514
2515int32_t KeyboardInputMapper::getMetaState() {
2516 return mMetaState;
2517}
2518
Andrii Kulian763a3a42016-03-08 10:46:16 -08002519void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2520 updateMetaStateIfNeeded(keyCode, false);
2521}
2522
2523bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2524 int32_t oldMetaState = mMetaState;
2525 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2526 bool metaStateChanged = oldMetaState != newMetaState;
2527 if (metaStateChanged) {
2528 mMetaState = newMetaState;
2529 updateLedState(false);
2530
2531 getContext()->updateGlobalMetaState();
2532 }
2533
2534 return metaStateChanged;
2535}
2536
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537void KeyboardInputMapper::resetLedState() {
2538 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2539 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2540 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2541
2542 updateLedState(true);
2543}
2544
2545void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2546 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2547 ledState.on = false;
2548}
2549
2550void KeyboardInputMapper::updateLedState(bool reset) {
2551 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2552 AMETA_CAPS_LOCK_ON, reset);
2553 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2554 AMETA_NUM_LOCK_ON, reset);
2555 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2556 AMETA_SCROLL_LOCK_ON, reset);
2557}
2558
2559void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2560 int32_t led, int32_t modifier, bool reset) {
2561 if (ledState.avail) {
2562 bool desiredState = (mMetaState & modifier) != 0;
2563 if (reset || ledState.on != desiredState) {
2564 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2565 ledState.on = desiredState;
2566 }
2567 }
2568}
2569
2570
2571// --- CursorInputMapper ---
2572
2573CursorInputMapper::CursorInputMapper(InputDevice* device) :
2574 InputMapper(device) {
2575}
2576
2577CursorInputMapper::~CursorInputMapper() {
2578}
2579
2580uint32_t CursorInputMapper::getSources() {
2581 return mSource;
2582}
2583
2584void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2585 InputMapper::populateDeviceInfo(info);
2586
2587 if (mParameters.mode == Parameters::MODE_POINTER) {
2588 float minX, minY, maxX, maxY;
2589 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2590 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2591 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2592 }
2593 } else {
2594 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2595 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2596 }
2597 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2598
2599 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2600 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2601 }
2602 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2603 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2604 }
2605}
2606
2607void CursorInputMapper::dump(String8& dump) {
2608 dump.append(INDENT2 "Cursor Input Mapper:\n");
2609 dumpParameters(dump);
2610 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2611 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2612 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2613 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2614 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2615 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2616 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2617 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2618 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2619 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2620 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2621 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2622 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002623 dump.appendFormat(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624}
2625
2626void CursorInputMapper::configure(nsecs_t when,
2627 const InputReaderConfiguration* config, uint32_t changes) {
2628 InputMapper::configure(when, config, changes);
2629
2630 if (!changes) { // first time only
2631 mCursorScrollAccumulator.configure(getDevice());
2632
2633 // Configure basic parameters.
2634 configureParameters();
2635
2636 // Configure device mode.
2637 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002638 case Parameters::MODE_POINTER_RELATIVE:
2639 // Should not happen during first time configuration.
2640 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2641 mParameters.mode = Parameters::MODE_POINTER;
2642 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 case Parameters::MODE_POINTER:
2644 mSource = AINPUT_SOURCE_MOUSE;
2645 mXPrecision = 1.0f;
2646 mYPrecision = 1.0f;
2647 mXScale = 1.0f;
2648 mYScale = 1.0f;
2649 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2650 break;
2651 case Parameters::MODE_NAVIGATION:
2652 mSource = AINPUT_SOURCE_TRACKBALL;
2653 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2654 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2655 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2656 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2657 break;
2658 }
2659
2660 mVWheelScale = 1.0f;
2661 mHWheelScale = 1.0f;
2662 }
2663
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002664 if ((!changes && config->pointerCapture)
2665 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2666 if (config->pointerCapture) {
2667 if (mParameters.mode == Parameters::MODE_POINTER) {
2668 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2669 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2670 // Keep PointerController around in order to preserve the pointer position.
2671 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2672 } else {
2673 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2674 }
2675 } else {
2676 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2677 mParameters.mode = Parameters::MODE_POINTER;
2678 mSource = AINPUT_SOURCE_MOUSE;
2679 } else {
2680 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2681 }
2682 }
2683 bumpGeneration();
2684 if (changes) {
2685 getDevice()->notifyReset(when);
2686 }
2687 }
2688
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2690 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2691 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2692 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2693 }
2694
2695 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2696 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2697 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002698 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 mOrientation = v.orientation;
2700 } else {
2701 mOrientation = DISPLAY_ORIENTATION_0;
2702 }
2703 } else {
2704 mOrientation = DISPLAY_ORIENTATION_0;
2705 }
2706 bumpGeneration();
2707 }
2708}
2709
2710void CursorInputMapper::configureParameters() {
2711 mParameters.mode = Parameters::MODE_POINTER;
2712 String8 cursorModeString;
2713 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2714 if (cursorModeString == "navigation") {
2715 mParameters.mode = Parameters::MODE_NAVIGATION;
2716 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2717 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2718 }
2719 }
2720
2721 mParameters.orientationAware = false;
2722 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2723 mParameters.orientationAware);
2724
2725 mParameters.hasAssociatedDisplay = false;
2726 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2727 mParameters.hasAssociatedDisplay = true;
2728 }
2729}
2730
2731void CursorInputMapper::dumpParameters(String8& dump) {
2732 dump.append(INDENT3 "Parameters:\n");
2733 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2734 toString(mParameters.hasAssociatedDisplay));
2735
2736 switch (mParameters.mode) {
2737 case Parameters::MODE_POINTER:
2738 dump.append(INDENT4 "Mode: pointer\n");
2739 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002740 case Parameters::MODE_POINTER_RELATIVE:
2741 dump.append(INDENT4 "Mode: relative pointer\n");
2742 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 case Parameters::MODE_NAVIGATION:
2744 dump.append(INDENT4 "Mode: navigation\n");
2745 break;
2746 default:
2747 ALOG_ASSERT(false);
2748 }
2749
2750 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2751 toString(mParameters.orientationAware));
2752}
2753
2754void CursorInputMapper::reset(nsecs_t when) {
2755 mButtonState = 0;
2756 mDownTime = 0;
2757
2758 mPointerVelocityControl.reset();
2759 mWheelXVelocityControl.reset();
2760 mWheelYVelocityControl.reset();
2761
2762 mCursorButtonAccumulator.reset(getDevice());
2763 mCursorMotionAccumulator.reset(getDevice());
2764 mCursorScrollAccumulator.reset(getDevice());
2765
2766 InputMapper::reset(when);
2767}
2768
2769void CursorInputMapper::process(const RawEvent* rawEvent) {
2770 mCursorButtonAccumulator.process(rawEvent);
2771 mCursorMotionAccumulator.process(rawEvent);
2772 mCursorScrollAccumulator.process(rawEvent);
2773
2774 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2775 sync(rawEvent->when);
2776 }
2777}
2778
2779void CursorInputMapper::sync(nsecs_t when) {
2780 int32_t lastButtonState = mButtonState;
2781 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2782 mButtonState = currentButtonState;
2783
2784 bool wasDown = isPointerDown(lastButtonState);
2785 bool down = isPointerDown(currentButtonState);
2786 bool downChanged;
2787 if (!wasDown && down) {
2788 mDownTime = when;
2789 downChanged = true;
2790 } else if (wasDown && !down) {
2791 downChanged = true;
2792 } else {
2793 downChanged = false;
2794 }
2795 nsecs_t downTime = mDownTime;
2796 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002797 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2798 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799
2800 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2801 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2802 bool moved = deltaX != 0 || deltaY != 0;
2803
2804 // Rotate delta according to orientation if needed.
2805 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2806 && (deltaX != 0.0f || deltaY != 0.0f)) {
2807 rotateDelta(mOrientation, &deltaX, &deltaY);
2808 }
2809
2810 // Move the pointer.
2811 PointerProperties pointerProperties;
2812 pointerProperties.clear();
2813 pointerProperties.id = 0;
2814 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2815
2816 PointerCoords pointerCoords;
2817 pointerCoords.clear();
2818
2819 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2820 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2821 bool scrolled = vscroll != 0 || hscroll != 0;
2822
2823 mWheelYVelocityControl.move(when, NULL, &vscroll);
2824 mWheelXVelocityControl.move(when, &hscroll, NULL);
2825
2826 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2827
2828 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002829 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 if (moved || scrolled || buttonsChanged) {
2831 mPointerController->setPresentation(
2832 PointerControllerInterface::PRESENTATION_POINTER);
2833
2834 if (moved) {
2835 mPointerController->move(deltaX, deltaY);
2836 }
2837
2838 if (buttonsChanged) {
2839 mPointerController->setButtonState(currentButtonState);
2840 }
2841
2842 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2843 }
2844
2845 float x, y;
2846 mPointerController->getPosition(&x, &y);
2847 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2848 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002849 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2850 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 displayId = ADISPLAY_ID_DEFAULT;
2852 } else {
2853 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2854 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2855 displayId = ADISPLAY_ID_NONE;
2856 }
2857
2858 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2859
2860 // Moving an external trackball or mouse should wake the device.
2861 // We don't do this for internal cursor devices to prevent them from waking up
2862 // the device in your pocket.
2863 // TODO: Use the input device configuration to control this behavior more finely.
2864 uint32_t policyFlags = 0;
2865 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002866 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 }
2868
2869 // Synthesize key down from buttons if needed.
2870 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2871 policyFlags, lastButtonState, currentButtonState);
2872
2873 // Send motion event.
2874 if (downChanged || moved || scrolled || buttonsChanged) {
2875 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002876 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 int32_t motionEventAction;
2878 if (downChanged) {
2879 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002880 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2882 } else {
2883 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2884 }
2885
Michael Wright7b159c92015-05-14 14:48:03 +01002886 if (buttonsReleased) {
2887 BitSet32 released(buttonsReleased);
2888 while (!released.isEmpty()) {
2889 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2890 buttonState &= ~actionButton;
2891 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2892 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2893 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2894 displayId, 1, &pointerProperties, &pointerCoords,
2895 mXPrecision, mYPrecision, downTime);
2896 getListener()->notifyMotion(&releaseArgs);
2897 }
2898 }
2899
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002901 motionEventAction, 0, 0, metaState, currentButtonState,
2902 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 displayId, 1, &pointerProperties, &pointerCoords,
2904 mXPrecision, mYPrecision, downTime);
2905 getListener()->notifyMotion(&args);
2906
Michael Wright7b159c92015-05-14 14:48:03 +01002907 if (buttonsPressed) {
2908 BitSet32 pressed(buttonsPressed);
2909 while (!pressed.isEmpty()) {
2910 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2911 buttonState |= actionButton;
2912 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2913 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2914 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2915 displayId, 1, &pointerProperties, &pointerCoords,
2916 mXPrecision, mYPrecision, downTime);
2917 getListener()->notifyMotion(&pressArgs);
2918 }
2919 }
2920
2921 ALOG_ASSERT(buttonState == currentButtonState);
2922
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 // Send hover move after UP to tell the application that the mouse is hovering now.
2924 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002925 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002927 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2929 displayId, 1, &pointerProperties, &pointerCoords,
2930 mXPrecision, mYPrecision, downTime);
2931 getListener()->notifyMotion(&hoverArgs);
2932 }
2933
2934 // Send scroll events.
2935 if (scrolled) {
2936 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2937 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2938
2939 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002940 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 AMOTION_EVENT_EDGE_FLAG_NONE,
2942 displayId, 1, &pointerProperties, &pointerCoords,
2943 mXPrecision, mYPrecision, downTime);
2944 getListener()->notifyMotion(&scrollArgs);
2945 }
2946 }
2947
2948 // Synthesize key up from buttons if needed.
2949 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2950 policyFlags, lastButtonState, currentButtonState);
2951
2952 mCursorMotionAccumulator.finishSync();
2953 mCursorScrollAccumulator.finishSync();
2954}
2955
2956int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2957 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2958 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2959 } else {
2960 return AKEY_STATE_UNKNOWN;
2961 }
2962}
2963
2964void CursorInputMapper::fadePointer() {
2965 if (mPointerController != NULL) {
2966 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2967 }
2968}
2969
Prashant Malani1941ff52015-08-11 18:29:28 -07002970// --- RotaryEncoderInputMapper ---
2971
2972RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002973 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002974 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2975}
2976
2977RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2978}
2979
2980uint32_t RotaryEncoderInputMapper::getSources() {
2981 return mSource;
2982}
2983
2984void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2985 InputMapper::populateDeviceInfo(info);
2986
2987 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002988 float res = 0.0f;
2989 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2990 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2991 }
2992 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2993 mScalingFactor)) {
2994 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2995 "default to 1.0!\n");
2996 mScalingFactor = 1.0f;
2997 }
2998 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2999 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003000 }
3001}
3002
3003void RotaryEncoderInputMapper::dump(String8& dump) {
3004 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
3005 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
3006 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3007}
3008
3009void RotaryEncoderInputMapper::configure(nsecs_t when,
3010 const InputReaderConfiguration* config, uint32_t changes) {
3011 InputMapper::configure(when, config, changes);
3012 if (!changes) {
3013 mRotaryEncoderScrollAccumulator.configure(getDevice());
3014 }
Ivan Podogovad437252016-09-29 16:29:55 +01003015 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
3016 DisplayViewport v;
3017 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
3018 mOrientation = v.orientation;
3019 } else {
3020 mOrientation = DISPLAY_ORIENTATION_0;
3021 }
3022 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003023}
3024
3025void RotaryEncoderInputMapper::reset(nsecs_t when) {
3026 mRotaryEncoderScrollAccumulator.reset(getDevice());
3027
3028 InputMapper::reset(when);
3029}
3030
3031void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3032 mRotaryEncoderScrollAccumulator.process(rawEvent);
3033
3034 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3035 sync(rawEvent->when);
3036 }
3037}
3038
3039void RotaryEncoderInputMapper::sync(nsecs_t when) {
3040 PointerCoords pointerCoords;
3041 pointerCoords.clear();
3042
3043 PointerProperties pointerProperties;
3044 pointerProperties.clear();
3045 pointerProperties.id = 0;
3046 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3047
3048 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3049 bool scrolled = scroll != 0;
3050
3051 // This is not a pointer, so it's not associated with a display.
3052 int32_t displayId = ADISPLAY_ID_NONE;
3053
3054 // Moving the rotary encoder should wake the device (if specified).
3055 uint32_t policyFlags = 0;
3056 if (scrolled && getDevice()->isExternal()) {
3057 policyFlags |= POLICY_FLAG_WAKE;
3058 }
3059
Ivan Podogovad437252016-09-29 16:29:55 +01003060 if (mOrientation == DISPLAY_ORIENTATION_180) {
3061 scroll = -scroll;
3062 }
3063
Prashant Malani1941ff52015-08-11 18:29:28 -07003064 // Send motion event.
3065 if (scrolled) {
3066 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003067 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003068
3069 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3070 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3071 AMOTION_EVENT_EDGE_FLAG_NONE,
3072 displayId, 1, &pointerProperties, &pointerCoords,
3073 0, 0, 0);
3074 getListener()->notifyMotion(&scrollArgs);
3075 }
3076
3077 mRotaryEncoderScrollAccumulator.finishSync();
3078}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079
3080// --- TouchInputMapper ---
3081
3082TouchInputMapper::TouchInputMapper(InputDevice* device) :
3083 InputMapper(device),
3084 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3085 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3086 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3087}
3088
3089TouchInputMapper::~TouchInputMapper() {
3090}
3091
3092uint32_t TouchInputMapper::getSources() {
3093 return mSource;
3094}
3095
3096void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3097 InputMapper::populateDeviceInfo(info);
3098
3099 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3100 info->addMotionRange(mOrientedRanges.x);
3101 info->addMotionRange(mOrientedRanges.y);
3102 info->addMotionRange(mOrientedRanges.pressure);
3103
3104 if (mOrientedRanges.haveSize) {
3105 info->addMotionRange(mOrientedRanges.size);
3106 }
3107
3108 if (mOrientedRanges.haveTouchSize) {
3109 info->addMotionRange(mOrientedRanges.touchMajor);
3110 info->addMotionRange(mOrientedRanges.touchMinor);
3111 }
3112
3113 if (mOrientedRanges.haveToolSize) {
3114 info->addMotionRange(mOrientedRanges.toolMajor);
3115 info->addMotionRange(mOrientedRanges.toolMinor);
3116 }
3117
3118 if (mOrientedRanges.haveOrientation) {
3119 info->addMotionRange(mOrientedRanges.orientation);
3120 }
3121
3122 if (mOrientedRanges.haveDistance) {
3123 info->addMotionRange(mOrientedRanges.distance);
3124 }
3125
3126 if (mOrientedRanges.haveTilt) {
3127 info->addMotionRange(mOrientedRanges.tilt);
3128 }
3129
3130 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3131 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3132 0.0f);
3133 }
3134 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3135 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3136 0.0f);
3137 }
3138 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3139 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3140 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3141 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3142 x.fuzz, x.resolution);
3143 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3144 y.fuzz, y.resolution);
3145 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3146 x.fuzz, x.resolution);
3147 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3148 y.fuzz, y.resolution);
3149 }
3150 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3151 }
3152}
3153
3154void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003155 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 dumpParameters(dump);
3157 dumpVirtualKeys(dump);
3158 dumpRawPointerAxes(dump);
3159 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003160 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 dumpSurface(dump);
3162
3163 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3164 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3165 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3166 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3167 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3168 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3169 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3170 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3171 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3172 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3173 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3174 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3175 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3176 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3177 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3178 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3179 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3180
Michael Wright7b159c92015-05-14 14:48:03 +01003181 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003183 mLastRawState.rawPointerData.pointerCount);
3184 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3185 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3187 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3188 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3189 "toolType=%d, isHovering=%s\n", i,
3190 pointer.id, pointer.x, pointer.y, pointer.pressure,
3191 pointer.touchMajor, pointer.touchMinor,
3192 pointer.toolMajor, pointer.toolMinor,
3193 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3194 pointer.toolType, toString(pointer.isHovering));
3195 }
3196
Michael Wright7b159c92015-05-14 14:48:03 +01003197 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003199 mLastCookedState.cookedPointerData.pointerCount);
3200 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3201 const PointerProperties& pointerProperties =
3202 mLastCookedState.cookedPointerData.pointerProperties[i];
3203 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3205 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3206 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3207 "toolType=%d, isHovering=%s\n", i,
3208 pointerProperties.id,
3209 pointerCoords.getX(),
3210 pointerCoords.getY(),
3211 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3212 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3213 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3214 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3215 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3216 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3217 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3218 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3219 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003220 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
3222
Michael Wright842500e2015-03-13 17:32:02 -07003223 dump.append(INDENT3 "Stylus Fusion:\n");
3224 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3225 toString(mExternalStylusConnected));
3226 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3227 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003228 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003229 dump.append(INDENT3 "External Stylus State:\n");
3230 dumpStylusState(dump, mExternalStylusState);
3231
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 if (mDeviceMode == DEVICE_MODE_POINTER) {
3233 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3234 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3235 mPointerXMovementScale);
3236 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3237 mPointerYMovementScale);
3238 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3239 mPointerXZoomScale);
3240 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3241 mPointerYZoomScale);
3242 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3243 mPointerGestureMaxSwipeWidth);
3244 }
3245}
3246
Santos Cordonfa5cf462017-04-05 10:37:00 -07003247const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3248 switch (deviceMode) {
3249 case DEVICE_MODE_DISABLED:
3250 return "disabled";
3251 case DEVICE_MODE_DIRECT:
3252 return "direct";
3253 case DEVICE_MODE_UNSCALED:
3254 return "unscaled";
3255 case DEVICE_MODE_NAVIGATION:
3256 return "navigation";
3257 case DEVICE_MODE_POINTER:
3258 return "pointer";
3259 }
3260 return "unknown";
3261}
3262
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263void TouchInputMapper::configure(nsecs_t when,
3264 const InputReaderConfiguration* config, uint32_t changes) {
3265 InputMapper::configure(when, config, changes);
3266
3267 mConfig = *config;
3268
3269 if (!changes) { // first time only
3270 // Configure basic parameters.
3271 configureParameters();
3272
3273 // Configure common accumulators.
3274 mCursorScrollAccumulator.configure(getDevice());
3275 mTouchButtonAccumulator.configure(getDevice());
3276
3277 // Configure absolute axis information.
3278 configureRawPointerAxes();
3279
3280 // Prepare input device calibration.
3281 parseCalibration();
3282 resolveCalibration();
3283 }
3284
Michael Wright842500e2015-03-13 17:32:02 -07003285 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003286 // Update location calibration to reflect current settings
3287 updateAffineTransformation();
3288 }
3289
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3291 // Update pointer speed.
3292 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3293 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3294 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3295 }
3296
3297 bool resetNeeded = false;
3298 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3299 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003300 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3301 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 // Configure device sources, surface dimensions, orientation and
3303 // scaling factors.
3304 configureSurface(when, &resetNeeded);
3305 }
3306
3307 if (changes && resetNeeded) {
3308 // Send reset, unless this is the first time the device has been configured,
3309 // in which case the reader will call reset itself after all mappers are ready.
3310 getDevice()->notifyReset(when);
3311 }
3312}
3313
Michael Wright842500e2015-03-13 17:32:02 -07003314void TouchInputMapper::resolveExternalStylusPresence() {
3315 Vector<InputDeviceInfo> devices;
3316 mContext->getExternalStylusDevices(devices);
3317 mExternalStylusConnected = !devices.isEmpty();
3318
3319 if (!mExternalStylusConnected) {
3320 resetExternalStylus();
3321 }
3322}
3323
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324void TouchInputMapper::configureParameters() {
3325 // Use the pointer presentation mode for devices that do not support distinct
3326 // multitouch. The spot-based presentation relies on being able to accurately
3327 // locate two or more fingers on the touch pad.
3328 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003329 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
3331 String8 gestureModeString;
3332 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3333 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003334 if (gestureModeString == "single-touch") {
3335 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3336 } else if (gestureModeString == "multi-touch") {
3337 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 } else if (gestureModeString != "default") {
3339 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3340 }
3341 }
3342
3343 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3344 // The device is a touch screen.
3345 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3346 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3347 // The device is a pointing device like a track pad.
3348 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3349 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3350 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3351 // The device is a cursor device with a touch pad attached.
3352 // By default don't use the touch pad to move the pointer.
3353 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3354 } else {
3355 // The device is a touch pad of unknown purpose.
3356 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3357 }
3358
3359 mParameters.hasButtonUnderPad=
3360 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3361
3362 String8 deviceTypeString;
3363 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3364 deviceTypeString)) {
3365 if (deviceTypeString == "touchScreen") {
3366 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3367 } else if (deviceTypeString == "touchPad") {
3368 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3369 } else if (deviceTypeString == "touchNavigation") {
3370 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3371 } else if (deviceTypeString == "pointer") {
3372 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3373 } else if (deviceTypeString != "default") {
3374 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3375 }
3376 }
3377
3378 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3379 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3380 mParameters.orientationAware);
3381
3382 mParameters.hasAssociatedDisplay = false;
3383 mParameters.associatedDisplayIsExternal = false;
3384 if (mParameters.orientationAware
3385 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3386 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3387 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003388 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3389 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3390 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3391 mParameters.uniqueDisplayId);
3392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003394
3395 // Initial downs on external touch devices should wake the device.
3396 // Normally we don't do this for internal touch screens to prevent them from waking
3397 // up in your pocket but you can enable it using the input device configuration.
3398 mParameters.wake = getDevice()->isExternal();
3399 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3400 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401}
3402
3403void TouchInputMapper::dumpParameters(String8& dump) {
3404 dump.append(INDENT3 "Parameters:\n");
3405
3406 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003407 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3408 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003410 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3411 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 break;
3413 default:
3414 assert(false);
3415 }
3416
3417 switch (mParameters.deviceType) {
3418 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3419 dump.append(INDENT4 "DeviceType: touchScreen\n");
3420 break;
3421 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3422 dump.append(INDENT4 "DeviceType: touchPad\n");
3423 break;
3424 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3425 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3426 break;
3427 case Parameters::DEVICE_TYPE_POINTER:
3428 dump.append(INDENT4 "DeviceType: pointer\n");
3429 break;
3430 default:
3431 ALOG_ASSERT(false);
3432 }
3433
Santos Cordonfa5cf462017-04-05 10:37:00 -07003434 dump.appendFormat(
3435 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003437 toString(mParameters.associatedDisplayIsExternal),
3438 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3440 toString(mParameters.orientationAware));
3441}
3442
3443void TouchInputMapper::configureRawPointerAxes() {
3444 mRawPointerAxes.clear();
3445}
3446
3447void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3448 dump.append(INDENT3 "Raw Touch Axes:\n");
3449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3451 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3455 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3462}
3463
Michael Wright842500e2015-03-13 17:32:02 -07003464bool TouchInputMapper::hasExternalStylus() const {
3465 return mExternalStylusConnected;
3466}
3467
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3469 int32_t oldDeviceMode = mDeviceMode;
3470
Michael Wright842500e2015-03-13 17:32:02 -07003471 resolveExternalStylusPresence();
3472
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 // Determine device mode.
3474 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3475 && mConfig.pointerGesturesEnabled) {
3476 mSource = AINPUT_SOURCE_MOUSE;
3477 mDeviceMode = DEVICE_MODE_POINTER;
3478 if (hasStylus()) {
3479 mSource |= AINPUT_SOURCE_STYLUS;
3480 }
3481 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3482 && mParameters.hasAssociatedDisplay) {
3483 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3484 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003485 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 mSource |= AINPUT_SOURCE_STYLUS;
3487 }
Michael Wright2f78b682015-06-12 15:25:08 +01003488 if (hasExternalStylus()) {
3489 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3492 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3493 mDeviceMode = DEVICE_MODE_NAVIGATION;
3494 } else {
3495 mSource = AINPUT_SOURCE_TOUCHPAD;
3496 mDeviceMode = DEVICE_MODE_UNSCALED;
3497 }
3498
3499 // Ensure we have valid X and Y axes.
3500 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3501 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3502 "The device will be inoperable.", getDeviceName().string());
3503 mDeviceMode = DEVICE_MODE_DISABLED;
3504 return;
3505 }
3506
3507 // Raw width and height in the natural orientation.
3508 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3509 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3510
3511 // Get associated display dimensions.
3512 DisplayViewport newViewport;
3513 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003514 const String8* uniqueDisplayId = NULL;
3515 ViewportType viewportTypeToUse;
3516
3517 if (mParameters.associatedDisplayIsExternal) {
3518 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3519 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3520 // If the IDC file specified a unique display Id, then it expects to be linked to a
3521 // virtual display with the same unique ID.
3522 uniqueDisplayId = &mParameters.uniqueDisplayId;
3523 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3524 } else {
3525 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3526 }
3527
3528 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3530 "display. The device will be inoperable until the display size "
3531 "becomes available.",
3532 getDeviceName().string());
3533 mDeviceMode = DEVICE_MODE_DISABLED;
3534 return;
3535 }
3536 } else {
3537 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3538 }
3539 bool viewportChanged = mViewport != newViewport;
3540 if (viewportChanged) {
3541 mViewport = newViewport;
3542
3543 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3544 // Convert rotated viewport to natural surface coordinates.
3545 int32_t naturalLogicalWidth, naturalLogicalHeight;
3546 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3547 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3548 int32_t naturalDeviceWidth, naturalDeviceHeight;
3549 switch (mViewport.orientation) {
3550 case DISPLAY_ORIENTATION_90:
3551 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3552 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3553 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3554 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3555 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3556 naturalPhysicalTop = mViewport.physicalLeft;
3557 naturalDeviceWidth = mViewport.deviceHeight;
3558 naturalDeviceHeight = mViewport.deviceWidth;
3559 break;
3560 case DISPLAY_ORIENTATION_180:
3561 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3562 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3563 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3564 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3565 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3566 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3567 naturalDeviceWidth = mViewport.deviceWidth;
3568 naturalDeviceHeight = mViewport.deviceHeight;
3569 break;
3570 case DISPLAY_ORIENTATION_270:
3571 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3572 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3573 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3574 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3575 naturalPhysicalLeft = mViewport.physicalTop;
3576 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3577 naturalDeviceWidth = mViewport.deviceHeight;
3578 naturalDeviceHeight = mViewport.deviceWidth;
3579 break;
3580 case DISPLAY_ORIENTATION_0:
3581 default:
3582 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3583 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3584 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3585 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3586 naturalPhysicalLeft = mViewport.physicalLeft;
3587 naturalPhysicalTop = mViewport.physicalTop;
3588 naturalDeviceWidth = mViewport.deviceWidth;
3589 naturalDeviceHeight = mViewport.deviceHeight;
3590 break;
3591 }
3592
3593 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3594 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3595 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3596 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3597
3598 mSurfaceOrientation = mParameters.orientationAware ?
3599 mViewport.orientation : DISPLAY_ORIENTATION_0;
3600 } else {
3601 mSurfaceWidth = rawWidth;
3602 mSurfaceHeight = rawHeight;
3603 mSurfaceLeft = 0;
3604 mSurfaceTop = 0;
3605 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3606 }
3607 }
3608
3609 // If moving between pointer modes, need to reset some state.
3610 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3611 if (deviceModeChanged) {
3612 mOrientedRanges.clear();
3613 }
3614
3615 // Create pointer controller if needed.
3616 if (mDeviceMode == DEVICE_MODE_POINTER ||
3617 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3618 if (mPointerController == NULL) {
3619 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3620 }
3621 } else {
3622 mPointerController.clear();
3623 }
3624
3625 if (viewportChanged || deviceModeChanged) {
3626 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3627 "display id %d",
3628 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3629 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3630
3631 // Configure X and Y factors.
3632 mXScale = float(mSurfaceWidth) / rawWidth;
3633 mYScale = float(mSurfaceHeight) / rawHeight;
3634 mXTranslate = -mSurfaceLeft;
3635 mYTranslate = -mSurfaceTop;
3636 mXPrecision = 1.0f / mXScale;
3637 mYPrecision = 1.0f / mYScale;
3638
3639 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3640 mOrientedRanges.x.source = mSource;
3641 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3642 mOrientedRanges.y.source = mSource;
3643
3644 configureVirtualKeys();
3645
3646 // Scale factor for terms that are not oriented in a particular axis.
3647 // If the pixels are square then xScale == yScale otherwise we fake it
3648 // by choosing an average.
3649 mGeometricScale = avg(mXScale, mYScale);
3650
3651 // Size of diagonal axis.
3652 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3653
3654 // Size factors.
3655 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3656 if (mRawPointerAxes.touchMajor.valid
3657 && mRawPointerAxes.touchMajor.maxValue != 0) {
3658 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3659 } else if (mRawPointerAxes.toolMajor.valid
3660 && mRawPointerAxes.toolMajor.maxValue != 0) {
3661 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3662 } else {
3663 mSizeScale = 0.0f;
3664 }
3665
3666 mOrientedRanges.haveTouchSize = true;
3667 mOrientedRanges.haveToolSize = true;
3668 mOrientedRanges.haveSize = true;
3669
3670 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3671 mOrientedRanges.touchMajor.source = mSource;
3672 mOrientedRanges.touchMajor.min = 0;
3673 mOrientedRanges.touchMajor.max = diagonalSize;
3674 mOrientedRanges.touchMajor.flat = 0;
3675 mOrientedRanges.touchMajor.fuzz = 0;
3676 mOrientedRanges.touchMajor.resolution = 0;
3677
3678 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3679 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3680
3681 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3682 mOrientedRanges.toolMajor.source = mSource;
3683 mOrientedRanges.toolMajor.min = 0;
3684 mOrientedRanges.toolMajor.max = diagonalSize;
3685 mOrientedRanges.toolMajor.flat = 0;
3686 mOrientedRanges.toolMajor.fuzz = 0;
3687 mOrientedRanges.toolMajor.resolution = 0;
3688
3689 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3690 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3691
3692 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3693 mOrientedRanges.size.source = mSource;
3694 mOrientedRanges.size.min = 0;
3695 mOrientedRanges.size.max = 1.0;
3696 mOrientedRanges.size.flat = 0;
3697 mOrientedRanges.size.fuzz = 0;
3698 mOrientedRanges.size.resolution = 0;
3699 } else {
3700 mSizeScale = 0.0f;
3701 }
3702
3703 // Pressure factors.
3704 mPressureScale = 0;
3705 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3706 || mCalibration.pressureCalibration
3707 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3708 if (mCalibration.havePressureScale) {
3709 mPressureScale = mCalibration.pressureScale;
3710 } else if (mRawPointerAxes.pressure.valid
3711 && mRawPointerAxes.pressure.maxValue != 0) {
3712 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3713 }
3714 }
3715
3716 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3717 mOrientedRanges.pressure.source = mSource;
3718 mOrientedRanges.pressure.min = 0;
3719 mOrientedRanges.pressure.max = 1.0;
3720 mOrientedRanges.pressure.flat = 0;
3721 mOrientedRanges.pressure.fuzz = 0;
3722 mOrientedRanges.pressure.resolution = 0;
3723
3724 // Tilt
3725 mTiltXCenter = 0;
3726 mTiltXScale = 0;
3727 mTiltYCenter = 0;
3728 mTiltYScale = 0;
3729 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3730 if (mHaveTilt) {
3731 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3732 mRawPointerAxes.tiltX.maxValue);
3733 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3734 mRawPointerAxes.tiltY.maxValue);
3735 mTiltXScale = M_PI / 180;
3736 mTiltYScale = M_PI / 180;
3737
3738 mOrientedRanges.haveTilt = true;
3739
3740 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3741 mOrientedRanges.tilt.source = mSource;
3742 mOrientedRanges.tilt.min = 0;
3743 mOrientedRanges.tilt.max = M_PI_2;
3744 mOrientedRanges.tilt.flat = 0;
3745 mOrientedRanges.tilt.fuzz = 0;
3746 mOrientedRanges.tilt.resolution = 0;
3747 }
3748
3749 // Orientation
3750 mOrientationScale = 0;
3751 if (mHaveTilt) {
3752 mOrientedRanges.haveOrientation = true;
3753
3754 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3755 mOrientedRanges.orientation.source = mSource;
3756 mOrientedRanges.orientation.min = -M_PI;
3757 mOrientedRanges.orientation.max = M_PI;
3758 mOrientedRanges.orientation.flat = 0;
3759 mOrientedRanges.orientation.fuzz = 0;
3760 mOrientedRanges.orientation.resolution = 0;
3761 } else if (mCalibration.orientationCalibration !=
3762 Calibration::ORIENTATION_CALIBRATION_NONE) {
3763 if (mCalibration.orientationCalibration
3764 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3765 if (mRawPointerAxes.orientation.valid) {
3766 if (mRawPointerAxes.orientation.maxValue > 0) {
3767 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3768 } else if (mRawPointerAxes.orientation.minValue < 0) {
3769 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3770 } else {
3771 mOrientationScale = 0;
3772 }
3773 }
3774 }
3775
3776 mOrientedRanges.haveOrientation = true;
3777
3778 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3779 mOrientedRanges.orientation.source = mSource;
3780 mOrientedRanges.orientation.min = -M_PI_2;
3781 mOrientedRanges.orientation.max = M_PI_2;
3782 mOrientedRanges.orientation.flat = 0;
3783 mOrientedRanges.orientation.fuzz = 0;
3784 mOrientedRanges.orientation.resolution = 0;
3785 }
3786
3787 // Distance
3788 mDistanceScale = 0;
3789 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3790 if (mCalibration.distanceCalibration
3791 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3792 if (mCalibration.haveDistanceScale) {
3793 mDistanceScale = mCalibration.distanceScale;
3794 } else {
3795 mDistanceScale = 1.0f;
3796 }
3797 }
3798
3799 mOrientedRanges.haveDistance = true;
3800
3801 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3802 mOrientedRanges.distance.source = mSource;
3803 mOrientedRanges.distance.min =
3804 mRawPointerAxes.distance.minValue * mDistanceScale;
3805 mOrientedRanges.distance.max =
3806 mRawPointerAxes.distance.maxValue * mDistanceScale;
3807 mOrientedRanges.distance.flat = 0;
3808 mOrientedRanges.distance.fuzz =
3809 mRawPointerAxes.distance.fuzz * mDistanceScale;
3810 mOrientedRanges.distance.resolution = 0;
3811 }
3812
3813 // Compute oriented precision, scales and ranges.
3814 // Note that the maximum value reported is an inclusive maximum value so it is one
3815 // unit less than the total width or height of surface.
3816 switch (mSurfaceOrientation) {
3817 case DISPLAY_ORIENTATION_90:
3818 case DISPLAY_ORIENTATION_270:
3819 mOrientedXPrecision = mYPrecision;
3820 mOrientedYPrecision = mXPrecision;
3821
3822 mOrientedRanges.x.min = mYTranslate;
3823 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3824 mOrientedRanges.x.flat = 0;
3825 mOrientedRanges.x.fuzz = 0;
3826 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3827
3828 mOrientedRanges.y.min = mXTranslate;
3829 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3830 mOrientedRanges.y.flat = 0;
3831 mOrientedRanges.y.fuzz = 0;
3832 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3833 break;
3834
3835 default:
3836 mOrientedXPrecision = mXPrecision;
3837 mOrientedYPrecision = mYPrecision;
3838
3839 mOrientedRanges.x.min = mXTranslate;
3840 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3841 mOrientedRanges.x.flat = 0;
3842 mOrientedRanges.x.fuzz = 0;
3843 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3844
3845 mOrientedRanges.y.min = mYTranslate;
3846 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3847 mOrientedRanges.y.flat = 0;
3848 mOrientedRanges.y.fuzz = 0;
3849 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3850 break;
3851 }
3852
Jason Gerecke71b16e82014-03-10 09:47:59 -07003853 // Location
3854 updateAffineTransformation();
3855
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 if (mDeviceMode == DEVICE_MODE_POINTER) {
3857 // Compute pointer gesture detection parameters.
3858 float rawDiagonal = hypotf(rawWidth, rawHeight);
3859 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3860
3861 // Scale movements such that one whole swipe of the touch pad covers a
3862 // given area relative to the diagonal size of the display when no acceleration
3863 // is applied.
3864 // Assume that the touch pad has a square aspect ratio such that movements in
3865 // X and Y of the same number of raw units cover the same physical distance.
3866 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3867 * displayDiagonal / rawDiagonal;
3868 mPointerYMovementScale = mPointerXMovementScale;
3869
3870 // Scale zooms to cover a smaller range of the display than movements do.
3871 // This value determines the area around the pointer that is affected by freeform
3872 // pointer gestures.
3873 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3874 * displayDiagonal / rawDiagonal;
3875 mPointerYZoomScale = mPointerXZoomScale;
3876
3877 // Max width between pointers to detect a swipe gesture is more than some fraction
3878 // of the diagonal axis of the touch pad. Touches that are wider than this are
3879 // translated into freeform gestures.
3880 mPointerGestureMaxSwipeWidth =
3881 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3882
3883 // Abort current pointer usages because the state has changed.
3884 abortPointerUsage(when, 0 /*policyFlags*/);
3885 }
3886
3887 // Inform the dispatcher about the changes.
3888 *outResetNeeded = true;
3889 bumpGeneration();
3890 }
3891}
3892
3893void TouchInputMapper::dumpSurface(String8& dump) {
3894 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3895 "logicalFrame=[%d, %d, %d, %d], "
3896 "physicalFrame=[%d, %d, %d, %d], "
3897 "deviceSize=[%d, %d]\n",
3898 mViewport.displayId, mViewport.orientation,
3899 mViewport.logicalLeft, mViewport.logicalTop,
3900 mViewport.logicalRight, mViewport.logicalBottom,
3901 mViewport.physicalLeft, mViewport.physicalTop,
3902 mViewport.physicalRight, mViewport.physicalBottom,
3903 mViewport.deviceWidth, mViewport.deviceHeight);
3904
3905 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3906 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3907 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3908 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3909 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3910}
3911
3912void TouchInputMapper::configureVirtualKeys() {
3913 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3914 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3915
3916 mVirtualKeys.clear();
3917
3918 if (virtualKeyDefinitions.size() == 0) {
3919 return;
3920 }
3921
3922 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3923
3924 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3925 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3926 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3927 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3928
3929 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3930 const VirtualKeyDefinition& virtualKeyDefinition =
3931 virtualKeyDefinitions[i];
3932
3933 mVirtualKeys.add();
3934 VirtualKey& virtualKey = mVirtualKeys.editTop();
3935
3936 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3937 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003938 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003940 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3941 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3943 virtualKey.scanCode);
3944 mVirtualKeys.pop(); // drop the key
3945 continue;
3946 }
3947
3948 virtualKey.keyCode = keyCode;
3949 virtualKey.flags = flags;
3950
3951 // convert the key definition's display coordinates into touch coordinates for a hit box
3952 int32_t halfWidth = virtualKeyDefinition.width / 2;
3953 int32_t halfHeight = virtualKeyDefinition.height / 2;
3954
3955 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3956 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3957 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3958 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3959 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3960 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3961 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3962 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3963 }
3964}
3965
3966void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3967 if (!mVirtualKeys.isEmpty()) {
3968 dump.append(INDENT3 "Virtual Keys:\n");
3969
3970 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3971 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003972 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3974 i, virtualKey.scanCode, virtualKey.keyCode,
3975 virtualKey.hitLeft, virtualKey.hitRight,
3976 virtualKey.hitTop, virtualKey.hitBottom);
3977 }
3978 }
3979}
3980
3981void TouchInputMapper::parseCalibration() {
3982 const PropertyMap& in = getDevice()->getConfiguration();
3983 Calibration& out = mCalibration;
3984
3985 // Size
3986 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3987 String8 sizeCalibrationString;
3988 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3989 if (sizeCalibrationString == "none") {
3990 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3991 } else if (sizeCalibrationString == "geometric") {
3992 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3993 } else if (sizeCalibrationString == "diameter") {
3994 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3995 } else if (sizeCalibrationString == "box") {
3996 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3997 } else if (sizeCalibrationString == "area") {
3998 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3999 } else if (sizeCalibrationString != "default") {
4000 ALOGW("Invalid value for touch.size.calibration: '%s'",
4001 sizeCalibrationString.string());
4002 }
4003 }
4004
4005 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4006 out.sizeScale);
4007 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4008 out.sizeBias);
4009 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4010 out.sizeIsSummed);
4011
4012 // Pressure
4013 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4014 String8 pressureCalibrationString;
4015 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4016 if (pressureCalibrationString == "none") {
4017 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4018 } else if (pressureCalibrationString == "physical") {
4019 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4020 } else if (pressureCalibrationString == "amplitude") {
4021 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4022 } else if (pressureCalibrationString != "default") {
4023 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4024 pressureCalibrationString.string());
4025 }
4026 }
4027
4028 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4029 out.pressureScale);
4030
4031 // Orientation
4032 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4033 String8 orientationCalibrationString;
4034 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4035 if (orientationCalibrationString == "none") {
4036 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4037 } else if (orientationCalibrationString == "interpolated") {
4038 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4039 } else if (orientationCalibrationString == "vector") {
4040 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4041 } else if (orientationCalibrationString != "default") {
4042 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4043 orientationCalibrationString.string());
4044 }
4045 }
4046
4047 // Distance
4048 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4049 String8 distanceCalibrationString;
4050 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4051 if (distanceCalibrationString == "none") {
4052 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4053 } else if (distanceCalibrationString == "scaled") {
4054 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4055 } else if (distanceCalibrationString != "default") {
4056 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4057 distanceCalibrationString.string());
4058 }
4059 }
4060
4061 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4062 out.distanceScale);
4063
4064 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4065 String8 coverageCalibrationString;
4066 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4067 if (coverageCalibrationString == "none") {
4068 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4069 } else if (coverageCalibrationString == "box") {
4070 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4071 } else if (coverageCalibrationString != "default") {
4072 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4073 coverageCalibrationString.string());
4074 }
4075 }
4076}
4077
4078void TouchInputMapper::resolveCalibration() {
4079 // Size
4080 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4081 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4082 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4083 }
4084 } else {
4085 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4086 }
4087
4088 // Pressure
4089 if (mRawPointerAxes.pressure.valid) {
4090 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4091 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4092 }
4093 } else {
4094 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4095 }
4096
4097 // Orientation
4098 if (mRawPointerAxes.orientation.valid) {
4099 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4100 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4101 }
4102 } else {
4103 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4104 }
4105
4106 // Distance
4107 if (mRawPointerAxes.distance.valid) {
4108 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4109 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4110 }
4111 } else {
4112 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4113 }
4114
4115 // Coverage
4116 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4117 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4118 }
4119}
4120
4121void TouchInputMapper::dumpCalibration(String8& dump) {
4122 dump.append(INDENT3 "Calibration:\n");
4123
4124 // Size
4125 switch (mCalibration.sizeCalibration) {
4126 case Calibration::SIZE_CALIBRATION_NONE:
4127 dump.append(INDENT4 "touch.size.calibration: none\n");
4128 break;
4129 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4130 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4131 break;
4132 case Calibration::SIZE_CALIBRATION_DIAMETER:
4133 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4134 break;
4135 case Calibration::SIZE_CALIBRATION_BOX:
4136 dump.append(INDENT4 "touch.size.calibration: box\n");
4137 break;
4138 case Calibration::SIZE_CALIBRATION_AREA:
4139 dump.append(INDENT4 "touch.size.calibration: area\n");
4140 break;
4141 default:
4142 ALOG_ASSERT(false);
4143 }
4144
4145 if (mCalibration.haveSizeScale) {
4146 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4147 mCalibration.sizeScale);
4148 }
4149
4150 if (mCalibration.haveSizeBias) {
4151 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4152 mCalibration.sizeBias);
4153 }
4154
4155 if (mCalibration.haveSizeIsSummed) {
4156 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4157 toString(mCalibration.sizeIsSummed));
4158 }
4159
4160 // Pressure
4161 switch (mCalibration.pressureCalibration) {
4162 case Calibration::PRESSURE_CALIBRATION_NONE:
4163 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4164 break;
4165 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4166 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4167 break;
4168 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4169 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4170 break;
4171 default:
4172 ALOG_ASSERT(false);
4173 }
4174
4175 if (mCalibration.havePressureScale) {
4176 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4177 mCalibration.pressureScale);
4178 }
4179
4180 // Orientation
4181 switch (mCalibration.orientationCalibration) {
4182 case Calibration::ORIENTATION_CALIBRATION_NONE:
4183 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4184 break;
4185 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4186 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4187 break;
4188 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4189 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4190 break;
4191 default:
4192 ALOG_ASSERT(false);
4193 }
4194
4195 // Distance
4196 switch (mCalibration.distanceCalibration) {
4197 case Calibration::DISTANCE_CALIBRATION_NONE:
4198 dump.append(INDENT4 "touch.distance.calibration: none\n");
4199 break;
4200 case Calibration::DISTANCE_CALIBRATION_SCALED:
4201 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4202 break;
4203 default:
4204 ALOG_ASSERT(false);
4205 }
4206
4207 if (mCalibration.haveDistanceScale) {
4208 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4209 mCalibration.distanceScale);
4210 }
4211
4212 switch (mCalibration.coverageCalibration) {
4213 case Calibration::COVERAGE_CALIBRATION_NONE:
4214 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4215 break;
4216 case Calibration::COVERAGE_CALIBRATION_BOX:
4217 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4218 break;
4219 default:
4220 ALOG_ASSERT(false);
4221 }
4222}
4223
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004224void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4225 dump.append(INDENT3 "Affine Transformation:\n");
4226
4227 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4228 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4229 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4230 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4231 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4232 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4233}
4234
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004235void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004236 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4237 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004238}
4239
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240void TouchInputMapper::reset(nsecs_t when) {
4241 mCursorButtonAccumulator.reset(getDevice());
4242 mCursorScrollAccumulator.reset(getDevice());
4243 mTouchButtonAccumulator.reset(getDevice());
4244
4245 mPointerVelocityControl.reset();
4246 mWheelXVelocityControl.reset();
4247 mWheelYVelocityControl.reset();
4248
Michael Wright842500e2015-03-13 17:32:02 -07004249 mRawStatesPending.clear();
4250 mCurrentRawState.clear();
4251 mCurrentCookedState.clear();
4252 mLastRawState.clear();
4253 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 mPointerUsage = POINTER_USAGE_NONE;
4255 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004256 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004257 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 mDownTime = 0;
4259
4260 mCurrentVirtualKey.down = false;
4261
4262 mPointerGesture.reset();
4263 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004264 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265
4266 if (mPointerController != NULL) {
4267 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4268 mPointerController->clearSpots();
4269 }
4270
4271 InputMapper::reset(when);
4272}
4273
Michael Wright842500e2015-03-13 17:32:02 -07004274void TouchInputMapper::resetExternalStylus() {
4275 mExternalStylusState.clear();
4276 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004277 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004278 mExternalStylusDataPending = false;
4279}
4280
Michael Wright43fd19f2015-04-21 19:02:58 +01004281void TouchInputMapper::clearStylusDataPendingFlags() {
4282 mExternalStylusDataPending = false;
4283 mExternalStylusFusionTimeout = LLONG_MAX;
4284}
4285
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286void TouchInputMapper::process(const RawEvent* rawEvent) {
4287 mCursorButtonAccumulator.process(rawEvent);
4288 mCursorScrollAccumulator.process(rawEvent);
4289 mTouchButtonAccumulator.process(rawEvent);
4290
4291 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4292 sync(rawEvent->when);
4293 }
4294}
4295
4296void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004297 const RawState* last = mRawStatesPending.isEmpty() ?
4298 &mCurrentRawState : &mRawStatesPending.top();
4299
4300 // Push a new state.
4301 mRawStatesPending.push();
4302 RawState* next = &mRawStatesPending.editTop();
4303 next->clear();
4304 next->when = when;
4305
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004307 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 | mCursorButtonAccumulator.getButtonState();
4309
Michael Wright842500e2015-03-13 17:32:02 -07004310 // Sync scroll
4311 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4312 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 mCursorScrollAccumulator.finishSync();
4314
Michael Wright842500e2015-03-13 17:32:02 -07004315 // Sync touch
4316 syncTouch(when, next);
4317
4318 // Assign pointer ids.
4319 if (!mHavePointerIds) {
4320 assignPointerIds(last, next);
4321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
4323#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004324 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4325 "hovering ids 0x%08x -> 0x%08x",
4326 last->rawPointerData.pointerCount,
4327 next->rawPointerData.pointerCount,
4328 last->rawPointerData.touchingIdBits.value,
4329 next->rawPointerData.touchingIdBits.value,
4330 last->rawPointerData.hoveringIdBits.value,
4331 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332#endif
4333
Michael Wright842500e2015-03-13 17:32:02 -07004334 processRawTouches(false /*timeout*/);
4335}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Michael Wright842500e2015-03-13 17:32:02 -07004337void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4339 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004340 mCurrentRawState.clear();
4341 mRawStatesPending.clear();
4342 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
4344
Michael Wright842500e2015-03-13 17:32:02 -07004345 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4346 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4347 // touching the current state will only observe the events that have been dispatched to the
4348 // rest of the pipeline.
4349 const size_t N = mRawStatesPending.size();
4350 size_t count;
4351 for(count = 0; count < N; count++) {
4352 const RawState& next = mRawStatesPending[count];
4353
4354 // A failure to assign the stylus id means that we're waiting on stylus data
4355 // and so should defer the rest of the pipeline.
4356 if (assignExternalStylusId(next, timeout)) {
4357 break;
4358 }
4359
4360 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004361 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004362 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004363 if (mCurrentRawState.when < mLastRawState.when) {
4364 mCurrentRawState.when = mLastRawState.when;
4365 }
Michael Wright842500e2015-03-13 17:32:02 -07004366 cookAndDispatch(mCurrentRawState.when);
4367 }
4368 if (count != 0) {
4369 mRawStatesPending.removeItemsAt(0, count);
4370 }
4371
Michael Wright842500e2015-03-13 17:32:02 -07004372 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004373 if (timeout) {
4374 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4375 clearStylusDataPendingFlags();
4376 mCurrentRawState.copyFrom(mLastRawState);
4377#if DEBUG_STYLUS_FUSION
4378 ALOGD("Timeout expired, synthesizing event with new stylus data");
4379#endif
4380 cookAndDispatch(when);
4381 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4382 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4383 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4384 }
Michael Wright842500e2015-03-13 17:32:02 -07004385 }
4386}
4387
4388void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4389 // Always start with a clean state.
4390 mCurrentCookedState.clear();
4391
4392 // Apply stylus buttons to current raw state.
4393 applyExternalStylusButtonState(when);
4394
4395 // Handle policy on initial down or hover events.
4396 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4397 && mCurrentRawState.rawPointerData.pointerCount != 0;
4398
4399 uint32_t policyFlags = 0;
4400 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4401 if (initialDown || buttonsPressed) {
4402 // If this is a touch screen, hide the pointer on an initial down.
4403 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4404 getContext()->fadePointer();
4405 }
4406
4407 if (mParameters.wake) {
4408 policyFlags |= POLICY_FLAG_WAKE;
4409 }
4410 }
4411
4412 // Consume raw off-screen touches before cooking pointer data.
4413 // If touches are consumed, subsequent code will not receive any pointer data.
4414 if (consumeRawTouches(when, policyFlags)) {
4415 mCurrentRawState.rawPointerData.clear();
4416 }
4417
4418 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4419 // with cooked pointer data that has the same ids and indices as the raw data.
4420 // The following code can use either the raw or cooked data, as needed.
4421 cookPointerData();
4422
4423 // Apply stylus pressure to current cooked state.
4424 applyExternalStylusTouchState(when);
4425
4426 // Synthesize key down from raw buttons if needed.
4427 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004428 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004429
4430 // Dispatch the touches either directly or by translation through a pointer on screen.
4431 if (mDeviceMode == DEVICE_MODE_POINTER) {
4432 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4433 !idBits.isEmpty(); ) {
4434 uint32_t id = idBits.clearFirstMarkedBit();
4435 const RawPointerData::Pointer& pointer =
4436 mCurrentRawState.rawPointerData.pointerForId(id);
4437 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4438 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4439 mCurrentCookedState.stylusIdBits.markBit(id);
4440 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4441 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4442 mCurrentCookedState.fingerIdBits.markBit(id);
4443 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4444 mCurrentCookedState.mouseIdBits.markBit(id);
4445 }
4446 }
4447 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4448 !idBits.isEmpty(); ) {
4449 uint32_t id = idBits.clearFirstMarkedBit();
4450 const RawPointerData::Pointer& pointer =
4451 mCurrentRawState.rawPointerData.pointerForId(id);
4452 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4453 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4454 mCurrentCookedState.stylusIdBits.markBit(id);
4455 }
4456 }
4457
4458 // Stylus takes precedence over all tools, then mouse, then finger.
4459 PointerUsage pointerUsage = mPointerUsage;
4460 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4461 mCurrentCookedState.mouseIdBits.clear();
4462 mCurrentCookedState.fingerIdBits.clear();
4463 pointerUsage = POINTER_USAGE_STYLUS;
4464 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4465 mCurrentCookedState.fingerIdBits.clear();
4466 pointerUsage = POINTER_USAGE_MOUSE;
4467 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4468 isPointerDown(mCurrentRawState.buttonState)) {
4469 pointerUsage = POINTER_USAGE_GESTURES;
4470 }
4471
4472 dispatchPointerUsage(when, policyFlags, pointerUsage);
4473 } else {
4474 if (mDeviceMode == DEVICE_MODE_DIRECT
4475 && mConfig.showTouches && mPointerController != NULL) {
4476 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4477 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4478
4479 mPointerController->setButtonState(mCurrentRawState.buttonState);
4480 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4481 mCurrentCookedState.cookedPointerData.idToIndex,
4482 mCurrentCookedState.cookedPointerData.touchingIdBits);
4483 }
4484
Michael Wright8e812822015-06-22 16:18:21 +01004485 if (!mCurrentMotionAborted) {
4486 dispatchButtonRelease(when, policyFlags);
4487 dispatchHoverExit(when, policyFlags);
4488 dispatchTouches(when, policyFlags);
4489 dispatchHoverEnterAndMove(when, policyFlags);
4490 dispatchButtonPress(when, policyFlags);
4491 }
4492
4493 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4494 mCurrentMotionAborted = false;
4495 }
Michael Wright842500e2015-03-13 17:32:02 -07004496 }
4497
4498 // Synthesize key up from raw buttons if needed.
4499 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004500 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501
4502 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004503 mCurrentRawState.rawVScroll = 0;
4504 mCurrentRawState.rawHScroll = 0;
4505
4506 // Copy current touch to last touch in preparation for the next cycle.
4507 mLastRawState.copyFrom(mCurrentRawState);
4508 mLastCookedState.copyFrom(mCurrentCookedState);
4509}
4510
4511void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004512 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004513 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4514 }
4515}
4516
4517void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004518 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4519 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004520
Michael Wright53dca3a2015-04-23 17:39:53 +01004521 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4522 float pressure = mExternalStylusState.pressure;
4523 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4524 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4525 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4526 }
4527 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4528 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4529
4530 PointerProperties& properties =
4531 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004532 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4533 properties.toolType = mExternalStylusState.toolType;
4534 }
4535 }
4536}
4537
4538bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4539 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4540 return false;
4541 }
4542
4543 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4544 && state.rawPointerData.pointerCount != 0;
4545 if (initialDown) {
4546 if (mExternalStylusState.pressure != 0.0f) {
4547#if DEBUG_STYLUS_FUSION
4548 ALOGD("Have both stylus and touch data, beginning fusion");
4549#endif
4550 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4551 } else if (timeout) {
4552#if DEBUG_STYLUS_FUSION
4553 ALOGD("Timeout expired, assuming touch is not a stylus.");
4554#endif
4555 resetExternalStylus();
4556 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004557 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4558 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004559 }
4560#if DEBUG_STYLUS_FUSION
4561 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004562 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004563#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004564 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004565 return true;
4566 }
4567 }
4568
4569 // Check if the stylus pointer has gone up.
4570 if (mExternalStylusId != -1 &&
4571 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4572#if DEBUG_STYLUS_FUSION
4573 ALOGD("Stylus pointer is going up");
4574#endif
4575 mExternalStylusId = -1;
4576 }
4577
4578 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579}
4580
4581void TouchInputMapper::timeoutExpired(nsecs_t when) {
4582 if (mDeviceMode == DEVICE_MODE_POINTER) {
4583 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4584 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4585 }
Michael Wright842500e2015-03-13 17:32:02 -07004586 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004587 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004588 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004589 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4590 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004591 }
4592 }
4593}
4594
4595void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004596 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004597 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004598 // We're either in the middle of a fused stream of data or we're waiting on data before
4599 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4600 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004601 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004602 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604}
4605
4606bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4607 // Check for release of a virtual key.
4608 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004609 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 // Pointer went up while virtual key was down.
4611 mCurrentVirtualKey.down = false;
4612 if (!mCurrentVirtualKey.ignored) {
4613#if DEBUG_VIRTUAL_KEYS
4614 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4615 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4616#endif
4617 dispatchVirtualKey(when, policyFlags,
4618 AKEY_EVENT_ACTION_UP,
4619 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4620 }
4621 return true;
4622 }
4623
Michael Wright842500e2015-03-13 17:32:02 -07004624 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4625 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4626 const RawPointerData::Pointer& pointer =
4627 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4629 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4630 // Pointer is still within the space of the virtual key.
4631 return true;
4632 }
4633 }
4634
4635 // Pointer left virtual key area or another pointer also went down.
4636 // Send key cancellation but do not consume the touch yet.
4637 // This is useful when the user swipes through from the virtual key area
4638 // into the main display surface.
4639 mCurrentVirtualKey.down = false;
4640 if (!mCurrentVirtualKey.ignored) {
4641#if DEBUG_VIRTUAL_KEYS
4642 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4643 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4644#endif
4645 dispatchVirtualKey(when, policyFlags,
4646 AKEY_EVENT_ACTION_UP,
4647 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4648 | AKEY_EVENT_FLAG_CANCELED);
4649 }
4650 }
4651
Michael Wright842500e2015-03-13 17:32:02 -07004652 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4653 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004655 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4656 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4658 // If exactly one pointer went down, check for virtual key hit.
4659 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004660 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4662 if (virtualKey) {
4663 mCurrentVirtualKey.down = true;
4664 mCurrentVirtualKey.downTime = when;
4665 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4666 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4667 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4668 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4669
4670 if (!mCurrentVirtualKey.ignored) {
4671#if DEBUG_VIRTUAL_KEYS
4672 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4673 mCurrentVirtualKey.keyCode,
4674 mCurrentVirtualKey.scanCode);
4675#endif
4676 dispatchVirtualKey(when, policyFlags,
4677 AKEY_EVENT_ACTION_DOWN,
4678 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4679 }
4680 }
4681 }
4682 return true;
4683 }
4684 }
4685
4686 // Disable all virtual key touches that happen within a short time interval of the
4687 // most recent touch within the screen area. The idea is to filter out stray
4688 // virtual key presses when interacting with the touch screen.
4689 //
4690 // Problems we're trying to solve:
4691 //
4692 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4693 // virtual key area that is implemented by a separate touch panel and accidentally
4694 // triggers a virtual key.
4695 //
4696 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4697 // area and accidentally triggers a virtual key. This often happens when virtual keys
4698 // are layed out below the screen near to where the on screen keyboard's space bar
4699 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004700 if (mConfig.virtualKeyQuietTime > 0 &&
4701 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4703 }
4704 return false;
4705}
4706
4707void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4708 int32_t keyEventAction, int32_t keyEventFlags) {
4709 int32_t keyCode = mCurrentVirtualKey.keyCode;
4710 int32_t scanCode = mCurrentVirtualKey.scanCode;
4711 nsecs_t downTime = mCurrentVirtualKey.downTime;
4712 int32_t metaState = mContext->getGlobalMetaState();
4713 policyFlags |= POLICY_FLAG_VIRTUAL;
4714
4715 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4716 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4717 getListener()->notifyKey(&args);
4718}
4719
Michael Wright8e812822015-06-22 16:18:21 +01004720void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4721 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4722 if (!currentIdBits.isEmpty()) {
4723 int32_t metaState = getContext()->getGlobalMetaState();
4724 int32_t buttonState = mCurrentCookedState.buttonState;
4725 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4726 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4727 mCurrentCookedState.cookedPointerData.pointerProperties,
4728 mCurrentCookedState.cookedPointerData.pointerCoords,
4729 mCurrentCookedState.cookedPointerData.idToIndex,
4730 currentIdBits, -1,
4731 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4732 mCurrentMotionAborted = true;
4733 }
4734}
4735
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004737 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4738 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004740 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741
4742 if (currentIdBits == lastIdBits) {
4743 if (!currentIdBits.isEmpty()) {
4744 // No pointer id changes so this is a move event.
4745 // The listener takes care of batching moves so we don't have to deal with that here.
4746 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004747 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004749 mCurrentCookedState.cookedPointerData.pointerProperties,
4750 mCurrentCookedState.cookedPointerData.pointerCoords,
4751 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 currentIdBits, -1,
4753 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4754 }
4755 } else {
4756 // There may be pointers going up and pointers going down and pointers moving
4757 // all at the same time.
4758 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4759 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4760 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4761 BitSet32 dispatchedIdBits(lastIdBits.value);
4762
4763 // Update last coordinates of pointers that have moved so that we observe the new
4764 // pointer positions at the same time as other pointers that have just gone up.
4765 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004766 mCurrentCookedState.cookedPointerData.pointerProperties,
4767 mCurrentCookedState.cookedPointerData.pointerCoords,
4768 mCurrentCookedState.cookedPointerData.idToIndex,
4769 mLastCookedState.cookedPointerData.pointerProperties,
4770 mLastCookedState.cookedPointerData.pointerCoords,
4771 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004773 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 moveNeeded = true;
4775 }
4776
4777 // Dispatch pointer up events.
4778 while (!upIdBits.isEmpty()) {
4779 uint32_t upId = upIdBits.clearFirstMarkedBit();
4780
4781 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004782 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004783 mLastCookedState.cookedPointerData.pointerProperties,
4784 mLastCookedState.cookedPointerData.pointerCoords,
4785 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004786 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 dispatchedIdBits.clearBit(upId);
4788 }
4789
4790 // Dispatch move events if any of the remaining pointers moved from their old locations.
4791 // Although applications receive new locations as part of individual pointer up
4792 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004793 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4795 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004796 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004797 mCurrentCookedState.cookedPointerData.pointerProperties,
4798 mCurrentCookedState.cookedPointerData.pointerCoords,
4799 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004800 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802
4803 // Dispatch pointer down events using the new pointer locations.
4804 while (!downIdBits.isEmpty()) {
4805 uint32_t downId = downIdBits.clearFirstMarkedBit();
4806 dispatchedIdBits.markBit(downId);
4807
4808 if (dispatchedIdBits.count() == 1) {
4809 // First pointer is going down. Set down time.
4810 mDownTime = when;
4811 }
4812
4813 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004814 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004815 mCurrentCookedState.cookedPointerData.pointerProperties,
4816 mCurrentCookedState.cookedPointerData.pointerCoords,
4817 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004818 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
4820 }
4821}
4822
4823void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4824 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004825 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4826 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 int32_t metaState = getContext()->getGlobalMetaState();
4828 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004829 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004830 mLastCookedState.cookedPointerData.pointerProperties,
4831 mLastCookedState.cookedPointerData.pointerCoords,
4832 mLastCookedState.cookedPointerData.idToIndex,
4833 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4835 mSentHoverEnter = false;
4836 }
4837}
4838
4839void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004840 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4841 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 int32_t metaState = getContext()->getGlobalMetaState();
4843 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004844 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004845 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004846 mCurrentCookedState.cookedPointerData.pointerProperties,
4847 mCurrentCookedState.cookedPointerData.pointerCoords,
4848 mCurrentCookedState.cookedPointerData.idToIndex,
4849 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4851 mSentHoverEnter = true;
4852 }
4853
4854 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004855 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004856 mCurrentRawState.buttonState, 0,
4857 mCurrentCookedState.cookedPointerData.pointerProperties,
4858 mCurrentCookedState.cookedPointerData.pointerCoords,
4859 mCurrentCookedState.cookedPointerData.idToIndex,
4860 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4862 }
4863}
4864
Michael Wright7b159c92015-05-14 14:48:03 +01004865void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4866 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4867 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4868 const int32_t metaState = getContext()->getGlobalMetaState();
4869 int32_t buttonState = mLastCookedState.buttonState;
4870 while (!releasedButtons.isEmpty()) {
4871 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4872 buttonState &= ~actionButton;
4873 dispatchMotion(when, policyFlags, mSource,
4874 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4875 0, metaState, buttonState, 0,
4876 mCurrentCookedState.cookedPointerData.pointerProperties,
4877 mCurrentCookedState.cookedPointerData.pointerCoords,
4878 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4879 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4880 }
4881}
4882
4883void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4884 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4885 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4886 const int32_t metaState = getContext()->getGlobalMetaState();
4887 int32_t buttonState = mLastCookedState.buttonState;
4888 while (!pressedButtons.isEmpty()) {
4889 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4890 buttonState |= actionButton;
4891 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4892 0, metaState, buttonState, 0,
4893 mCurrentCookedState.cookedPointerData.pointerProperties,
4894 mCurrentCookedState.cookedPointerData.pointerCoords,
4895 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4896 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4897 }
4898}
4899
4900const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4901 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4902 return cookedPointerData.touchingIdBits;
4903 }
4904 return cookedPointerData.hoveringIdBits;
4905}
4906
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004908 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909
Michael Wright842500e2015-03-13 17:32:02 -07004910 mCurrentCookedState.cookedPointerData.clear();
4911 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4912 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4913 mCurrentRawState.rawPointerData.hoveringIdBits;
4914 mCurrentCookedState.cookedPointerData.touchingIdBits =
4915 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916
Michael Wright7b159c92015-05-14 14:48:03 +01004917 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4918 mCurrentCookedState.buttonState = 0;
4919 } else {
4920 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4921 }
4922
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923 // Walk through the the active pointers and map device coordinates onto
4924 // surface coordinates and adjust for display orientation.
4925 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004926 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927
4928 // Size
4929 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4930 switch (mCalibration.sizeCalibration) {
4931 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4932 case Calibration::SIZE_CALIBRATION_DIAMETER:
4933 case Calibration::SIZE_CALIBRATION_BOX:
4934 case Calibration::SIZE_CALIBRATION_AREA:
4935 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4936 touchMajor = in.touchMajor;
4937 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4938 toolMajor = in.toolMajor;
4939 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4940 size = mRawPointerAxes.touchMinor.valid
4941 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4942 } else if (mRawPointerAxes.touchMajor.valid) {
4943 toolMajor = touchMajor = in.touchMajor;
4944 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4945 ? in.touchMinor : in.touchMajor;
4946 size = mRawPointerAxes.touchMinor.valid
4947 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4948 } else if (mRawPointerAxes.toolMajor.valid) {
4949 touchMajor = toolMajor = in.toolMajor;
4950 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4951 ? in.toolMinor : in.toolMajor;
4952 size = mRawPointerAxes.toolMinor.valid
4953 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4954 } else {
4955 ALOG_ASSERT(false, "No touch or tool axes. "
4956 "Size calibration should have been resolved to NONE.");
4957 touchMajor = 0;
4958 touchMinor = 0;
4959 toolMajor = 0;
4960 toolMinor = 0;
4961 size = 0;
4962 }
4963
4964 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004965 uint32_t touchingCount =
4966 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 if (touchingCount > 1) {
4968 touchMajor /= touchingCount;
4969 touchMinor /= touchingCount;
4970 toolMajor /= touchingCount;
4971 toolMinor /= touchingCount;
4972 size /= touchingCount;
4973 }
4974 }
4975
4976 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4977 touchMajor *= mGeometricScale;
4978 touchMinor *= mGeometricScale;
4979 toolMajor *= mGeometricScale;
4980 toolMinor *= mGeometricScale;
4981 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4982 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4983 touchMinor = touchMajor;
4984 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4985 toolMinor = toolMajor;
4986 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4987 touchMinor = touchMajor;
4988 toolMinor = toolMajor;
4989 }
4990
4991 mCalibration.applySizeScaleAndBias(&touchMajor);
4992 mCalibration.applySizeScaleAndBias(&touchMinor);
4993 mCalibration.applySizeScaleAndBias(&toolMajor);
4994 mCalibration.applySizeScaleAndBias(&toolMinor);
4995 size *= mSizeScale;
4996 break;
4997 default:
4998 touchMajor = 0;
4999 touchMinor = 0;
5000 toolMajor = 0;
5001 toolMinor = 0;
5002 size = 0;
5003 break;
5004 }
5005
5006 // Pressure
5007 float pressure;
5008 switch (mCalibration.pressureCalibration) {
5009 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5010 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5011 pressure = in.pressure * mPressureScale;
5012 break;
5013 default:
5014 pressure = in.isHovering ? 0 : 1;
5015 break;
5016 }
5017
5018 // Tilt and Orientation
5019 float tilt;
5020 float orientation;
5021 if (mHaveTilt) {
5022 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5023 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5024 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5025 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5026 } else {
5027 tilt = 0;
5028
5029 switch (mCalibration.orientationCalibration) {
5030 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5031 orientation = in.orientation * mOrientationScale;
5032 break;
5033 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5034 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5035 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5036 if (c1 != 0 || c2 != 0) {
5037 orientation = atan2f(c1, c2) * 0.5f;
5038 float confidence = hypotf(c1, c2);
5039 float scale = 1.0f + confidence / 16.0f;
5040 touchMajor *= scale;
5041 touchMinor /= scale;
5042 toolMajor *= scale;
5043 toolMinor /= scale;
5044 } else {
5045 orientation = 0;
5046 }
5047 break;
5048 }
5049 default:
5050 orientation = 0;
5051 }
5052 }
5053
5054 // Distance
5055 float distance;
5056 switch (mCalibration.distanceCalibration) {
5057 case Calibration::DISTANCE_CALIBRATION_SCALED:
5058 distance = in.distance * mDistanceScale;
5059 break;
5060 default:
5061 distance = 0;
5062 }
5063
5064 // Coverage
5065 int32_t rawLeft, rawTop, rawRight, rawBottom;
5066 switch (mCalibration.coverageCalibration) {
5067 case Calibration::COVERAGE_CALIBRATION_BOX:
5068 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5069 rawRight = in.toolMinor & 0x0000ffff;
5070 rawBottom = in.toolMajor & 0x0000ffff;
5071 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5072 break;
5073 default:
5074 rawLeft = rawTop = rawRight = rawBottom = 0;
5075 break;
5076 }
5077
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005078 // Adjust X,Y coords for device calibration
5079 // TODO: Adjust coverage coords?
5080 float xTransformed = in.x, yTransformed = in.y;
5081 mAffineTransform.applyTo(xTransformed, yTransformed);
5082
5083 // Adjust X, Y, and coverage coords for surface orientation.
5084 float x, y;
5085 float left, top, right, bottom;
5086
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 switch (mSurfaceOrientation) {
5088 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005089 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5090 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5092 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5093 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5094 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5095 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005096 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5098 }
5099 break;
5100 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005101 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5102 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5104 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5105 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5106 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5107 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005108 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5110 }
5111 break;
5112 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005113 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5114 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5116 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5117 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5118 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5119 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005120 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5122 }
5123 break;
5124 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005125 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5126 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5128 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5129 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5130 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5131 break;
5132 }
5133
5134 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005135 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 out.clear();
5137 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5138 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5139 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5140 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5141 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5142 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5143 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5144 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5145 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5146 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5147 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5148 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5150 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5151 } else {
5152 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5153 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5154 }
5155
5156 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005157 PointerProperties& properties =
5158 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 uint32_t id = in.id;
5160 properties.clear();
5161 properties.id = id;
5162 properties.toolType = in.toolType;
5163
5164 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005165 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167}
5168
5169void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5170 PointerUsage pointerUsage) {
5171 if (pointerUsage != mPointerUsage) {
5172 abortPointerUsage(when, policyFlags);
5173 mPointerUsage = pointerUsage;
5174 }
5175
5176 switch (mPointerUsage) {
5177 case POINTER_USAGE_GESTURES:
5178 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5179 break;
5180 case POINTER_USAGE_STYLUS:
5181 dispatchPointerStylus(when, policyFlags);
5182 break;
5183 case POINTER_USAGE_MOUSE:
5184 dispatchPointerMouse(when, policyFlags);
5185 break;
5186 default:
5187 break;
5188 }
5189}
5190
5191void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5192 switch (mPointerUsage) {
5193 case POINTER_USAGE_GESTURES:
5194 abortPointerGestures(when, policyFlags);
5195 break;
5196 case POINTER_USAGE_STYLUS:
5197 abortPointerStylus(when, policyFlags);
5198 break;
5199 case POINTER_USAGE_MOUSE:
5200 abortPointerMouse(when, policyFlags);
5201 break;
5202 default:
5203 break;
5204 }
5205
5206 mPointerUsage = POINTER_USAGE_NONE;
5207}
5208
5209void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5210 bool isTimeout) {
5211 // Update current gesture coordinates.
5212 bool cancelPreviousGesture, finishPreviousGesture;
5213 bool sendEvents = preparePointerGestures(when,
5214 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5215 if (!sendEvents) {
5216 return;
5217 }
5218 if (finishPreviousGesture) {
5219 cancelPreviousGesture = false;
5220 }
5221
5222 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005223 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5224 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225 if (finishPreviousGesture || cancelPreviousGesture) {
5226 mPointerController->clearSpots();
5227 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005228
5229 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5230 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5231 mPointerGesture.currentGestureIdToIndex,
5232 mPointerGesture.currentGestureIdBits);
5233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234 } else {
5235 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5236 }
5237
5238 // Show or hide the pointer if needed.
5239 switch (mPointerGesture.currentGestureMode) {
5240 case PointerGesture::NEUTRAL:
5241 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005242 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5243 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 // Remind the user of where the pointer is after finishing a gesture with spots.
5245 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5246 }
5247 break;
5248 case PointerGesture::TAP:
5249 case PointerGesture::TAP_DRAG:
5250 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5251 case PointerGesture::HOVER:
5252 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005253 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254 // Unfade the pointer when the current gesture manipulates the
5255 // area directly under the pointer.
5256 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5257 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 case PointerGesture::FREEFORM:
5259 // Fade the pointer when the current gesture manipulates a different
5260 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005261 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5263 } else {
5264 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5265 }
5266 break;
5267 }
5268
5269 // Send events!
5270 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005271 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
5273 // Update last coordinates of pointers that have moved so that we observe the new
5274 // pointer positions at the same time as other pointers that have just gone up.
5275 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5276 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5277 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5278 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5279 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5280 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5281 bool moveNeeded = false;
5282 if (down && !cancelPreviousGesture && !finishPreviousGesture
5283 && !mPointerGesture.lastGestureIdBits.isEmpty()
5284 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5285 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5286 & mPointerGesture.lastGestureIdBits.value);
5287 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5288 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5289 mPointerGesture.lastGestureProperties,
5290 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5291 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005292 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 moveNeeded = true;
5294 }
5295 }
5296
5297 // Send motion events for all pointers that went up or were canceled.
5298 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5299 if (!dispatchedGestureIdBits.isEmpty()) {
5300 if (cancelPreviousGesture) {
5301 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005302 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 AMOTION_EVENT_EDGE_FLAG_NONE,
5304 mPointerGesture.lastGestureProperties,
5305 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005306 dispatchedGestureIdBits, -1, 0,
5307 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308
5309 dispatchedGestureIdBits.clear();
5310 } else {
5311 BitSet32 upGestureIdBits;
5312 if (finishPreviousGesture) {
5313 upGestureIdBits = dispatchedGestureIdBits;
5314 } else {
5315 upGestureIdBits.value = dispatchedGestureIdBits.value
5316 & ~mPointerGesture.currentGestureIdBits.value;
5317 }
5318 while (!upGestureIdBits.isEmpty()) {
5319 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5320
5321 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005322 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5324 mPointerGesture.lastGestureProperties,
5325 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5326 dispatchedGestureIdBits, id,
5327 0, 0, mPointerGesture.downTime);
5328
5329 dispatchedGestureIdBits.clearBit(id);
5330 }
5331 }
5332 }
5333
5334 // Send motion events for all pointers that moved.
5335 if (moveNeeded) {
5336 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005337 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5338 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 mPointerGesture.currentGestureProperties,
5340 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5341 dispatchedGestureIdBits, -1,
5342 0, 0, mPointerGesture.downTime);
5343 }
5344
5345 // Send motion events for all pointers that went down.
5346 if (down) {
5347 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5348 & ~dispatchedGestureIdBits.value);
5349 while (!downGestureIdBits.isEmpty()) {
5350 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5351 dispatchedGestureIdBits.markBit(id);
5352
5353 if (dispatchedGestureIdBits.count() == 1) {
5354 mPointerGesture.downTime = when;
5355 }
5356
5357 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005358 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 mPointerGesture.currentGestureProperties,
5360 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5361 dispatchedGestureIdBits, id,
5362 0, 0, mPointerGesture.downTime);
5363 }
5364 }
5365
5366 // Send motion events for hover.
5367 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5368 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005369 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5371 mPointerGesture.currentGestureProperties,
5372 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5373 mPointerGesture.currentGestureIdBits, -1,
5374 0, 0, mPointerGesture.downTime);
5375 } else if (dispatchedGestureIdBits.isEmpty()
5376 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5377 // Synthesize a hover move event after all pointers go up to indicate that
5378 // the pointer is hovering again even if the user is not currently touching
5379 // the touch pad. This ensures that a view will receive a fresh hover enter
5380 // event after a tap.
5381 float x, y;
5382 mPointerController->getPosition(&x, &y);
5383
5384 PointerProperties pointerProperties;
5385 pointerProperties.clear();
5386 pointerProperties.id = 0;
5387 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5388
5389 PointerCoords pointerCoords;
5390 pointerCoords.clear();
5391 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5392 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5393
5394 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005395 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5397 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5398 0, 0, mPointerGesture.downTime);
5399 getListener()->notifyMotion(&args);
5400 }
5401
5402 // Update state.
5403 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5404 if (!down) {
5405 mPointerGesture.lastGestureIdBits.clear();
5406 } else {
5407 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5408 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5409 uint32_t id = idBits.clearFirstMarkedBit();
5410 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5411 mPointerGesture.lastGestureProperties[index].copyFrom(
5412 mPointerGesture.currentGestureProperties[index]);
5413 mPointerGesture.lastGestureCoords[index].copyFrom(
5414 mPointerGesture.currentGestureCoords[index]);
5415 mPointerGesture.lastGestureIdToIndex[id] = index;
5416 }
5417 }
5418}
5419
5420void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5421 // Cancel previously dispatches pointers.
5422 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5423 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005424 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005426 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 AMOTION_EVENT_EDGE_FLAG_NONE,
5428 mPointerGesture.lastGestureProperties,
5429 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5430 mPointerGesture.lastGestureIdBits, -1,
5431 0, 0, mPointerGesture.downTime);
5432 }
5433
5434 // Reset the current pointer gesture.
5435 mPointerGesture.reset();
5436 mPointerVelocityControl.reset();
5437
5438 // Remove any current spots.
5439 if (mPointerController != NULL) {
5440 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5441 mPointerController->clearSpots();
5442 }
5443}
5444
5445bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5446 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5447 *outCancelPreviousGesture = false;
5448 *outFinishPreviousGesture = false;
5449
5450 // Handle TAP timeout.
5451 if (isTimeout) {
5452#if DEBUG_GESTURES
5453 ALOGD("Gestures: Processing timeout");
5454#endif
5455
5456 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5457 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5458 // The tap/drag timeout has not yet expired.
5459 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5460 + mConfig.pointerGestureTapDragInterval);
5461 } else {
5462 // The tap is finished.
5463#if DEBUG_GESTURES
5464 ALOGD("Gestures: TAP finished");
5465#endif
5466 *outFinishPreviousGesture = true;
5467
5468 mPointerGesture.activeGestureId = -1;
5469 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5470 mPointerGesture.currentGestureIdBits.clear();
5471
5472 mPointerVelocityControl.reset();
5473 return true;
5474 }
5475 }
5476
5477 // We did not handle this timeout.
5478 return false;
5479 }
5480
Michael Wright842500e2015-03-13 17:32:02 -07005481 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5482 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483
5484 // Update the velocity tracker.
5485 {
5486 VelocityTracker::Position positions[MAX_POINTERS];
5487 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005488 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005490 const RawPointerData::Pointer& pointer =
5491 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492 positions[count].x = pointer.x * mPointerXMovementScale;
5493 positions[count].y = pointer.y * mPointerYMovementScale;
5494 }
5495 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005496 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 }
5498
5499 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5500 // to NEUTRAL, then we should not generate tap event.
5501 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5502 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5503 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5504 mPointerGesture.resetTap();
5505 }
5506
5507 // Pick a new active touch id if needed.
5508 // Choose an arbitrary pointer that just went down, if there is one.
5509 // Otherwise choose an arbitrary remaining pointer.
5510 // This guarantees we always have an active touch id when there is at least one pointer.
5511 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 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 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005517 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 mPointerGesture.firstTouchTime = when;
5519 }
Michael Wright842500e2015-03-13 17:32:02 -07005520 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005521 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005523 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 } else {
5525 activeTouchId = mPointerGesture.activeTouchId = -1;
5526 }
5527 }
5528
5529 // Determine whether we are in quiet time.
5530 bool isQuietTime = false;
5531 if (activeTouchId < 0) {
5532 mPointerGesture.resetQuietTime();
5533 } else {
5534 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5535 if (!isQuietTime) {
5536 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5537 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5538 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5539 && currentFingerCount < 2) {
5540 // Enter quiet time when exiting swipe or freeform state.
5541 // This is to prevent accidentally entering the hover state and flinging the
5542 // pointer when finishing a swipe and there is still one pointer left onscreen.
5543 isQuietTime = true;
5544 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5545 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005546 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 // Enter quiet time when releasing the button and there are still two or more
5548 // fingers down. This may indicate that one finger was used to press the button
5549 // but it has not gone up yet.
5550 isQuietTime = true;
5551 }
5552 if (isQuietTime) {
5553 mPointerGesture.quietTime = when;
5554 }
5555 }
5556 }
5557
5558 // Switch states based on button and pointer state.
5559 if (isQuietTime) {
5560 // Case 1: Quiet time. (QUIET)
5561#if DEBUG_GESTURES
5562 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5563 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5564#endif
5565 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5566 *outFinishPreviousGesture = true;
5567 }
5568
5569 mPointerGesture.activeGestureId = -1;
5570 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5571 mPointerGesture.currentGestureIdBits.clear();
5572
5573 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005574 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5576 // The pointer follows the active touch point.
5577 // Emit DOWN, MOVE, UP events at the pointer location.
5578 //
5579 // Only the active touch matters; other fingers are ignored. This policy helps
5580 // to handle the case where the user places a second finger on the touch pad
5581 // to apply the necessary force to depress an integrated button below the surface.
5582 // We don't want the second finger to be delivered to applications.
5583 //
5584 // For this to work well, we need to make sure to track the pointer that is really
5585 // active. If the user first puts one finger down to click then adds another
5586 // finger to drag then the active pointer should switch to the finger that is
5587 // being dragged.
5588#if DEBUG_GESTURES
5589 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5590 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5591#endif
5592 // Reset state when just starting.
5593 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5594 *outFinishPreviousGesture = true;
5595 mPointerGesture.activeGestureId = 0;
5596 }
5597
5598 // Switch pointers if needed.
5599 // Find the fastest pointer and follow it.
5600 if (activeTouchId >= 0 && currentFingerCount > 1) {
5601 int32_t bestId = -1;
5602 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005603 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604 uint32_t id = idBits.clearFirstMarkedBit();
5605 float vx, vy;
5606 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5607 float speed = hypotf(vx, vy);
5608 if (speed > bestSpeed) {
5609 bestId = id;
5610 bestSpeed = speed;
5611 }
5612 }
5613 }
5614 if (bestId >= 0 && bestId != activeTouchId) {
5615 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616#if DEBUG_GESTURES
5617 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5618 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5619#endif
5620 }
5621 }
5622
Jun Mukaifa1706a2015-12-03 01:14:46 -08005623 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005624 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005626 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005628 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005629 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5630 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631
5632 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5633 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5634
5635 // Move the pointer using a relative motion.
5636 // When using spots, the click will occur at the position of the anchor
5637 // spot and all other spots will move there.
5638 mPointerController->move(deltaX, deltaY);
5639 } else {
5640 mPointerVelocityControl.reset();
5641 }
5642
5643 float x, y;
5644 mPointerController->getPosition(&x, &y);
5645
5646 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5647 mPointerGesture.currentGestureIdBits.clear();
5648 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5649 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5650 mPointerGesture.currentGestureProperties[0].clear();
5651 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5652 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5653 mPointerGesture.currentGestureCoords[0].clear();
5654 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5655 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5656 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5657 } else if (currentFingerCount == 0) {
5658 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5659 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5660 *outFinishPreviousGesture = true;
5661 }
5662
5663 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5664 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5665 bool tapped = false;
5666 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5667 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5668 && lastFingerCount == 1) {
5669 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5670 float x, y;
5671 mPointerController->getPosition(&x, &y);
5672 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5673 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5674#if DEBUG_GESTURES
5675 ALOGD("Gestures: TAP");
5676#endif
5677
5678 mPointerGesture.tapUpTime = when;
5679 getContext()->requestTimeoutAtTime(when
5680 + mConfig.pointerGestureTapDragInterval);
5681
5682 mPointerGesture.activeGestureId = 0;
5683 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5684 mPointerGesture.currentGestureIdBits.clear();
5685 mPointerGesture.currentGestureIdBits.markBit(
5686 mPointerGesture.activeGestureId);
5687 mPointerGesture.currentGestureIdToIndex[
5688 mPointerGesture.activeGestureId] = 0;
5689 mPointerGesture.currentGestureProperties[0].clear();
5690 mPointerGesture.currentGestureProperties[0].id =
5691 mPointerGesture.activeGestureId;
5692 mPointerGesture.currentGestureProperties[0].toolType =
5693 AMOTION_EVENT_TOOL_TYPE_FINGER;
5694 mPointerGesture.currentGestureCoords[0].clear();
5695 mPointerGesture.currentGestureCoords[0].setAxisValue(
5696 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5697 mPointerGesture.currentGestureCoords[0].setAxisValue(
5698 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5699 mPointerGesture.currentGestureCoords[0].setAxisValue(
5700 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5701
5702 tapped = true;
5703 } else {
5704#if DEBUG_GESTURES
5705 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5706 x - mPointerGesture.tapX,
5707 y - mPointerGesture.tapY);
5708#endif
5709 }
5710 } else {
5711#if DEBUG_GESTURES
5712 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5713 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5714 (when - mPointerGesture.tapDownTime) * 0.000001f);
5715 } else {
5716 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5717 }
5718#endif
5719 }
5720 }
5721
5722 mPointerVelocityControl.reset();
5723
5724 if (!tapped) {
5725#if DEBUG_GESTURES
5726 ALOGD("Gestures: NEUTRAL");
5727#endif
5728 mPointerGesture.activeGestureId = -1;
5729 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5730 mPointerGesture.currentGestureIdBits.clear();
5731 }
5732 } else if (currentFingerCount == 1) {
5733 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5734 // The pointer follows the active touch point.
5735 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5736 // When in TAP_DRAG, emit MOVE events at the pointer location.
5737 ALOG_ASSERT(activeTouchId >= 0);
5738
5739 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5740 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5741 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5742 float x, y;
5743 mPointerController->getPosition(&x, &y);
5744 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5745 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5746 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5747 } else {
5748#if DEBUG_GESTURES
5749 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5750 x - mPointerGesture.tapX,
5751 y - mPointerGesture.tapY);
5752#endif
5753 }
5754 } else {
5755#if DEBUG_GESTURES
5756 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5757 (when - mPointerGesture.tapUpTime) * 0.000001f);
5758#endif
5759 }
5760 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5761 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5762 }
5763
Jun Mukaifa1706a2015-12-03 01:14:46 -08005764 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005765 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005767 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005769 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005770 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5771 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772
5773 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5774 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5775
5776 // Move the pointer using a relative motion.
5777 // When using spots, the hover or drag will occur at the position of the anchor spot.
5778 mPointerController->move(deltaX, deltaY);
5779 } else {
5780 mPointerVelocityControl.reset();
5781 }
5782
5783 bool down;
5784 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5785#if DEBUG_GESTURES
5786 ALOGD("Gestures: TAP_DRAG");
5787#endif
5788 down = true;
5789 } else {
5790#if DEBUG_GESTURES
5791 ALOGD("Gestures: HOVER");
5792#endif
5793 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5794 *outFinishPreviousGesture = true;
5795 }
5796 mPointerGesture.activeGestureId = 0;
5797 down = false;
5798 }
5799
5800 float x, y;
5801 mPointerController->getPosition(&x, &y);
5802
5803 mPointerGesture.currentGestureIdBits.clear();
5804 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5805 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5806 mPointerGesture.currentGestureProperties[0].clear();
5807 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5808 mPointerGesture.currentGestureProperties[0].toolType =
5809 AMOTION_EVENT_TOOL_TYPE_FINGER;
5810 mPointerGesture.currentGestureCoords[0].clear();
5811 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5812 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5813 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5814 down ? 1.0f : 0.0f);
5815
5816 if (lastFingerCount == 0 && currentFingerCount != 0) {
5817 mPointerGesture.resetTap();
5818 mPointerGesture.tapDownTime = when;
5819 mPointerGesture.tapX = x;
5820 mPointerGesture.tapY = y;
5821 }
5822 } else {
5823 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5824 // We need to provide feedback for each finger that goes down so we cannot wait
5825 // for the fingers to move before deciding what to do.
5826 //
5827 // The ambiguous case is deciding what to do when there are two fingers down but they
5828 // have not moved enough to determine whether they are part of a drag or part of a
5829 // freeform gesture, or just a press or long-press at the pointer location.
5830 //
5831 // When there are two fingers we start with the PRESS hypothesis and we generate a
5832 // down at the pointer location.
5833 //
5834 // When the two fingers move enough or when additional fingers are added, we make
5835 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5836 ALOG_ASSERT(activeTouchId >= 0);
5837
5838 bool settled = when >= mPointerGesture.firstTouchTime
5839 + mConfig.pointerGestureMultitouchSettleInterval;
5840 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5841 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5842 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5843 *outFinishPreviousGesture = true;
5844 } else if (!settled && currentFingerCount > lastFingerCount) {
5845 // Additional pointers have gone down but not yet settled.
5846 // Reset the gesture.
5847#if DEBUG_GESTURES
5848 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5849 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5850 + mConfig.pointerGestureMultitouchSettleInterval - when)
5851 * 0.000001f);
5852#endif
5853 *outCancelPreviousGesture = true;
5854 } else {
5855 // Continue previous gesture.
5856 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5857 }
5858
5859 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5860 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5861 mPointerGesture.activeGestureId = 0;
5862 mPointerGesture.referenceIdBits.clear();
5863 mPointerVelocityControl.reset();
5864
5865 // Use the centroid and pointer location as the reference points for the gesture.
5866#if DEBUG_GESTURES
5867 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5868 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5869 + mConfig.pointerGestureMultitouchSettleInterval - when)
5870 * 0.000001f);
5871#endif
Michael Wright842500e2015-03-13 17:32:02 -07005872 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873 &mPointerGesture.referenceTouchX,
5874 &mPointerGesture.referenceTouchY);
5875 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5876 &mPointerGesture.referenceGestureY);
5877 }
5878
5879 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005880 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5882 uint32_t id = idBits.clearFirstMarkedBit();
5883 mPointerGesture.referenceDeltas[id].dx = 0;
5884 mPointerGesture.referenceDeltas[id].dy = 0;
5885 }
Michael Wright842500e2015-03-13 17:32:02 -07005886 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887
5888 // Add delta for all fingers and calculate a common movement delta.
5889 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005890 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5891 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5893 bool first = (idBits == commonIdBits);
5894 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005895 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5896 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5898 delta.dx += cpd.x - lpd.x;
5899 delta.dy += cpd.y - lpd.y;
5900
5901 if (first) {
5902 commonDeltaX = delta.dx;
5903 commonDeltaY = delta.dy;
5904 } else {
5905 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5906 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5907 }
5908 }
5909
5910 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5911 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5912 float dist[MAX_POINTER_ID + 1];
5913 int32_t distOverThreshold = 0;
5914 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5915 uint32_t id = idBits.clearFirstMarkedBit();
5916 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5917 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5918 delta.dy * mPointerYZoomScale);
5919 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5920 distOverThreshold += 1;
5921 }
5922 }
5923
5924 // Only transition when at least two pointers have moved further than
5925 // the minimum distance threshold.
5926 if (distOverThreshold >= 2) {
5927 if (currentFingerCount > 2) {
5928 // There are more than two pointers, switch to FREEFORM.
5929#if DEBUG_GESTURES
5930 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5931 currentFingerCount);
5932#endif
5933 *outCancelPreviousGesture = true;
5934 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5935 } else {
5936 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005937 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 uint32_t id1 = idBits.clearFirstMarkedBit();
5939 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005940 const RawPointerData::Pointer& p1 =
5941 mCurrentRawState.rawPointerData.pointerForId(id1);
5942 const RawPointerData::Pointer& p2 =
5943 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5945 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5946 // There are two pointers but they are too far apart for a SWIPE,
5947 // switch to FREEFORM.
5948#if DEBUG_GESTURES
5949 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5950 mutualDistance, mPointerGestureMaxSwipeWidth);
5951#endif
5952 *outCancelPreviousGesture = true;
5953 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5954 } else {
5955 // There are two pointers. Wait for both pointers to start moving
5956 // before deciding whether this is a SWIPE or FREEFORM gesture.
5957 float dist1 = dist[id1];
5958 float dist2 = dist[id2];
5959 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5960 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5961 // Calculate the dot product of the displacement vectors.
5962 // When the vectors are oriented in approximately the same direction,
5963 // the angle betweeen them is near zero and the cosine of the angle
5964 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5965 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5966 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5967 float dx1 = delta1.dx * mPointerXZoomScale;
5968 float dy1 = delta1.dy * mPointerYZoomScale;
5969 float dx2 = delta2.dx * mPointerXZoomScale;
5970 float dy2 = delta2.dy * mPointerYZoomScale;
5971 float dot = dx1 * dx2 + dy1 * dy2;
5972 float cosine = dot / (dist1 * dist2); // denominator always > 0
5973 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5974 // Pointers are moving in the same direction. Switch to SWIPE.
5975#if DEBUG_GESTURES
5976 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5977 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5978 "cosine %0.3f >= %0.3f",
5979 dist1, mConfig.pointerGestureMultitouchMinDistance,
5980 dist2, mConfig.pointerGestureMultitouchMinDistance,
5981 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5982#endif
5983 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5984 } else {
5985 // Pointers are moving in different directions. Switch to FREEFORM.
5986#if DEBUG_GESTURES
5987 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5988 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5989 "cosine %0.3f < %0.3f",
5990 dist1, mConfig.pointerGestureMultitouchMinDistance,
5991 dist2, mConfig.pointerGestureMultitouchMinDistance,
5992 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5993#endif
5994 *outCancelPreviousGesture = true;
5995 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5996 }
5997 }
5998 }
5999 }
6000 }
6001 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6002 // Switch from SWIPE to FREEFORM if additional pointers go down.
6003 // Cancel previous gesture.
6004 if (currentFingerCount > 2) {
6005#if DEBUG_GESTURES
6006 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6007 currentFingerCount);
6008#endif
6009 *outCancelPreviousGesture = true;
6010 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6011 }
6012 }
6013
6014 // Move the reference points based on the overall group motion of the fingers
6015 // except in PRESS mode while waiting for a transition to occur.
6016 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6017 && (commonDeltaX || commonDeltaY)) {
6018 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6019 uint32_t id = idBits.clearFirstMarkedBit();
6020 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6021 delta.dx = 0;
6022 delta.dy = 0;
6023 }
6024
6025 mPointerGesture.referenceTouchX += commonDeltaX;
6026 mPointerGesture.referenceTouchY += commonDeltaY;
6027
6028 commonDeltaX *= mPointerXMovementScale;
6029 commonDeltaY *= mPointerYMovementScale;
6030
6031 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6032 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6033
6034 mPointerGesture.referenceGestureX += commonDeltaX;
6035 mPointerGesture.referenceGestureY += commonDeltaY;
6036 }
6037
6038 // Report gestures.
6039 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6040 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6041 // PRESS or SWIPE mode.
6042#if DEBUG_GESTURES
6043 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6044 "activeGestureId=%d, currentTouchPointerCount=%d",
6045 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6046#endif
6047 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6048
6049 mPointerGesture.currentGestureIdBits.clear();
6050 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6051 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6052 mPointerGesture.currentGestureProperties[0].clear();
6053 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6054 mPointerGesture.currentGestureProperties[0].toolType =
6055 AMOTION_EVENT_TOOL_TYPE_FINGER;
6056 mPointerGesture.currentGestureCoords[0].clear();
6057 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6058 mPointerGesture.referenceGestureX);
6059 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6060 mPointerGesture.referenceGestureY);
6061 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6062 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6063 // FREEFORM mode.
6064#if DEBUG_GESTURES
6065 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6066 "activeGestureId=%d, currentTouchPointerCount=%d",
6067 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6068#endif
6069 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6070
6071 mPointerGesture.currentGestureIdBits.clear();
6072
6073 BitSet32 mappedTouchIdBits;
6074 BitSet32 usedGestureIdBits;
6075 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6076 // Initially, assign the active gesture id to the active touch point
6077 // if there is one. No other touch id bits are mapped yet.
6078 if (!*outCancelPreviousGesture) {
6079 mappedTouchIdBits.markBit(activeTouchId);
6080 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6081 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6082 mPointerGesture.activeGestureId;
6083 } else {
6084 mPointerGesture.activeGestureId = -1;
6085 }
6086 } else {
6087 // Otherwise, assume we mapped all touches from the previous frame.
6088 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006089 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6090 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6092
6093 // Check whether we need to choose a new active gesture id because the
6094 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006095 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6096 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097 !upTouchIdBits.isEmpty(); ) {
6098 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6099 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6100 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6101 mPointerGesture.activeGestureId = -1;
6102 break;
6103 }
6104 }
6105 }
6106
6107#if DEBUG_GESTURES
6108 ALOGD("Gestures: FREEFORM follow up "
6109 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6110 "activeGestureId=%d",
6111 mappedTouchIdBits.value, usedGestureIdBits.value,
6112 mPointerGesture.activeGestureId);
6113#endif
6114
Michael Wright842500e2015-03-13 17:32:02 -07006115 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006116 for (uint32_t i = 0; i < currentFingerCount; i++) {
6117 uint32_t touchId = idBits.clearFirstMarkedBit();
6118 uint32_t gestureId;
6119 if (!mappedTouchIdBits.hasBit(touchId)) {
6120 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6121 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6122#if DEBUG_GESTURES
6123 ALOGD("Gestures: FREEFORM "
6124 "new mapping for touch id %d -> gesture id %d",
6125 touchId, gestureId);
6126#endif
6127 } else {
6128 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6129#if DEBUG_GESTURES
6130 ALOGD("Gestures: FREEFORM "
6131 "existing mapping for touch id %d -> gesture id %d",
6132 touchId, gestureId);
6133#endif
6134 }
6135 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6136 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6137
6138 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006139 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6141 * mPointerXZoomScale;
6142 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6143 * mPointerYZoomScale;
6144 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6145
6146 mPointerGesture.currentGestureProperties[i].clear();
6147 mPointerGesture.currentGestureProperties[i].id = gestureId;
6148 mPointerGesture.currentGestureProperties[i].toolType =
6149 AMOTION_EVENT_TOOL_TYPE_FINGER;
6150 mPointerGesture.currentGestureCoords[i].clear();
6151 mPointerGesture.currentGestureCoords[i].setAxisValue(
6152 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6153 mPointerGesture.currentGestureCoords[i].setAxisValue(
6154 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6155 mPointerGesture.currentGestureCoords[i].setAxisValue(
6156 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6157 }
6158
6159 if (mPointerGesture.activeGestureId < 0) {
6160 mPointerGesture.activeGestureId =
6161 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6162#if DEBUG_GESTURES
6163 ALOGD("Gestures: FREEFORM new "
6164 "activeGestureId=%d", mPointerGesture.activeGestureId);
6165#endif
6166 }
6167 }
6168 }
6169
Michael Wright842500e2015-03-13 17:32:02 -07006170 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171
6172#if DEBUG_GESTURES
6173 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6174 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6175 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6176 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6177 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6178 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6179 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6180 uint32_t id = idBits.clearFirstMarkedBit();
6181 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6182 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6183 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6184 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6185 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6186 id, index, properties.toolType,
6187 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6188 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6189 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6190 }
6191 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6192 uint32_t id = idBits.clearFirstMarkedBit();
6193 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6194 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6195 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6196 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6197 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6198 id, index, properties.toolType,
6199 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6200 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6201 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6202 }
6203#endif
6204 return true;
6205}
6206
6207void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6208 mPointerSimple.currentCoords.clear();
6209 mPointerSimple.currentProperties.clear();
6210
6211 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006212 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6213 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6214 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6215 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6216 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006217 mPointerController->setPosition(x, y);
6218
Michael Wright842500e2015-03-13 17:32:02 -07006219 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 down = !hovering;
6221
6222 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006223 mPointerSimple.currentCoords.copyFrom(
6224 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6226 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6227 mPointerSimple.currentProperties.id = 0;
6228 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006229 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 } else {
6231 down = false;
6232 hovering = false;
6233 }
6234
6235 dispatchPointerSimple(when, policyFlags, down, hovering);
6236}
6237
6238void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6239 abortPointerSimple(when, policyFlags);
6240}
6241
6242void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6243 mPointerSimple.currentCoords.clear();
6244 mPointerSimple.currentProperties.clear();
6245
6246 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006247 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6248 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6249 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006250 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006251 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6252 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006253 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006254 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006256 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006257 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258 * mPointerYMovementScale;
6259
6260 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6261 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6262
6263 mPointerController->move(deltaX, deltaY);
6264 } else {
6265 mPointerVelocityControl.reset();
6266 }
6267
Michael Wright842500e2015-03-13 17:32:02 -07006268 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269 hovering = !down;
6270
6271 float x, y;
6272 mPointerController->getPosition(&x, &y);
6273 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006274 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006275 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6276 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6277 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6278 hovering ? 0.0f : 1.0f);
6279 mPointerSimple.currentProperties.id = 0;
6280 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006281 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 } else {
6283 mPointerVelocityControl.reset();
6284
6285 down = false;
6286 hovering = false;
6287 }
6288
6289 dispatchPointerSimple(when, policyFlags, down, hovering);
6290}
6291
6292void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6293 abortPointerSimple(when, policyFlags);
6294
6295 mPointerVelocityControl.reset();
6296}
6297
6298void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6299 bool down, bool hovering) {
6300 int32_t metaState = getContext()->getGlobalMetaState();
6301
6302 if (mPointerController != NULL) {
6303 if (down || hovering) {
6304 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6305 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006306 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006307 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6308 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6309 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6310 }
6311 }
6312
6313 if (mPointerSimple.down && !down) {
6314 mPointerSimple.down = false;
6315
6316 // Send up.
6317 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006318 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 mViewport.displayId,
6320 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6321 mOrientedXPrecision, mOrientedYPrecision,
6322 mPointerSimple.downTime);
6323 getListener()->notifyMotion(&args);
6324 }
6325
6326 if (mPointerSimple.hovering && !hovering) {
6327 mPointerSimple.hovering = false;
6328
6329 // Send hover exit.
6330 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006331 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 mViewport.displayId,
6333 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6334 mOrientedXPrecision, mOrientedYPrecision,
6335 mPointerSimple.downTime);
6336 getListener()->notifyMotion(&args);
6337 }
6338
6339 if (down) {
6340 if (!mPointerSimple.down) {
6341 mPointerSimple.down = true;
6342 mPointerSimple.downTime = when;
6343
6344 // Send down.
6345 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006346 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006347 mViewport.displayId,
6348 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6349 mOrientedXPrecision, mOrientedYPrecision,
6350 mPointerSimple.downTime);
6351 getListener()->notifyMotion(&args);
6352 }
6353
6354 // Send move.
6355 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006356 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006357 mViewport.displayId,
6358 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6359 mOrientedXPrecision, mOrientedYPrecision,
6360 mPointerSimple.downTime);
6361 getListener()->notifyMotion(&args);
6362 }
6363
6364 if (hovering) {
6365 if (!mPointerSimple.hovering) {
6366 mPointerSimple.hovering = true;
6367
6368 // Send hover enter.
6369 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006370 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006371 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 mViewport.displayId,
6373 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6374 mOrientedXPrecision, mOrientedYPrecision,
6375 mPointerSimple.downTime);
6376 getListener()->notifyMotion(&args);
6377 }
6378
6379 // Send hover move.
6380 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006381 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006382 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383 mViewport.displayId,
6384 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6385 mOrientedXPrecision, mOrientedYPrecision,
6386 mPointerSimple.downTime);
6387 getListener()->notifyMotion(&args);
6388 }
6389
Michael Wright842500e2015-03-13 17:32:02 -07006390 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6391 float vscroll = mCurrentRawState.rawVScroll;
6392 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393 mWheelYVelocityControl.move(when, NULL, &vscroll);
6394 mWheelXVelocityControl.move(when, &hscroll, NULL);
6395
6396 // Send scroll.
6397 PointerCoords pointerCoords;
6398 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6399 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6400 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6401
6402 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006403 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404 mViewport.displayId,
6405 1, &mPointerSimple.currentProperties, &pointerCoords,
6406 mOrientedXPrecision, mOrientedYPrecision,
6407 mPointerSimple.downTime);
6408 getListener()->notifyMotion(&args);
6409 }
6410
6411 // Save state.
6412 if (down || hovering) {
6413 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6414 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6415 } else {
6416 mPointerSimple.reset();
6417 }
6418}
6419
6420void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6421 mPointerSimple.currentCoords.clear();
6422 mPointerSimple.currentProperties.clear();
6423
6424 dispatchPointerSimple(when, policyFlags, false, false);
6425}
6426
6427void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006428 int32_t action, int32_t actionButton, int32_t flags,
6429 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006431 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6432 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433 PointerCoords pointerCoords[MAX_POINTERS];
6434 PointerProperties pointerProperties[MAX_POINTERS];
6435 uint32_t pointerCount = 0;
6436 while (!idBits.isEmpty()) {
6437 uint32_t id = idBits.clearFirstMarkedBit();
6438 uint32_t index = idToIndex[id];
6439 pointerProperties[pointerCount].copyFrom(properties[index]);
6440 pointerCoords[pointerCount].copyFrom(coords[index]);
6441
6442 if (changedId >= 0 && id == uint32_t(changedId)) {
6443 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6444 }
6445
6446 pointerCount += 1;
6447 }
6448
6449 ALOG_ASSERT(pointerCount != 0);
6450
6451 if (changedId >= 0 && pointerCount == 1) {
6452 // Replace initial down and final up action.
6453 // We can compare the action without masking off the changed pointer index
6454 // because we know the index is 0.
6455 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6456 action = AMOTION_EVENT_ACTION_DOWN;
6457 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6458 action = AMOTION_EVENT_ACTION_UP;
6459 } else {
6460 // Can't happen.
6461 ALOG_ASSERT(false);
6462 }
6463 }
6464
6465 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006466 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006467 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6468 xPrecision, yPrecision, downTime);
6469 getListener()->notifyMotion(&args);
6470}
6471
6472bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6473 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6474 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6475 BitSet32 idBits) const {
6476 bool changed = false;
6477 while (!idBits.isEmpty()) {
6478 uint32_t id = idBits.clearFirstMarkedBit();
6479 uint32_t inIndex = inIdToIndex[id];
6480 uint32_t outIndex = outIdToIndex[id];
6481
6482 const PointerProperties& curInProperties = inProperties[inIndex];
6483 const PointerCoords& curInCoords = inCoords[inIndex];
6484 PointerProperties& curOutProperties = outProperties[outIndex];
6485 PointerCoords& curOutCoords = outCoords[outIndex];
6486
6487 if (curInProperties != curOutProperties) {
6488 curOutProperties.copyFrom(curInProperties);
6489 changed = true;
6490 }
6491
6492 if (curInCoords != curOutCoords) {
6493 curOutCoords.copyFrom(curInCoords);
6494 changed = true;
6495 }
6496 }
6497 return changed;
6498}
6499
6500void TouchInputMapper::fadePointer() {
6501 if (mPointerController != NULL) {
6502 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6503 }
6504}
6505
Jeff Brownc9aa6282015-02-11 19:03:28 -08006506void TouchInputMapper::cancelTouch(nsecs_t when) {
6507 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006508 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006509}
6510
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6512 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6513 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6514}
6515
6516const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6517 int32_t x, int32_t y) {
6518 size_t numVirtualKeys = mVirtualKeys.size();
6519 for (size_t i = 0; i < numVirtualKeys; i++) {
6520 const VirtualKey& virtualKey = mVirtualKeys[i];
6521
6522#if DEBUG_VIRTUAL_KEYS
6523 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6524 "left=%d, top=%d, right=%d, bottom=%d",
6525 x, y,
6526 virtualKey.keyCode, virtualKey.scanCode,
6527 virtualKey.hitLeft, virtualKey.hitTop,
6528 virtualKey.hitRight, virtualKey.hitBottom);
6529#endif
6530
6531 if (virtualKey.isHit(x, y)) {
6532 return & virtualKey;
6533 }
6534 }
6535
6536 return NULL;
6537}
6538
Michael Wright842500e2015-03-13 17:32:02 -07006539void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6540 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6541 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542
Michael Wright842500e2015-03-13 17:32:02 -07006543 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544
6545 if (currentPointerCount == 0) {
6546 // No pointers to assign.
6547 return;
6548 }
6549
6550 if (lastPointerCount == 0) {
6551 // All pointers are new.
6552 for (uint32_t i = 0; i < currentPointerCount; i++) {
6553 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006554 current->rawPointerData.pointers[i].id = id;
6555 current->rawPointerData.idToIndex[id] = i;
6556 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 }
6558 return;
6559 }
6560
6561 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006562 && current->rawPointerData.pointers[0].toolType
6563 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006565 uint32_t id = last->rawPointerData.pointers[0].id;
6566 current->rawPointerData.pointers[0].id = id;
6567 current->rawPointerData.idToIndex[id] = 0;
6568 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 return;
6570 }
6571
6572 // General case.
6573 // We build a heap of squared euclidean distances between current and last pointers
6574 // associated with the current and last pointer indices. Then, we find the best
6575 // match (by distance) for each current pointer.
6576 // The pointers must have the same tool type but it is possible for them to
6577 // transition from hovering to touching or vice-versa while retaining the same id.
6578 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6579
6580 uint32_t heapSize = 0;
6581 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6582 currentPointerIndex++) {
6583 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6584 lastPointerIndex++) {
6585 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006586 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006587 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006588 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589 if (currentPointer.toolType == lastPointer.toolType) {
6590 int64_t deltaX = currentPointer.x - lastPointer.x;
6591 int64_t deltaY = currentPointer.y - lastPointer.y;
6592
6593 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6594
6595 // Insert new element into the heap (sift up).
6596 heap[heapSize].currentPointerIndex = currentPointerIndex;
6597 heap[heapSize].lastPointerIndex = lastPointerIndex;
6598 heap[heapSize].distance = distance;
6599 heapSize += 1;
6600 }
6601 }
6602 }
6603
6604 // Heapify
6605 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6606 startIndex -= 1;
6607 for (uint32_t parentIndex = startIndex; ;) {
6608 uint32_t childIndex = parentIndex * 2 + 1;
6609 if (childIndex >= heapSize) {
6610 break;
6611 }
6612
6613 if (childIndex + 1 < heapSize
6614 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6615 childIndex += 1;
6616 }
6617
6618 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6619 break;
6620 }
6621
6622 swap(heap[parentIndex], heap[childIndex]);
6623 parentIndex = childIndex;
6624 }
6625 }
6626
6627#if DEBUG_POINTER_ASSIGNMENT
6628 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6629 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006630 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6632 heap[i].distance);
6633 }
6634#endif
6635
6636 // Pull matches out by increasing order of distance.
6637 // To avoid reassigning pointers that have already been matched, the loop keeps track
6638 // of which last and current pointers have been matched using the matchedXXXBits variables.
6639 // It also tracks the used pointer id bits.
6640 BitSet32 matchedLastBits(0);
6641 BitSet32 matchedCurrentBits(0);
6642 BitSet32 usedIdBits(0);
6643 bool first = true;
6644 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6645 while (heapSize > 0) {
6646 if (first) {
6647 // The first time through the loop, we just consume the root element of
6648 // the heap (the one with smallest distance).
6649 first = false;
6650 } else {
6651 // Previous iterations consumed the root element of the heap.
6652 // Pop root element off of the heap (sift down).
6653 heap[0] = heap[heapSize];
6654 for (uint32_t parentIndex = 0; ;) {
6655 uint32_t childIndex = parentIndex * 2 + 1;
6656 if (childIndex >= heapSize) {
6657 break;
6658 }
6659
6660 if (childIndex + 1 < heapSize
6661 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6662 childIndex += 1;
6663 }
6664
6665 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6666 break;
6667 }
6668
6669 swap(heap[parentIndex], heap[childIndex]);
6670 parentIndex = childIndex;
6671 }
6672
6673#if DEBUG_POINTER_ASSIGNMENT
6674 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6675 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006676 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006677 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6678 heap[i].distance);
6679 }
6680#endif
6681 }
6682
6683 heapSize -= 1;
6684
6685 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6686 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6687
6688 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6689 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6690
6691 matchedCurrentBits.markBit(currentPointerIndex);
6692 matchedLastBits.markBit(lastPointerIndex);
6693
Michael Wright842500e2015-03-13 17:32:02 -07006694 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6695 current->rawPointerData.pointers[currentPointerIndex].id = id;
6696 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6697 current->rawPointerData.markIdBit(id,
6698 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006699 usedIdBits.markBit(id);
6700
6701#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006702 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6703 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006704 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6705#endif
6706 break;
6707 }
6708 }
6709
6710 // Assign fresh ids to pointers that were not matched in the process.
6711 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6712 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6713 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6714
Michael Wright842500e2015-03-13 17:32:02 -07006715 current->rawPointerData.pointers[currentPointerIndex].id = id;
6716 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6717 current->rawPointerData.markIdBit(id,
6718 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006719
6720#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006721 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006722#endif
6723 }
6724}
6725
6726int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6727 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6728 return AKEY_STATE_VIRTUAL;
6729 }
6730
6731 size_t numVirtualKeys = mVirtualKeys.size();
6732 for (size_t i = 0; i < numVirtualKeys; i++) {
6733 const VirtualKey& virtualKey = mVirtualKeys[i];
6734 if (virtualKey.keyCode == keyCode) {
6735 return AKEY_STATE_UP;
6736 }
6737 }
6738
6739 return AKEY_STATE_UNKNOWN;
6740}
6741
6742int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6743 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6744 return AKEY_STATE_VIRTUAL;
6745 }
6746
6747 size_t numVirtualKeys = mVirtualKeys.size();
6748 for (size_t i = 0; i < numVirtualKeys; i++) {
6749 const VirtualKey& virtualKey = mVirtualKeys[i];
6750 if (virtualKey.scanCode == scanCode) {
6751 return AKEY_STATE_UP;
6752 }
6753 }
6754
6755 return AKEY_STATE_UNKNOWN;
6756}
6757
6758bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6759 const int32_t* keyCodes, uint8_t* outFlags) {
6760 size_t numVirtualKeys = mVirtualKeys.size();
6761 for (size_t i = 0; i < numVirtualKeys; i++) {
6762 const VirtualKey& virtualKey = mVirtualKeys[i];
6763
6764 for (size_t i = 0; i < numCodes; i++) {
6765 if (virtualKey.keyCode == keyCodes[i]) {
6766 outFlags[i] = 1;
6767 }
6768 }
6769 }
6770
6771 return true;
6772}
6773
6774
6775// --- SingleTouchInputMapper ---
6776
6777SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6778 TouchInputMapper(device) {
6779}
6780
6781SingleTouchInputMapper::~SingleTouchInputMapper() {
6782}
6783
6784void SingleTouchInputMapper::reset(nsecs_t when) {
6785 mSingleTouchMotionAccumulator.reset(getDevice());
6786
6787 TouchInputMapper::reset(when);
6788}
6789
6790void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6791 TouchInputMapper::process(rawEvent);
6792
6793 mSingleTouchMotionAccumulator.process(rawEvent);
6794}
6795
Michael Wright842500e2015-03-13 17:32:02 -07006796void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006797 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006798 outState->rawPointerData.pointerCount = 1;
6799 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006800
6801 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6802 && (mTouchButtonAccumulator.isHovering()
6803 || (mRawPointerAxes.pressure.valid
6804 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006805 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006806
Michael Wright842500e2015-03-13 17:32:02 -07006807 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006808 outPointer.id = 0;
6809 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6810 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6811 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6812 outPointer.touchMajor = 0;
6813 outPointer.touchMinor = 0;
6814 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6815 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6816 outPointer.orientation = 0;
6817 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6818 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6819 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6820 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6821 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6822 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6823 }
6824 outPointer.isHovering = isHovering;
6825 }
6826}
6827
6828void SingleTouchInputMapper::configureRawPointerAxes() {
6829 TouchInputMapper::configureRawPointerAxes();
6830
6831 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6832 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6833 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6834 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6835 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6836 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6837 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6838}
6839
6840bool SingleTouchInputMapper::hasStylus() const {
6841 return mTouchButtonAccumulator.hasStylus();
6842}
6843
6844
6845// --- MultiTouchInputMapper ---
6846
6847MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6848 TouchInputMapper(device) {
6849}
6850
6851MultiTouchInputMapper::~MultiTouchInputMapper() {
6852}
6853
6854void MultiTouchInputMapper::reset(nsecs_t when) {
6855 mMultiTouchMotionAccumulator.reset(getDevice());
6856
6857 mPointerIdBits.clear();
6858
6859 TouchInputMapper::reset(when);
6860}
6861
6862void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6863 TouchInputMapper::process(rawEvent);
6864
6865 mMultiTouchMotionAccumulator.process(rawEvent);
6866}
6867
Michael Wright842500e2015-03-13 17:32:02 -07006868void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006869 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6870 size_t outCount = 0;
6871 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006872 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006873
6874 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6875 const MultiTouchMotionAccumulator::Slot* inSlot =
6876 mMultiTouchMotionAccumulator.getSlot(inIndex);
6877 if (!inSlot->isInUse()) {
6878 continue;
6879 }
6880
6881 if (outCount >= MAX_POINTERS) {
6882#if DEBUG_POINTERS
6883 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6884 "ignoring the rest.",
6885 getDeviceName().string(), MAX_POINTERS);
6886#endif
6887 break; // too many fingers!
6888 }
6889
Michael Wright842500e2015-03-13 17:32:02 -07006890 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006891 outPointer.x = inSlot->getX();
6892 outPointer.y = inSlot->getY();
6893 outPointer.pressure = inSlot->getPressure();
6894 outPointer.touchMajor = inSlot->getTouchMajor();
6895 outPointer.touchMinor = inSlot->getTouchMinor();
6896 outPointer.toolMajor = inSlot->getToolMajor();
6897 outPointer.toolMinor = inSlot->getToolMinor();
6898 outPointer.orientation = inSlot->getOrientation();
6899 outPointer.distance = inSlot->getDistance();
6900 outPointer.tiltX = 0;
6901 outPointer.tiltY = 0;
6902
6903 outPointer.toolType = inSlot->getToolType();
6904 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6905 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6906 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6907 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6908 }
6909 }
6910
6911 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6912 && (mTouchButtonAccumulator.isHovering()
6913 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6914 outPointer.isHovering = isHovering;
6915
6916 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006917 if (mHavePointerIds) {
6918 int32_t trackingId = inSlot->getTrackingId();
6919 int32_t id = -1;
6920 if (trackingId >= 0) {
6921 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6922 uint32_t n = idBits.clearFirstMarkedBit();
6923 if (mPointerTrackingIdMap[n] == trackingId) {
6924 id = n;
6925 }
6926 }
6927
6928 if (id < 0 && !mPointerIdBits.isFull()) {
6929 id = mPointerIdBits.markFirstUnmarkedBit();
6930 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006931 }
Michael Wright842500e2015-03-13 17:32:02 -07006932 }
gaoshang1a632de2016-08-24 10:23:50 +08006933 if (id < 0) {
6934 mHavePointerIds = false;
6935 outState->rawPointerData.clearIdBits();
6936 newPointerIdBits.clear();
6937 } else {
6938 outPointer.id = id;
6939 outState->rawPointerData.idToIndex[id] = outCount;
6940 outState->rawPointerData.markIdBit(id, isHovering);
6941 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006942 }
Michael Wright842500e2015-03-13 17:32:02 -07006943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006944 outCount += 1;
6945 }
6946
Michael Wright842500e2015-03-13 17:32:02 -07006947 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006948 mPointerIdBits = newPointerIdBits;
6949
6950 mMultiTouchMotionAccumulator.finishSync();
6951}
6952
6953void MultiTouchInputMapper::configureRawPointerAxes() {
6954 TouchInputMapper::configureRawPointerAxes();
6955
6956 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6957 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6958 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6959 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6960 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6961 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6962 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6963 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6964 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6965 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6966 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6967
6968 if (mRawPointerAxes.trackingId.valid
6969 && mRawPointerAxes.slot.valid
6970 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6971 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6972 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006973 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6974 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006975 getDeviceName().string(), slotCount, MAX_SLOTS);
6976 slotCount = MAX_SLOTS;
6977 }
6978 mMultiTouchMotionAccumulator.configure(getDevice(),
6979 slotCount, true /*usingSlotsProtocol*/);
6980 } else {
6981 mMultiTouchMotionAccumulator.configure(getDevice(),
6982 MAX_POINTERS, false /*usingSlotsProtocol*/);
6983 }
6984}
6985
6986bool MultiTouchInputMapper::hasStylus() const {
6987 return mMultiTouchMotionAccumulator.hasStylus()
6988 || mTouchButtonAccumulator.hasStylus();
6989}
6990
Michael Wright842500e2015-03-13 17:32:02 -07006991// --- ExternalStylusInputMapper
6992
6993ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6994 InputMapper(device) {
6995
6996}
6997
6998uint32_t ExternalStylusInputMapper::getSources() {
6999 return AINPUT_SOURCE_STYLUS;
7000}
7001
7002void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7003 InputMapper::populateDeviceInfo(info);
7004 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7005 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7006}
7007
7008void ExternalStylusInputMapper::dump(String8& dump) {
7009 dump.append(INDENT2 "External Stylus Input Mapper:\n");
7010 dump.append(INDENT3 "Raw Stylus Axes:\n");
7011 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
7012 dump.append(INDENT3 "Stylus State:\n");
7013 dumpStylusState(dump, mStylusState);
7014}
7015
7016void ExternalStylusInputMapper::configure(nsecs_t when,
7017 const InputReaderConfiguration* config, uint32_t changes) {
7018 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7019 mTouchButtonAccumulator.configure(getDevice());
7020}
7021
7022void ExternalStylusInputMapper::reset(nsecs_t when) {
7023 InputDevice* device = getDevice();
7024 mSingleTouchMotionAccumulator.reset(device);
7025 mTouchButtonAccumulator.reset(device);
7026 InputMapper::reset(when);
7027}
7028
7029void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7030 mSingleTouchMotionAccumulator.process(rawEvent);
7031 mTouchButtonAccumulator.process(rawEvent);
7032
7033 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7034 sync(rawEvent->when);
7035 }
7036}
7037
7038void ExternalStylusInputMapper::sync(nsecs_t when) {
7039 mStylusState.clear();
7040
7041 mStylusState.when = when;
7042
Michael Wright45ccacf2015-04-21 19:01:58 +01007043 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7044 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7045 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7046 }
7047
Michael Wright842500e2015-03-13 17:32:02 -07007048 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7049 if (mRawPressureAxis.valid) {
7050 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7051 } else if (mTouchButtonAccumulator.isToolActive()) {
7052 mStylusState.pressure = 1.0f;
7053 } else {
7054 mStylusState.pressure = 0.0f;
7055 }
7056
7057 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007058
7059 mContext->dispatchExternalStylusState(mStylusState);
7060}
7061
Michael Wrightd02c5b62014-02-10 15:10:22 -08007062
7063// --- JoystickInputMapper ---
7064
7065JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7066 InputMapper(device) {
7067}
7068
7069JoystickInputMapper::~JoystickInputMapper() {
7070}
7071
7072uint32_t JoystickInputMapper::getSources() {
7073 return AINPUT_SOURCE_JOYSTICK;
7074}
7075
7076void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7077 InputMapper::populateDeviceInfo(info);
7078
7079 for (size_t i = 0; i < mAxes.size(); i++) {
7080 const Axis& axis = mAxes.valueAt(i);
7081 addMotionRange(axis.axisInfo.axis, axis, info);
7082
7083 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7084 addMotionRange(axis.axisInfo.highAxis, axis, info);
7085
7086 }
7087 }
7088}
7089
7090void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7091 InputDeviceInfo* info) {
7092 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7093 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7094 /* In order to ease the transition for developers from using the old axes
7095 * to the newer, more semantically correct axes, we'll continue to register
7096 * the old axes as duplicates of their corresponding new ones. */
7097 int32_t compatAxis = getCompatAxis(axisId);
7098 if (compatAxis >= 0) {
7099 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7100 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7101 }
7102}
7103
7104/* A mapping from axes the joystick actually has to the axes that should be
7105 * artificially created for compatibility purposes.
7106 * Returns -1 if no compatibility axis is needed. */
7107int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7108 switch(axis) {
7109 case AMOTION_EVENT_AXIS_LTRIGGER:
7110 return AMOTION_EVENT_AXIS_BRAKE;
7111 case AMOTION_EVENT_AXIS_RTRIGGER:
7112 return AMOTION_EVENT_AXIS_GAS;
7113 }
7114 return -1;
7115}
7116
7117void JoystickInputMapper::dump(String8& dump) {
7118 dump.append(INDENT2 "Joystick Input Mapper:\n");
7119
7120 dump.append(INDENT3 "Axes:\n");
7121 size_t numAxes = mAxes.size();
7122 for (size_t i = 0; i < numAxes; i++) {
7123 const Axis& axis = mAxes.valueAt(i);
7124 const char* label = getAxisLabel(axis.axisInfo.axis);
7125 if (label) {
7126 dump.appendFormat(INDENT4 "%s", label);
7127 } else {
7128 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7129 }
7130 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7131 label = getAxisLabel(axis.axisInfo.highAxis);
7132 if (label) {
7133 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7134 } else {
7135 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7136 axis.axisInfo.splitValue);
7137 }
7138 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7139 dump.append(" (invert)");
7140 }
7141
7142 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7143 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7144 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7145 "highScale=%0.5f, highOffset=%0.5f\n",
7146 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7147 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7148 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7149 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7150 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7151 }
7152}
7153
7154void JoystickInputMapper::configure(nsecs_t when,
7155 const InputReaderConfiguration* config, uint32_t changes) {
7156 InputMapper::configure(when, config, changes);
7157
7158 if (!changes) { // first time only
7159 // Collect all axes.
7160 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7161 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7162 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7163 continue; // axis must be claimed by a different device
7164 }
7165
7166 RawAbsoluteAxisInfo rawAxisInfo;
7167 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7168 if (rawAxisInfo.valid) {
7169 // Map axis.
7170 AxisInfo axisInfo;
7171 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7172 if (!explicitlyMapped) {
7173 // Axis is not explicitly mapped, will choose a generic axis later.
7174 axisInfo.mode = AxisInfo::MODE_NORMAL;
7175 axisInfo.axis = -1;
7176 }
7177
7178 // Apply flat override.
7179 int32_t rawFlat = axisInfo.flatOverride < 0
7180 ? rawAxisInfo.flat : axisInfo.flatOverride;
7181
7182 // Calculate scaling factors and limits.
7183 Axis axis;
7184 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7185 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7186 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7187 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7188 scale, 0.0f, highScale, 0.0f,
7189 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7190 rawAxisInfo.resolution * scale);
7191 } else if (isCenteredAxis(axisInfo.axis)) {
7192 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7193 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7194 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7195 scale, offset, scale, offset,
7196 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7197 rawAxisInfo.resolution * scale);
7198 } else {
7199 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7200 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7201 scale, 0.0f, scale, 0.0f,
7202 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7203 rawAxisInfo.resolution * scale);
7204 }
7205
7206 // To eliminate noise while the joystick is at rest, filter out small variations
7207 // in axis values up front.
7208 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7209
7210 mAxes.add(abs, axis);
7211 }
7212 }
7213
7214 // If there are too many axes, start dropping them.
7215 // Prefer to keep explicitly mapped axes.
7216 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007217 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007218 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7219 pruneAxes(true);
7220 pruneAxes(false);
7221 }
7222
7223 // Assign generic axis ids to remaining axes.
7224 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7225 size_t numAxes = mAxes.size();
7226 for (size_t i = 0; i < numAxes; i++) {
7227 Axis& axis = mAxes.editValueAt(i);
7228 if (axis.axisInfo.axis < 0) {
7229 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7230 && haveAxis(nextGenericAxisId)) {
7231 nextGenericAxisId += 1;
7232 }
7233
7234 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7235 axis.axisInfo.axis = nextGenericAxisId;
7236 nextGenericAxisId += 1;
7237 } else {
7238 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7239 "have already been assigned to other axes.",
7240 getDeviceName().string(), mAxes.keyAt(i));
7241 mAxes.removeItemsAt(i--);
7242 numAxes -= 1;
7243 }
7244 }
7245 }
7246 }
7247}
7248
7249bool JoystickInputMapper::haveAxis(int32_t axisId) {
7250 size_t numAxes = mAxes.size();
7251 for (size_t i = 0; i < numAxes; i++) {
7252 const Axis& axis = mAxes.valueAt(i);
7253 if (axis.axisInfo.axis == axisId
7254 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7255 && axis.axisInfo.highAxis == axisId)) {
7256 return true;
7257 }
7258 }
7259 return false;
7260}
7261
7262void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7263 size_t i = mAxes.size();
7264 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7265 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7266 continue;
7267 }
7268 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7269 getDeviceName().string(), mAxes.keyAt(i));
7270 mAxes.removeItemsAt(i);
7271 }
7272}
7273
7274bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7275 switch (axis) {
7276 case AMOTION_EVENT_AXIS_X:
7277 case AMOTION_EVENT_AXIS_Y:
7278 case AMOTION_EVENT_AXIS_Z:
7279 case AMOTION_EVENT_AXIS_RX:
7280 case AMOTION_EVENT_AXIS_RY:
7281 case AMOTION_EVENT_AXIS_RZ:
7282 case AMOTION_EVENT_AXIS_HAT_X:
7283 case AMOTION_EVENT_AXIS_HAT_Y:
7284 case AMOTION_EVENT_AXIS_ORIENTATION:
7285 case AMOTION_EVENT_AXIS_RUDDER:
7286 case AMOTION_EVENT_AXIS_WHEEL:
7287 return true;
7288 default:
7289 return false;
7290 }
7291}
7292
7293void JoystickInputMapper::reset(nsecs_t when) {
7294 // Recenter all axes.
7295 size_t numAxes = mAxes.size();
7296 for (size_t i = 0; i < numAxes; i++) {
7297 Axis& axis = mAxes.editValueAt(i);
7298 axis.resetValue();
7299 }
7300
7301 InputMapper::reset(when);
7302}
7303
7304void JoystickInputMapper::process(const RawEvent* rawEvent) {
7305 switch (rawEvent->type) {
7306 case EV_ABS: {
7307 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7308 if (index >= 0) {
7309 Axis& axis = mAxes.editValueAt(index);
7310 float newValue, highNewValue;
7311 switch (axis.axisInfo.mode) {
7312 case AxisInfo::MODE_INVERT:
7313 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7314 * axis.scale + axis.offset;
7315 highNewValue = 0.0f;
7316 break;
7317 case AxisInfo::MODE_SPLIT:
7318 if (rawEvent->value < axis.axisInfo.splitValue) {
7319 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7320 * axis.scale + axis.offset;
7321 highNewValue = 0.0f;
7322 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7323 newValue = 0.0f;
7324 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7325 * axis.highScale + axis.highOffset;
7326 } else {
7327 newValue = 0.0f;
7328 highNewValue = 0.0f;
7329 }
7330 break;
7331 default:
7332 newValue = rawEvent->value * axis.scale + axis.offset;
7333 highNewValue = 0.0f;
7334 break;
7335 }
7336 axis.newValue = newValue;
7337 axis.highNewValue = highNewValue;
7338 }
7339 break;
7340 }
7341
7342 case EV_SYN:
7343 switch (rawEvent->code) {
7344 case SYN_REPORT:
7345 sync(rawEvent->when, false /*force*/);
7346 break;
7347 }
7348 break;
7349 }
7350}
7351
7352void JoystickInputMapper::sync(nsecs_t when, bool force) {
7353 if (!filterAxes(force)) {
7354 return;
7355 }
7356
7357 int32_t metaState = mContext->getGlobalMetaState();
7358 int32_t buttonState = 0;
7359
7360 PointerProperties pointerProperties;
7361 pointerProperties.clear();
7362 pointerProperties.id = 0;
7363 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7364
7365 PointerCoords pointerCoords;
7366 pointerCoords.clear();
7367
7368 size_t numAxes = mAxes.size();
7369 for (size_t i = 0; i < numAxes; i++) {
7370 const Axis& axis = mAxes.valueAt(i);
7371 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7372 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7373 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7374 axis.highCurrentValue);
7375 }
7376 }
7377
7378 // Moving a joystick axis should not wake the device because joysticks can
7379 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7380 // button will likely wake the device.
7381 // TODO: Use the input device configuration to control this behavior more finely.
7382 uint32_t policyFlags = 0;
7383
7384 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007385 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007386 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7387 getListener()->notifyMotion(&args);
7388}
7389
7390void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7391 int32_t axis, float value) {
7392 pointerCoords->setAxisValue(axis, value);
7393 /* In order to ease the transition for developers from using the old axes
7394 * to the newer, more semantically correct axes, we'll continue to produce
7395 * values for the old axes as mirrors of the value of their corresponding
7396 * new axes. */
7397 int32_t compatAxis = getCompatAxis(axis);
7398 if (compatAxis >= 0) {
7399 pointerCoords->setAxisValue(compatAxis, value);
7400 }
7401}
7402
7403bool JoystickInputMapper::filterAxes(bool force) {
7404 bool atLeastOneSignificantChange = force;
7405 size_t numAxes = mAxes.size();
7406 for (size_t i = 0; i < numAxes; i++) {
7407 Axis& axis = mAxes.editValueAt(i);
7408 if (force || hasValueChangedSignificantly(axis.filter,
7409 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7410 axis.currentValue = axis.newValue;
7411 atLeastOneSignificantChange = true;
7412 }
7413 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7414 if (force || hasValueChangedSignificantly(axis.filter,
7415 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7416 axis.highCurrentValue = axis.highNewValue;
7417 atLeastOneSignificantChange = true;
7418 }
7419 }
7420 }
7421 return atLeastOneSignificantChange;
7422}
7423
7424bool JoystickInputMapper::hasValueChangedSignificantly(
7425 float filter, float newValue, float currentValue, float min, float max) {
7426 if (newValue != currentValue) {
7427 // Filter out small changes in value unless the value is converging on the axis
7428 // bounds or center point. This is intended to reduce the amount of information
7429 // sent to applications by particularly noisy joysticks (such as PS3).
7430 if (fabs(newValue - currentValue) > filter
7431 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7432 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7433 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7434 return true;
7435 }
7436 }
7437 return false;
7438}
7439
7440bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7441 float filter, float newValue, float currentValue, float thresholdValue) {
7442 float newDistance = fabs(newValue - thresholdValue);
7443 if (newDistance < filter) {
7444 float oldDistance = fabs(currentValue - thresholdValue);
7445 if (newDistance < oldDistance) {
7446 return true;
7447 }
7448 }
7449 return false;
7450}
7451
7452} // namespace android